2016-01-06 66 views
1

我已經寫了一些基本的代碼,下面讓我爲他們玩過的遊戲獲取用戶輸入。用戶將輸入如下「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()); 


     }   
    } 
}} 
+2

可能的重複[什麼是檢查是否一個字符串表示一個整數在Java中的最佳方法?](http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-到看到-IF-A-字符串表示-的整數式-java的) – ericbn

回答

4

最強大,最靈活的方式可能是用正則表達式:

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]; 

最後,最簡單的方法來做到這一點,並以最小更改當前的代碼只是爲了趕上NumberFormatExceptionparseInt拋出:

try { 
    score = Integer.parseInt(elements[1].trim()); 
} catch(NumberFormatException ex) { 
    //invalid input, emit error or exit 
} 
0

我會這樣做的方式是解析在try時鐘,並捕獲NumberFormat異常,像這樣。

 try{ 
      score = Integer.parseInt(elements[1].trim()); 
     } 
     catch(NumberFormatException e){ 
      //Deal with it not being an integer here 
     } 

你也可以用正則表達式來做到這一點,但這是對我來說最直接的方式。