检查数值是否是有效整数

时间:2016-01-06 15:14:02

标签: java

我在下面写了一些基本代码,这些代码允许我为他们玩过的游戏获取用户输入。用户将输入如下“GameName:Score:Time”。一旦用户输入了该I,则将时间和分数转换为整数,因为它们被输入到字符串中。从这里我需要确保用户输入了一个有效的整数,我不知道如何做到这一点。

    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 个答案:

答案 0 :(得分: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];

最后,最简单的方法是执行此操作,并且对当前代码进行最少的更改,只需捕获NumberFormatException parseInt抛出的try { score = Integer.parseInt(elements[1].trim()); } catch(NumberFormatException ex) { //invalid input, emit error or exit }

  encrypted.append( vig2[longPass.charAt(i)][file.charAt(i)]);

答案 1 :(得分:0)

我这样做的方法是将解析放在NumberFormat时钟中,并捕获 try{ score = Integer.parseInt(elements[1].trim()); } catch(NumberFormatException e){ //Deal with it not being an integer here } 异常,就像这样。

<?php

require('config.php');

if(isset($_POST['submit'])) {

  $uname = mysqli_real_escape_string($con, $_POST['uname']);
  $pass = mysqli_real_escape_string($con, $_POST['pass']);

  $sql = mysqli_query($con, "SELECT * FROM users WHERE uname = '$uname' AND pass = '$pass'");
if (mysqli_num_rows($sql) > 0) {
  echo "You are now logged in.";
  exit();
}

} else {

  $form = <<<EOT
  <form action="login.php" method="POST">
  Username: <input type="text" name="uname" /></br>
  Password: <input type="password" name="pass" /></br>
  <input type="submit" name="submit" value="Log in" />
  </form>
EOT;
  echo $form;
}
?>

您也可以使用正则表达式执行此操作,但这对我来说似乎最直接。