如果用户输入整数而不是String,则为条件语句

时间:2017-01-23 12:16:19

标签: java

嘿伙计们我的实验室练习需要帮助。我只需要通过这个问题..我唯一的问题是,如果用户试图在String&#34中输入一个数字(特别是int),我需要确保会有异常;但** 我正在使用java.util.Scanner并将输入读作String

else if (userInput.hasNextInt())仅限我的问题

实验室练习保存为图像 enter image description here

import java.util.*;

public class Quizbee{

    public static void main (String args[]){

        Scanner sc = new Scanner(System.in);
        int score = 0;
        String userInput;
        String answerKey[] = {"A", "C", "B", "B", "C"}; //A, C, 

        String multichoice[][] = {{"A = Leonardo Da Vinci ", "B = Albert Einstein ","C = Stephen Hawking"},  //[0][0],[0][1],[0][2]
                                  {"A = 9 ", "B = 8 ", "C = 7 "},                                            //[1][0],[1][1],[1][2]
                                  {"A = Rodrigo Duterte ", "B = Ferdinand Marcos ", "C = Ninoy Aquino "},    //[2][0],[2][1],[2][2]
                                  {"A = John F. Kennedy ","B = Abraham Lincoln ","C = Ronald Reagan "},      //[3][0],[3][1],[3][2]
                                  {"A = Floyd Mayweather ","B = Manny Pacquaio ", "C = Muhammad Ali "}};     //[4][0],[4][1],[4][2]
                                      {}

        String arrQuestion[] = {"The Renaissance Man?", "prime number?","Longest-term serving Pres. of PH", 
                               "1st US President to be assassinated", "Nicknamed \"The Greatest\" in the boxing history"};


            for (int x = 0; x<arrQuestion.length; x++)
            {   
                try
                {   
                    System.out.println("\n" + (x+1)+". " + arrQuestion[x]); 
                    System.out.print(multichoice[x][0] + multichoice[x][1] + multichoice[x][2]+": "); 
                    userInput = sc.nextLine();


                    if(userInput.equalsIgnoreCase(answerKey[x]))
                    {
                        System.out.println("Correct!");
                        score = score + 1;
                    } 

                    else if(!userInput.equalsIgnoreCase(answerKey[x]))
                    {

                        if(userInput.isEmpty())
                        {
                            throw new NullPointerException();
                        }

                        else if(!userInput.equalsIgnoreCase("A") && !userInput.equalsIgnoreCase("B") && !userInput.equalsIgnoreCase("C"))
                        {
                            throw new OutOfRangeMisception();
                        }

                        else if(userInput.hasNextInt())
                        {
                            throw new InputMismatchException();
                        }

                        else 
                        {
                            System.out.println("Wrong!");   
                            score = score + 0;
                        }
                    }
                }

                catch(OutOfRangeMisception oor)
                {
                    System.out.println(oor.getMessage());       
                }

                catch(NullPointerException ex)
                {
                    System.out.println("No answer. please try again.");     
                }
                catch(InputMismatchException ex)
                {
                    System.out.println("Wrong data type.");
                }
            }
        System.out.println("\nYour score: " + score);
    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用Integer.parseInt(userInput)。如果成功,则用户输入一个整数,否则会出现异常。因此,如果它是一个整数,你可以抛出异常,否则你会抓住NumberFormatException

答案 1 :(得分:0)

您可以使用这种简单的方法来测试String是否为数字

public boolean isNumber(String text) {
    try {
        Integer.parseInt(text);
        return true;
    } catch (NumberFormatException exception) {
        return false;
    }
}

答案 2 :(得分:0)

如果您只使用Java,请使用StringUtils.isNumeric()

  

检查String是否仅包含unicode数字或空格('')。小数点不是unicode数字,返回false。

     

null将返回false。空字符串(length()= 0)将返回true。

所以在你的情况下,你会使用:

else if(StringUtils.isNumeric(userInput))

请注意,此不会在Android中运行。相反,您需要TextUtils.isDigitsOnly()