Java:接受输入为string或int

时间:2014-05-11 11:43:23

标签: java class java.util.scanner

我正在尝试制作一个简单的偶数或奇数程序。我希望它一直运行,直到用户进入' q'。但我无法接受' q'作为一个字符串。

import java.util.Scanner;

class EvenOrOdd {

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);

        System.out.println("Welcome to my program that checks if a number is even or odd.");

        while (true) {
            System.out.println();
            System.out.print("Please type number in a number ['q' to quit]: ");

            int number;
            String quit;
            try {
                number = myScanner.nextInt();
            } finally {
                quit = myScanner.nextLine();
            }

            if (quit.equals("q")) {
                break;
            } else if (number % 2 == 0) {
                System.out.println(number + " is Even.");
            } else {
                System.out.println(number + " is Odd.");
            }
        }
    }
}

当我输入数字时,程序运行正常,但当我输入' q'时,控制台会抛出错误:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at EvenOrOdd.main(EvenOrOdd.java:19)

我知道这对你们很多人来说可能很容易,但我刚拿起一本java书并试图完成任务。任何帮助将不胜感激!

7 个答案:

答案 0 :(得分:1)

从扫描仪中取出一个字符串,检查是否为“q”,如果不是,则将其转换为int,然后检查偶数或奇数。

public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);

    System.out.println("Welcome to my program that checks if a number is even or odd.");

    while (true) {
        System.out.println();
        System.out.print("Please type number in a number ['q' to quit]: ");

        String inText = myScanner.next();

        if (inText.equals("q")){
            break;
        }
        int number = Integer.valueOf(inText);
        if (number % 2 == 0) {
            System.out.println(number + " is Even.");
        } else {
            System.out.println(number + " is Odd.");
        }
    }
}

答案 1 :(得分:1)

你可以做这样的事情,我发现在这种情况下布尔值更适合循环而不是while(true)和break:

public class EvenOrOdd {
public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);

    System.out
            .println("Welcome to my program that checks if a number is even or odd.");
    boolean enterLoop = true;
    while (enterLoop) {
        System.out.println();
        System.out.print("Please type number in a number ['q' to quit]: ");

        String scannerinput = myScanner.nextLine();
        if (scannerinput.equals("q")) {
            enterLoop = false;
        } else {
            checkNumber(scannerinput);
        }

    }
}

private static void checkNumber(String scannerinput) {
    try {
        int number = Integer.parseInt(scannerinput);
        if (number % 2 == 0) {
            System.out.println(number + " is Even.");
        } else {
            System.out.println(number + " is Odd.");
        }
    } catch (Exception e) {
        System.out.println("No Number!");
    }
}

}

答案 2 :(得分:1)

import java.util.Scanner;

class EvenOrOdd {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to my program that checks if a number is even or odd.");

        while (true) {
            System.out.print("\nPlease type number in a number ['q' to quit]: ");
            String input = scanner.next();
            if (input.equals("q")) {
                break;
            } else {
                int number = Integer.parseInt(input);
                System.out.print(number + " is ");
                System.out.print(number%2 == 0 ? "Even." : "Odd.");
            }
        }
    }
}

那样做。 :)

答案 3 :(得分:0)

不要使用myScanner.nextInt(),只需使用myScanner.next()即可获得String。然后,如果它不是" q",请使用Integer.valueOf(inputString)获取int并检查偶数/奇数。

while (true) {
    String input = myScanner.next();
    if ("q".equals(input)) {
        break;
    } else {
        int number = Integer.valueOf(input);
        if (number % 2 == 0) {
            System.out.println(number + " is Even.");
        } else {
            System.out.println(number + " is Odd.");
        }
    }
}

答案 4 :(得分:0)

这是因为程序期望输入int类型,基本上是程序输出:请在数字中键入数字[' q'退出],之后它会到达myScanner.nextInt();行并等待输入,因为" q"不是整数,它会引发异常。

快速解决方案是使用myScanner.nextLine(),然后将字符串转换为整数,除非它等于' q'。像这样:

import java.util.Scanner;

public class EvenOrOdd {

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);

        System.out.println("Welcome to my program that checks if a number is even or odd.");

        while (true) {
            System.out.println();
            System.out.print("Please type number in a number ['q' to quit]: ");

            String string = myScanner.nextLine();
            int number = 0;

            if (string.equals("q")) {
                myScanner.close(); // Close the scanner.
                break;
            } else if ((number = toInteger(string)) == -1){  // Is the string a number, less than Integer.MAX_VALUE and greater than Integer.MIN_VALUE?
                System.out.printf("%s is not a valid integer!%n",string);
            } else if (number % 2 == 0) {
                System.out.println(number + " is Even.");
            } else {
                System.out.println(number + " is Odd.");
            }
        }
    }

    private static int toInteger(String str){
        try{
            return Math.abs(Integer.parseInt(str));
        }catch(NumberFormatException e){
            return -1;
        }
    }
}

顺便说一句,请务必关闭扫描仪,否则可能会发生资源泄漏。

答案 5 :(得分:0)

尝试这种方法。查看代码注释以获取更多详细信息。

import java.util.Scanner;

class EvenOrOdd {

public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);

    System.out.println("Welcome to my program that checks if a number is even or odd.");

    String input=null;
    int number;
    boolean flag=true;  // loop flag
    do {
        System.out.println();
        System.out.print("Please type number in a number ['q' to quit]: ");

        // Take user input as String
        input=myScanner.nextLine();


        try 
        {
            // convert the string value to integer value
            number = Integer.parseInt(input);

            if (number % 2 == 0)
            {
                System.out.println(number + " is Even.");
            }
            else
            {
                System.out.println(number + " is Odd.");
            }
        } 
        catch (NumberFormatException nfe) 
        {
           // control goes here if input is not integer value
            if(input.equals("q"))   // exist option
                flag=false;
            else    // invalid input
                System.out.println("Invalid input, Please enter integer value or (q) to exist");


        }


    } while (flag);

}
}

答案 6 :(得分:0)

你应该更新你的方法流,你实际上是在尝试传递和整数字符串的验证,所以首先把输入作为String并检查它是否是你的退出字符 q 然后如果不是尝试用int将字符串解析为Integer.parseInt(input)原语并测试它是奇数还是偶数。 如果过程失败,假设它既不是 q 也不是数字(任何其他字符),则会提示用户告知用户使用有效号码或" q"退出:

import java.util.Scanner;

class EvenOrOdd {

public static void main(String[] args) {
  Scanner myScanner = new Scanner(System.in);

  System.out.println("Welcome to my program that checks if a number is even or odd.");

  while (true) {
    System.out.println();
    System.out.print("Please type number in a number ['q' to quit]: ");

    int number;
    String input = myScanner.next();
    if (input.equals("q")) {
      break;
    } else {
      try {
        number = Integer.parseInt(input);
        if (number % 2 == 0) {
           System.out.println(number + " is Even.");
        } else {
           System.out.println(number + " is Odd.");
        }
        } catch (NumberFormatException nfe) {
           System.out.println("Enter valid number or \"q\" to quit!");
        }
      }
    }
  }
}