我对try和catch有意见。我的程序是插入三个不同的字符串名称、地址和电话号码,然后使用toString方法将这三个字符串转换为一个字符串。
无论何时编写错误的选择(字符串或其他数据类型),然后捕获工作无限次,我都会遇到异常处理问题。
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
ArrayList<String> arraylist= new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();
int choice;
String phoneNumber;
String name,address;
String format="Empty";
int x=1;
int flag=0;
do
{
try
{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice=input.nextInt();
switch (choice)
{
case 1:
{
System.out.println("Enter name ");
name=input.next();
System.out.println("Enter phone number");
phoneNumber=input.next();
System.out.println("Enter address");
address=input.next();
format=FormatObject.toString(phoneNumber, name, address);
arraylist.add(format);
flag++;
}
break;
case 2:
{
System.out.println("Name Phone number Address");
System.out.println();
for(int i=0;i<flag;i++)
{
System.out.println(arraylist.get(i));
}
}
break;
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice");`
}while(x==1);
}
}
//The format class ...//returns format for string发布于 2016-02-15 10:38:34
您的try和catch与循环无关,也与问题无关。
while(x==1)是您测试的内容,但是您从不更改x的值,因此它始终保持为1,因此上面的检查将始终返回true。
发布于 2016-02-15 10:54:08
我想我现在知道你到底有什么问题了。
简单地在代码的开头添加input.nextLine()将停止输入运行的混乱。
boolean wrongInput = false;
do {
try {
if (wrongInput) {
input.nextLine();
wrongInput = false;
}
System.out.println("Enter your choice");
[...]
} catch (...) {
wrongInput = true;
}应该能起作用。但是,请注意,我注意到您的程序中有两个错误(这可能是因为我没有您的CreateFormat类),(a)我不能向地址添加一个数字,(b)没有停止循环的选项(我强烈建议--在这里,只设置x= -1或类似的东西,最好使用boolean结束循环)。
https://stackoverflow.com/questions/35407076
复制相似问题