有 Java 编程相关的问题?

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

Java:Infinite循环hasnetint()

我试着寻找不同的来源来解决问题,我的老师不太擅长解释,所以有人解释了如何避免无限循环,因为hasneaxt阻塞了进一步的东西idk。如果有人告诉我该怎么做,我会非常感激的

import java.util.*;

public class MergeSort{
  public static void main(String args[]) throws Exception{
    //declaring variables, files, and arrays
    Scanner scan = new Scanner(System.in);
    File file1 = new File("num1.txt");
    File file2 = new File("num2.txt");
    ArrayList<Integer> arr1 = new ArrayList<>();
    ArrayList<Integer> arr2 = new ArrayList<>();

    //asking the amount of numbers
    System.out.print("How many numbers from file 1: ");
    int input1 = scan.nextInt();
    System.out.print("How many numbers from file 2: ");
    int input2 = scan.nextInt();

    // file 1
    try (Scanner s = new Scanner(file1)) {
      int i=0;
      while (s.hasNext()) {
        if (s.hasNextInt()) {
          if (i <= input1) {
            arr1.add(s.nextInt());
          }
        }
        i++;
      }
      System.out.println("i = " + i);
    } catch(Exception e) {
      System.out.println("Error");
    }
  }
}

共 (0) 个答案