我已經寫了一些基本的代碼,下面讓我爲他們玩過的遊戲獲取用戶輸入。用戶將輸入如下「GameName:Score:Time」。一旦用戶輸入了這個信息,我會將時間和分數轉換成整數,因爲它們被輸入到一個字符串中。從這我需要確保用戶輸入一個有效的整數,我不知道如何做到這一點。檢查數值是否爲有效整數
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());
}
}
}}
可能的重複[什麼是檢查是否一個字符串表示一個整數在Java中的最佳方法?](http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-到看到-IF-A-字符串表示-的整數式-java的) – ericbn