簡體   English   中英

如果沒有鍵盤輸入,如何生成隨機數

[英]How to generate a random number if there is no input from the keyboard

如果鍵盤輸入為“”,我已獲得有關如何生成隨機名稱的幫助。 如果輸入是“”,我如何做同樣的事情來生成一個隨機數? 輸入“請輸入第一個數字:”輸出 - 如果沒有輸入值“”然后生成隨機數。

package username;

import java.util.Scanner;
import java.util.Random;

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

        String user_Name1;
        System.out.print("Please enter the first username: ");
        user_Name1 = input.nextLine();
        if (user_Name1.equals("")) {
            String[] random = {"Luke", "Leia", "Hans", "Darth" , "Vader" , "Chewbacca"};
            user_Name1 = random[(int) (Math.random() * random.length)];
        }

        System.out.println("" + user_Name1);

        System.out.print("Please enter the first number: ");
        int user_number1 = input.nextInt();
    }
}

這里input.nextInt(); 意味着Scanner.nextInt沒有將enterkey作為有效輸入。 因此,您可以嘗試通過input.nextLine()並將值轉換為Integer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM