我在下面编写了一些基本代码,可以让我获得用户对他们玩过的游戏的输入。用户将输入如下“游戏名称:分数:时间”。一旦用户输入了这个,我就将时间和分数转换为整数,因为它们被输入到一个字符串中。由此我需要确保用户输入了一个有效的整数,我不确定如何做到这一点。
import java.util.Scanner;
import java.io.IOException;
import java.text.ParseException;
public class REQ2
{
public static void main (String[] args) throws ParseException
{
String playername;
String line;
String[] list = new String[100];
int count = 0;
int score;
int time;
int InvalidEntries;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
playername = sc.nextLine();
if(playername.equals(""))
{
System.out.println("Player name was not entered please try again");
System.exit(0);
}
System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (count < 100){
line = sc.nextLine();
if(line.equals("quit")){
break;
}
if(!(line.contains(":"))){
System.out.println("Please enter achivements with the proper \":\" sepration\n");
break;
}
list[count]=line;
System.out.println("list[count]" + list[count]);
count++;
for (int i=0; i<count; i++){
line=list[i];
String[] elements =line.split(":");
if (elements.length !=3){
System.out.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
break;
}
score = Integer.parseInt(elements[1].trim());
time=Integer.parseInt(elements[2].trim());
}
}
}}
最佳答案
最强大和灵活的方法可能是使用正则表达式:
final Pattern inputPattern = Pattern.compile("^(?<gameName>[^:]++):(?<score>\\d++):(?<time>\\d++)$")
final String line = sc.nextLine();
final Matcher matcher = inputPattern.matcher(line);
if(!matcher.matches()) {
throw new IllegalArgumentException("Invalid input") //or whatever
}
final String gameName = matcher.group("gameName");
final int score = Integer.parseInt(matcher.group("score"));
final int time = Integer.parseInt(matcher.group("time"));
这样您的正则表达式既验证又解析您的输入。
对于 MessageFormat
也是可能的:
final MessageFormat inputFormat = new MessageFormat("{0}:{1,number,integer}:{2,number,integer}")
final String line = sc.nextLine();
//throws an exception if input is invalid - possibly catch and report
final Object[] input = inputFormat.parse(line);
final String gameName = input[0];
//will be a long
final int score = (int) input[1];
final int time = (int) input[2];
最后,最简单的方法是捕获 parseInt
抛出的 NumberFormatException
,并且对您当前的代码进行最少的更改:
try {
score = Integer.parseInt(elements[1].trim());
} catch(NumberFormatException ex) {
//invalid input, emit error or exit
}
关于java - 检查数值是否为有效整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34636475/