这是我的主要方法,我需要一种方法来检查输入是否不是整数,因为当它们是字符串时我可以输入一个值,例如“12345”,它仍然是一个字符串。虽然我不确定如何区分字符串,可以是任何东西,只是一个整数?
import java.math.*;
import java.text.DecimalFormat;
import java.io.*;
import java.util.*;
public class labBookFortyEight
{
public static void main(String[] args)
{
String make = null;
String model = null;
String color = null;
String lNum = null;
int min = 0;
int quarters = 0;
Scanner myInput = new Scanner(System.in);
while(make == null && model == null && color == null && lNum == null && min == 0 && quarters == 0)
{
System.out.println("Please enter make, model, color, lisense num and mins spent ");
if (myInput.hasNext()) {
System.out.println("you entered make");
make = myInput.nextLine();
}
if(myInput.hasNext()){
System.out.println("you entered model");
model = myInput.nextLine();
}
if (myInput.hasNext()) {
System.out.println("you entered color");
color = myInput.nextLine();
}
if (myInput.hasNext()) {
System.out.println("you entered lNum");
lNum = myInput.nextLine();
}
if(myInput.hasNextInt()){
System.out.println("you entered mins spent");
min = myInput.nextInt();
myInput.nextLine(); //consumes newline char from nextLine
}
if(myInput.hasNextInt()){
System.out.println("you enter quarters entered");
quarters = myInput.nextInt();
}
else if (myInput.hasNext()) {
System.out.println("Please enter a proper value");
myInput.next();
} else {
System.err.println("No more input");
System.exit(1);
}
}
System.out.println("the values you entered are " + make + " " + model + " " + color + " " + lNum + " " + min);
答案 0 :(得分:2)
对于这类事情,您可能需要查看正则表达式或正则表达式,您可以检查它是否匹配。
String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
答案 1 :(得分:1)
使用正则表达式:
if (str.matches("\\d+"))
正则表达式\d+
表示“一个或多个数字”,如果整个字符串与正则表达式匹配,则matches()
仅返回true。