英文:
using try catch in a while loop (java)
问题
import java.util.InputMismatchException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args){
number();
}
public static int number() {
System.out.print("Enter a number: ");
Scanner readLine = new Scanner(System.in);
boolean isInteger = false;
while (!isInteger) {
try {
int numbers = readLine.nextInt();
System.out.println(numbers);
isInteger = true;
} catch (InputMismatchException e) {
System.err.println("Not a valid input. Error: " + e.getMessage());
}
}
return 0;
}
}
英文:
I wanted to write a simple program that asks for a number, if the user inputs a number it will end, otherwise it will print an error and ask again for a number. The problem is that my program just keeps printing the error message ("Not a valid input. Error :null") and never asks for a number again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args){
number();
}
public static int number() {
System.out.print("Enter a number: ");
Scanner readLine = new Scanner(System.in);
boolean isInteger = false;
while (!isInteger) {
try {
int numbers = readLine.nextInt();
System.out.println(numbers);
isInteger = true;
} catch (InputMismatchException e) {
System.err.println("Not a valid input. Error :" + e.getMessage());
}
}
return 0;
}
}
答案1
得分: 1
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
int number = sc.nextInt();
System.out.println(number);
} else {
System.err.println("不是有效的输入。错误:" + sc.next());
}
}
英文:
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
int number = sc.nextInt();
System.out.println(number);
} else {
System.err.println("Not a valid input. Error :" + sc.next());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论