2015-09-05 163 views
-1

所以我做Usacogate的貪婪送禮者和使用while循環來檢查,如果該文件中的下一行是空或不是,具體!= NULL在Java while循環不工作

while((tempName = sc.nextLine()) != null){ 

問題是,一旦它讀取最後一行並返回到頂部以檢查是否存在下一行,Java會拋出NoSuchElementException,而不是看到沒有行並退出循環。所有其他部分都可以工作,並且代碼返回正確的答案。

我該如何解決這個問題?

public static void main(String [] args) throws IOException { 
     Scanner sc = new Scanner(new File("gift1.in")); 
     int n = sc.nextInt(); 
     System.out.printf("n is: %d\n", n); 

     String[] names = new String[10]; 
     sc.nextLine(); 
     int[] account = new int[10]; 
for (int i = 0; i < n; i++) { 
      names[i]=sc.nextLine().trim(); 
      System.out.printf("current Name is: %s\n", names[i]); 

      account[i]=0; 
} 
String tempName; 
while((tempName = sc.nextLine()) != null){ 
    System.out.printf("tempName is: %s\n", tempName.trim()); 

    int indexDummy = -1; 
    for (int j=0; (j< names.length); j++){ 
      if (names[j].equals(tempName)) { 
       indexDummy = j; 
       break; 
      } 
    } 
    System.out.printf("indexDummy is: %d\n", indexDummy); 


    String nextLine = sc.nextLine(); 
    System.out.printf("Next line is: %s\n", nextLine); 
    StringTokenizer st = new StringTokenizer(nextLine); 
    int int1 = Integer.parseInt(st.nextToken());  
    int int2 = Integer.parseInt(st.nextToken()); 

    if(int2 == 0) { 
     for(int i=0; i<n;i++){ 
      System.out.println(names[i]+" "+account[i]); 
     } 
     continue; 
    } 
    int quotient = int1/int2; 
    int tempNum = int2 * quotient; 
    int remainder = int1-tempNum; 
    System.out.printf("quotient and remainder are: %d %d\n", quotient, remainder); 


    account[indexDummy]=account[indexDummy]+remainder-int1;//parsing the two numbers 
    System.out.println(indexDummy); 
    System.out.println(names[indexDummy]+" has "+account[indexDummy]); 
    for (int k=0;k < int2 ;k++){ 
     tempName = sc.nextLine(); 
     for (int j=0; j< names.length; j++){ 
       if (names[j].equals(tempName.trim())) { 
        //indexDummy2 = j; 
        account[j] =account[j]+ quotient; 
        System.out.printf("%s has balance %d\n", names[j], account[j]); 
        break; 
       } 

      } //sort out the output   
     } 

    //tempName = sc.next();    
} 

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("gift1.out"))); 
for(int i=0; i<n;i++){ 
    out.println(names[i]+" "+account[i]); 
} 
for(int i=0; i<n;i++){ 
    System.out.println(names[i]+" "+account[i]); 
} 
out.close();         
System.exit(0); 
} 
} 

回答

2

您可以檢查是否存在與Scanner.hasNextLine()更多的投入。

while(sc.hasNextLine() && (tempName = sc.nextLine()) != null) { 

或者:

while(sc.hasNextLine()) { 
    tempName = sc.nextLine(); //if you know it's not going to have a null as input 
2

這是你應該如何使用掃描儀

while (scanner.hasNextLine()) { 
    String line = scanner.nextLine(); 
} 

,你可以跳過空校驗,因爲nextLine()返回一個非空目的。