여기에는 고객의 성과 이름에 대한 문자열 입력에 대한 간단한 try/catch 문이 있습니다. 그러나 숫자가 입력되었거나 - 다른 텍스트가 아닌 다른 문자가 사용자에 의해 입력되는 경우 예외가 필요합니다 (이름에는 텍스트 만 포함되기 때문에). 문제는 문자열뿐만 아니라 문자도 허용한다는 것입니다. 사용자가 텍스트 이외의 내용을 입력하면 catch를 실행하려면 어떻게해야합니까?nextLine 입력으로 try/catch 문
ArrayList< String>arrayList=new ArrayList<String>();
arrayList.add("?");
//add other String
String input ="some text";
for(int i=0;i<arrayList.size();i++){
if(input.contains(arrayList.get(i)))
input=input.replace(arrayList.get(i), "");
}
하거나 교체 부분을 제거하고 조건이 true 인 경우 물어 얻을 수 :
public void Customer()
{
//Variables for Customer method
String firstName;
String lastName;
int customerNumber;
boolean end = false;
/* Reads input from user
* Stores customers first and last name into the variable name
*/
while(end == false)
{
try
{
System.out.println("Enter customers full name");
firstName = input.nextLine();
System.out.println("Enter customers last name");
lastName = input.nextLine();
end = true;
}
catch (InputMismatchException ime)
{
end = false;
System.out.println("Invalid input. You must enter the customers name. Please try again: ");
input.next();
}
}
}
문자열에서 숫자를 찾으려면 정규식을 사용하십시오. –
if 문에서 사용자 입력을 위해 (정규식을 사용하여) 유효성 검사기를 만들 필요가 있습니다. else 문에서 사용자 입력을 확인하면 InputMismatchException 예외를 throw 할 수 있습니다. 그래서 try-catch는 내부에 다른 if를 시도해야한다. 다른 경우에는 예외가 발생합니다. –
예외는 프로그램의 흐름을 제어하는 것이 아니며 조건문을 사용하십시오. –