亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

你好,我試圖只接受程序輸入中的數字,但我收到了錯誤的消息

你好,我試圖只接受程序輸入中的數字,但我收到了錯誤的消息

12345678_0001 2023-08-16 10:52:06
我想在這個程序中只接受 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;                                        }}
查看完整描述

2 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

這就是輸入驗證,當用戶沒有輸入整數值時要求用戶重新輸入。我已經為你寫了一個例子:)


import java.util.Scanner;


public class Tester {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        while (!sc.hasNextInt()){

            System.out.println("please enter again");

            sc.next();

        }

        int x = sc.nextInt();

        System.out.println(x);

    }

}

在這種情況下,您可以實現一個單獨的方法來進行輸入驗證。


public int getInputInt(Scanner sc, int max, int min) {

        while (sc.hasNext()) {

            if (sc.hasNextInt()) {

                int val = sc.nextInt();

                if (val >= min && val <= max) { 

                    return val;

                }

            } else {

                sc.next();

            }

        }

        return -1;

    }


查看完整回答
反對 回復 2023-08-16
?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

您可以簡單地循環輸入,直到選擇給定的選項,然后繼續游戲。


while(true){

  System.out.println(" Sciccors (0), Stone(1) or Paper(2)? ");

  scanner= scan.nextLine();

  if( scanner.equals("0") || scanner.equals("1") || scanner.equals("2"))

    break;

}


查看完整回答
反對 回復 2023-08-16
  • 2 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號