java - Use random name generator after getting input from keyboard
问题描述
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
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[] randoms = {"Luke", "Leia", "Sophia", "David"};
name = randoms[((int) Math.random()*randoms.length)];
}
System.out.println("" + user_Name1);
}
}
解决方案
这应该做的工作:
// Starting in main function after the System.out.println()
String name = scanner.nextLine();
scanner.close(); // optional but recommended
if (name == null || name.equals("") {
// Do random pick as you did before and assign it to name
String[] randoms = {"Luke", "Leia", "Sophia", "David"}; // Add all names here
name = randoms[((int) Math.random()*randoms.length)]; // Pick random name
}
System.out.println("Your name is " + name);
// The rest of the class with closing brackets
推荐阅读
- arrays - 映射对象数组时,TypeScript 不允许我实现参数接口
- google-cloud-platform - 使用 Terraform 创建 GCP VPC 时出错 - 无法获取令牌:意外 EOF
- python - “windll.user32.ReleaseDC 失败:从 pyautogui.pixel() 返回 0”
- xml - XML Schema - 内容受限的混合元素
- javascript - 为单击搜索按钮和输入按钮添加事件侦听器
- python - 当我的数据集发生变化时如何重构我现有的函数
- python - 递归python函数中的实例化对象似乎保留/获取对其他实例的引用
- python - 如何将 Django 添加到路径
- flutter - flutter 如何从 API 获取谷歌地图标记并在谷歌地图上绘图
- flutter - Flutter 安装问题,无法接受带有字母 Y 或 y 的许可证