你好,我试图只接受程序输入中的数字,但我收到了错误的消息

我想在这个程序中只接受 0,1 或 2 输入,否则会得到无效输入,有人可以帮忙吗?我尝试将字符串更改为双精度,但都不起作用


Scanner da = new Scanner(System.in);

String name;                          

int big=0;                         

int[] marks = new int[5];              

String getData()

{

    int total=0;                                

    String one="one";                           

    System.out.println("");

    name = da.nextLine();

    System.out.println("");

    big=da.nextInt();

    for(int b=0;b<5;b++)


        System.out.println("+(b+1));

        marks[b]=da.nextInt();

        if(b==4) da.nextLine();  

    if(total>big)  {

        big = total;                      

        return name;                                    

    }

}


12345678_0001
浏览 94回答 2
2回答

开心每一天1111

这就是输入验证,当用户没有输入整数值时要求用户重新输入。我已经为你写了一个例子:)import java.util.Scanner;public class Tester {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; while (!sc.hasNextInt()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("please enter again");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sc.next();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; int x = sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(x);&nbsp; &nbsp; }}在这种情况下,您可以实现一个单独的方法来进行输入验证。public int getInputInt(Scanner sc, int max, int min) {&nbsp; &nbsp; &nbsp; &nbsp; while (sc.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (sc.hasNextInt()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int val = sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (val >= min && val <= max) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return val;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sc.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }

宝慕林4294392

您可以简单地循环输入,直到选择给定的选项,然后继续游戏。while(true){&nbsp; System.out.println(" Sciccors (0), Stone(1) or Paper(2)? ");&nbsp; scanner= scan.nextLine();&nbsp; if( scanner.equals("0") || scanner.equals("1") || scanner.equals("2"))&nbsp; &nbsp; break;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java