有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

!= java while循环不工作时为空

所以我在做Usacogate的贪婪送礼者,并使用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); 
}
}

共 (1) 个答案

  1. # 1 楼答案

    这就是你应该如何使用扫描仪

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

    您可以安全地跳过null检查,因为nextLine()返回一个非null对象