java check a input

2012-11-24 10:24 pm
java check a input that out of range and non integer

回答 (2)

2012-11-24 11:32 pm
✔ 最佳答案
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class play {
public static void main (String[] arg){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
while (input != null){ // reading the words
if (input.equals("1")||input.equals("2")||input.equals("3")||input.equals("4")||input.equals("5")||input.equals("9")){
//input that is good
break;//break while loop when input matches condition
}
else{}//input that is bad or alphabets

}
}catch (IOException e) {System.out.println("error read file");}
}
}
2012-11-25 2:16 am
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Y7012112400177 {
public static void main(String[] args) {
Y7012112400177 app = new Y7012112400177();

boolean quit = false;
while (!quit) {
System.out.println("?");
Scanner scan = new Scanner(System.in);
String command = scan.nextLine();

if (app.isValidCommand(command)) {
System.out.println("The input is valid.");
quit = true;
}
else {
System.out.println("The input is invalid, try again.");
}
}

System.exit(0);
}

public boolean isValidCommand(String command) {
Matcher m = Pattern.compile("^[1-5|9]$").matcher(command);
return m.find();
}
}


收錄日期: 2021-04-13 19:07:38
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20121124000051KK00177

檢視 Wayback Machine 備份