想用java写一个无限输入直到输入0的时候终止输入的循环,当我输入0的时候出现了NoSuchElementException的异常。
第一次见,以下是我的代码
import java.util.Scanner;
import java.util.*;
public class Educode {
// 计算 GCD
public static int gcd(int a, int b) {
return b==0?a:gcd(b,a%b);
}
public static void main(String[] args) {
while (true) {
Scanner sc = new Scanner(System.in);
int[]nums=new int[101];
int n;
for(int k=0;(n = sc.nextInt()) != 0;k++) {
nums[k]=n;
double G=0;
for(int i=1;i<n;i++)
for(int j=i+1;j<=n;j++)
G+=gcd(i,j);
System.out.printf("%.0f\n",G);
}
sc.close();
}
}
}
//idea给我定位的位置是这个for循环的sc.nextInt()出问题了,不知道问题是什么。不懂修改
引用 皆我百晓生 小程序回复内容作答:
出现NoSuchElementException异常是因为在每次循环开始时都创建了一个新的Scanner对象,而在循环内部并没有关闭之前创建的Scanner对象。这会导致在输入0后重新开始循环时,新创建的Scanner对象会尝试读取输入流中的下一个整数,但是此时输入流已经到达末尾,因此抛出NoSuchElementException异常。
解决这个问题的方法是将Scanner对象的创建移动到循环外部,并且在循环内部只使用nextInt()方法来读取输入,而不是重新创建Scanner对象。修改后的代码如下:
import java.util.Scanner;
public class Educode {
// 计算 GCD
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] nums = new int[101];
int n;
while ((n = sc.nextInt()) != 0) {
for (int k = 0; k < n; k++) {
nums[k] = n;
double G = 0;
for (int i = 1; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
G += gcd(i, j);
}
}
System.out.printf("%.0f\n", G);
}
}
sc.close();
}
}
这样修改后,程序会在输入0后终止循环,不再抛出NoSuchElementException异常。
【以下回答由 GPT 生成】
import java.util.Scanner;
public class InfiniteInput {
// 计算 GCD
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] nums = new int[101];
int n;
while (sc.hasNextInt() && (n = sc.nextInt()) != 0) {
double G = 0;
for (int i = 1; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
G += gcd(i, j);
}
}
System.out.printf("%.0f\n", G);
}
sc.close();
}
}
在修改后的代码中,我将 Scanner
对象的创建放在了循环外部以避免重复创建。使用 sc.hasNextInt()
来检查是否还有输入值,然后通过 sc.nextInt()
来获取输入值。同时,我还将 for
循环中的部分代码移出来,确保每次循环只输出一次结果。
这样,当输入为0时,循环会终止,避免抛出 NoSuchElementException
异常。
【相关推荐】