I am having a problem with try
and catch
. My program is to insert three different strings name, address and phone number then I convert these three in to a single String using toString
method.
I have problem with exception handling whenever I write a wrong choice (String or other data type) then catch works infinity times.
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
Your try
and catch
are not related to a loop, nor to your problem.
while(x==1)
is what you test on, yet you never change the value of x
, so it will always remain 1, and thus the above check will always return true.
I think I now know what your problem actually is.
Simply adding input.nextLine()
at the very beginning at your code will stop the input running havoc.
boolean wrongInput = false;
do {
try {
if (wrongInput) {
input.nextLine();
wrongInput = false;
}
System.out.println("Enter your choice");
[...]
} catch (...) {
wrongInput = true;
}
should do the trick. However, please note that I noticed two errors in your program (which might be because I do not have the CreateFormat
class of yours), (a) I cannot add a number to the address and (b) there is no option to stop the loop (which I strongly recommend - where you simply set x = -1 or something similar, better use a boolean
to end the loop though).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.