我有一个小代码:
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.println("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
++i;
cisla = cisla + cislo;
}
catch(InputMismatchException exception){
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
但总是当我运行它并键入其他charakters然后int,程序崩溃并没有运行“catch”。 该程序的目标是当另一个int输入显示错误消息时,不要添加到int i并为用户添加另一个选项来添加整数。
答案 0 :(得分:0)
您需要抓住NumberFormatException
而不是InputMismatchException
,如此:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.print("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
i++;
cisla = cisla + cislo;
} catch(NumberFormatException exception) {
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
试试here!
答案 1 :(得分:0)
你抓住了错误的例外。方法parseInt(String s)
会引发NumberFormatException
而非 a InputMismatchException
。将您的catch子句更改为catch(NumberFormatException exception)
。
答案 2 :(得分:0)
import java.util。*; 公共课演示{
public static void main (String []args ){
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.println("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
++i;
cisla = cisla + cislo;
}
catch(InputMismatchException exception){
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
我不确定它崩溃的原因但这段代码有效。我想你可能忘了import.java。*;