2015-09-05 67 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()返回一个非空目的。