java中如何实现用户输入错误,从新输入
就拿这个例子来说吧。
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static int a=0;
public static void main(String[] args)
{
while(true)
{
try
{
Scanner input = new Scanner(System.in);
a=input.nextInt();
return;
}
//这个地方怎么实现IO异常
catch(Exception e)
{
System.out.println("erro is a,请从新输入:");
}
}
//在while后面的语句怎么都会报错?
System.out.print(a);
Test.prints();
a=a+0;
}
public static void prints()
{
System.out.println(a);
}
}
补充:我问的是while后面的语句为什么会报错,怎么实现IO异常,也就是说把Exception变成IOException、、就这两个问题
追问:我想要的是比如说输入“ss“字符,提示你输入不合法,请输入整数while语句没错,是while后面的会报错,我输的那三条语句都会报错。。但是又没错误提示。。。异常都不是关键,关键是这里会报错
//在while后面的语句怎么都会报错?
System.out.print(a);
Test.prints();
a=a+0;no suggestionsav ailable怎么还是不能实现输入错误,再次输入。。。我加分!你搞定
答案:你试试我这个看是不是你想要的?
public static int a = 0;
public static void main(String[] args) {
while (true) {
try {
a = getStr();
if (-1 == a) {
throw new IOException("请输入大于-1的数");
}else{
break;
}
}
// 这个地方怎么实现IO异常
catch (IOException e) {
System.out.println("erro is a,请从新输入:");
}
}
// 在while后面的语句怎么都会报错?
System.out.print(a);
Test.prints();
a = a + 0;
}
public static int getStr(){
Scanner input = new Scanner(System.in);
a = input.nextInt();
return a;
}
public static void prints() {
System.out.println(a);
}
其他:结果会映出错误的字样 然后要求用户从新输入 ConsoleIO里面有以下: String x 为了让程序更有结构化,JAVA不支持GOTO语句,所以不能实现VB的On error goto 你要捕获IOException吗?
catch(IOException e) 这样就可以了
但是这个程序没有会产生IOException的语句
非要捕获的话自己throw一个
try
{
Scanner input = new Scanner(System.in);
a=input.nextInt();
throw new IOException();
return;
}
//这个地方怎么实现IO异常
catch(IOException e)
{
System.out.println("erro is a,请从新输入:");
}
while语句报错是因为你上面已经return了,下面的代码执行不到
Scanner input = new Scanner(System.in);
a=input.nextInt();
return; //你这里直接return了
可以设个标志boolean flag=true;
while(flag){
flag=false;//然后在while循环里设成false,退出循环
} public class Test {
public static int a=0;
public static void main(String[] args)
{
while(true)
{
try
{
Scanner input = new Scanner(System.in);
a=input.nextInt();
if(-1==a){
throw new IOException("请输入大于-1的数");
}else{
return;
}
}
//这个地方怎么实现IO异常
catch(IOException e)
{
System.out.println("erro is a,请从新输入:");
}
}
//在while后面的语句怎么都会报错?
System.out.print(a);
Test.prints();
a=a+0;
}
public static void prints()
{
System.out.println(a);
}
}
上一个:java要考试了。。
下一个:java接口、继承的一些问题