Java Even Odd Integer添加是或否问题以再次播放

我是Java的新手,正在努力完成作业。我已经阅读了几篇文章,但似乎无法弄清楚如何在我的代码中再次添加“ Enter•y”来播放,•n•quit(y / n)。这是我到目前为止所拥有的。任何方向将不胜感激。我不知道如何返回到输入一个数字。 THX

//Program to display Even or Odd Integer
import java.util.Scanner;

public class EvenOdd {
    public static void main(String[] args) { //method to determine is a number is even or odd
        Scanner input = new Scanner(System.in);
        int number; //number o be entered
        System.out.print("Enter one number: "); //prompt user to enter a number
        number = input.nextInt();
        switch (number % 2) {
            case 0:
                System.out.printf("%d is even\n",number);
            case 1:
                System.out.printf("%d is odd\n",number);
        }
        System.out.print("Enter Y to play again,N to quit: "); //prompt user to enter a number
        number = input.nextInt();
    }

    public boolean isEven(int number) {
        return number %2 == 0;
    } //end method isEven
} //end class EvenOdd

结果:

Enter one number: 1
1 is odd
Enter Y to play again,N to quit: n
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 EvenOdd.main(EvenOdd.java:21)
as516344224 回答:Java Even Odd Integer添加是或否问题以再次播放

您将收到的异常告诉您输入与您尝试使用的正确类型不匹配。基本上:您正在尝试为String分配类型int(例如“ Y” /“ N”)。这将引发错误。在这里阅读有关不同类型的更多信息:https://en.wikibooks.org/wiki/Java_Programming/Primitive_Types

以下是有关解决方法的建议。您还将注意到,我在程序中添加了一个while循环,以便实际上可以再次播放。 您要更改的代码是从input.nextInt()input.next()。您还想更改将变量分配给哪个变量,因为您无法将String分配给int。 还向您的break;语句中添加了switch,因此不会遇到每种情况。

public class Main {

    public static void main(String[] args) { //method to determine is a number is even or odd
        String cont = "Y";
        Scanner input = new Scanner(System.in);
        while (cont.equals("Y")) {
            int number; //number o be entered
            System.out.print("Enter one number: "); //prompt user to enter a number
            number = input.nextInt();
            switch (number % 2) {
                case 0:
                    System.out.printf("%d is even\n",number);
                    break; //NOTICE here
                case 1:
                    System.out.printf("%d is odd\n",number);
                    break; //NOTICE here
            }
            System.out.print("Enter Y to play again,N to quit: "); //prompt user to enter a number
            cont = input.next(); // <---- This is what you want 
        }
        System.out.println("Did not want to play again,exiting...");
    }
}
本文链接:https://www.f2er.com/3044907.html

大家都在问