import java.util.*;
public class xArrays {
public static double total;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] marks = new double[5];
for (int i =0;i<5;i++){
System.out.printf("Enter your marks for course %d : ",(i+1));
try { input.nextDouble();}
catch ( InputMismatchException e ){
System.out.println("this doesn't work");
input.next();
continue;}
marks[i] = input.nextDouble();
total += marks[i];
}
我想问问标记1,然后移到标记2,但它要做的是问问标记1,我输入标记1,然后必须输入另一个数字才能继续。
答案 0 :(得分:0)
您没有将用input.nextDouble()
读取的输入分配给任何东西。并且更喜欢marks.length
来硬编码数字5。您想要类似的东西,
double[] marks = new double[5];
for (int i = 0; i < marks.length; i++) {
System.out.printf("Enter your marks for course %d : ", (i + 1));
try {
marks[i] = input.nextDouble();
} catch (InputMismatchException e) {
System.out.printf("%s is not a double.%n", input.nextLine());
i--;
continue;
}
total += marks[i];
}
答案 1 :(得分:0)
您两次致电input.nextDouble()
。将分配直接移到try-catch块中,然后删除第二个input.nextDouble()
。像这样:
for (int i = 0; i < 5; i++){
System.out.printf("Enter your marks for course %d : ", (i + 1));
try {
marks[i] = input.nextDouble();
} catch (InputMismatchException e) {
System.out.println("this doesn't work");
input.next();
continue;
}
total += marks[i];
}
答案 2 :(得分:0)
发生这种情况是因为您两次使用input.nextDouble()
。在try
中,使用类似value = input.nextDouble()
的名称,然后在catch
之后,marks[i] = value