2014-06-26 86 views
-1

我有一个问题,我试图做的地方根据一个指标,我们必须确定最好的路线,这是没有。空间除以没有。行中的字符。具有最佳比例的线被打印出来。我可以这样做,但如果出现较低比例的线条,则不会打印。但我们如何比较比率?看到这里:如何比较来自不同输入行的数字?

import java.util.Scanner; 

public class BestLine { 
    public static void main(String[] args) { 
    Scanner s = new Scanner(System.in); 
    System.out.println("Enter a line of text: "); 
    double temp = 0.0; 
    while (s.hasNextLine()) { 
     String sentence = s.nextLine(); 
     String chars = sentence.trim(); 
     int whtspacs = sentence.length() - chars.length(); 
     int totchars = chars.length(); 
     double ratio = (double) whtspacs/totchars; 

     if (ratio < temp) { 
      break; 
      } 

      temp = ratio; 

      System.out.println("Best line so far is: " + sentence); 
     } 

     System.out.println("Best Line was: ");  

     } 

} 

感谢您告诉我有关使用另一个变量,但现在再次的代码,它不工作?对不起,问一个简单的问题,但我只是不明白!再次,感谢这么多

+5

如果(比率<比率)??。你不觉得你需要保持另一个变量保持最大比率值吗? – TheLostMind

+0

它不工作? ...你能显示输出还有输入吗? – Rajan

回答

0

检查:

Scanner s = new Scanner(System.in); 
     ArrayList<Double> ratios=new ArrayList<Double>(); 
     ArrayList<String> sentences=new ArrayList<String>(); 

     System.out.println("Enter a line of text: "); 
     while (s.hasNextLine()) { 
      String sentence = s.nextLine(); 
      // Get the number of white spaces 
      int count = 0; 
      for(int i = 0; i < sentence.length(); i++) { 
       if(Character.isWhitespace(sentence.charAt(i))) count++; 
      } 
      //number of Characters 
      int totchars = sentence.length()-count; 
      //Add the ratio to our ArrayList 
      ratios.add((double) count/totchars); 
      // Add the Sentence to ArrayList 
      sentences.add(sentence); 
      if (sentence.length()==0) { 
       break; 
      } 

     } 
     //Find The best Ratio 
     int best=0; 
     for(int i=0;i<ratios.size();i++) { 
      if(ratios.get(i)<ratios.get((int)best)) 
       best=i; 
     } 
     System.out.println("Best line so far is: " + sentences.get((int)best)); 

    } 
1
//Declare outside loop 
double temp=0.0;//Or set to Max 
//Inside loop 
double ratio = (double) whtspacs/totchars; 
     if (ratio < temp) {//At first will use default value of temp 0.0 
     //OR Maybe You want if(temp < ratio) 
      break; 
     } 
//.....Your code 
temp=ratio;//after comparison with old value set current value to temp 

还有一两件事我想建议你,你应该所有的双值存储到Arraylist后那种Arraylist,你会得到最小值找到最佳线路,到目前为止,现在在你的代码会因为最后一行有比当前更多的spcaces而破坏(并且不允许添加更多行)或者反过来(当你编码时)。

+1

+1 ..解释:) – TheLostMind

+0

谢谢,但你可以再次检查代码?我添加了你说的,仍然不起作用,我觉得我很接近,但还没有那个 –

+0

_您需要在输入中添加前后空格来检查._ –

相关问题