2015-11-03 149 views
0
import java.io.*; 
import java.util.*; 

public class Hellno { 
    public static void main(String[] args) { 
     try { 
      Scanner s = new Scanner(new File("words.txt")); 
      findBiggest(s); 
      System.out.println(findBiggest(s)); 
     } catch (IOException e) { 
      System.out.println("Can't find that file"); 
     } 
    } 

    public static String findBiggest(Scanner scan) { 
     int count0 = 0; 
     int count1 = 0; 
     String srs = ""; 

     while (scan.hasNext()) { //how do i make this the longest? 
      String nsrs = scan.next(); 
      count0 = nsrs.length(); 

      if (count0 > count1) { // if the new length is bigger than what was solidified 
       count1 = count0; //new solidification of number 
       count0 = 0; // count becomes 0 to start again 
       srs = nsrs; // nsrs has been solidified as the new biggest String 
      } 

      else if (count0 <= count1) { // if the new length is smaller than what was solidified 
       count0 = 0; //then we start again with dummyCount = 0; 
      } 
     } 
     return srs;}} 

我想從文本文件中讀取,找出什麼是最長的字符串並返回該字符串。但是,這種編碼忽略了while()的所有內容,並且似乎跳轉到返回srs。爲什麼??Java初學者:忽略while循環

+0

確保該文件是在正確的位置,它在它的數據,然後嘗試設置一個斷點,而塊踩通過 –

+0

文本文件和java文件都在我的桌面上。你是這個意思嗎? –

+0

它必須是因爲它沒有讀取任何內容......將其打印到屏幕上。 – Gacci

回答

6

您在同一Scanner上撥打findBiggest兩次。第一次調用可能會找到最大的單詞並返回它,但它被忽略。第二個呼叫找不到任何詞,並且while循環沒有迭代。

只需撥打findBiggest一次。

Scanner s = new Scanner(new File("words.txt")); 
System.out.println(findBiggest(s)); 
+0

非常感謝!它現在正在工作。 –

0

需要設置在掃描儀上的分隔符

Scanner s = new Scanner(input).useDelimiter(System.getProperty("line.separator"));