gpt4 book ai didi

Java...While循环程序

转载 作者:行者123 更新时间:2023-11-30 11:40:31 24 4
gpt4 key购买 nike

我有一个家庭作业...代码在下面...有几个问题...提前致谢。初学者 Java 学生...如果这看起来很笨拙,请不要笑 >.>下面的代码...

    /*
* Getting to know you...
* @author Elle dela Victoria
* @version 092812
*/
import java.util.*;
public class A15_1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

System.out.print(
"Mind answering some questions for me?\n" +
"Type quit when you're ready to leave.\n");

while(true)
{
System.out.print("Does your name start with the letter H? ");
input.nextLine();
int ans = (int)(Math.random() * 5);
if (ans == 0)
System.out.println("That's awesome!");
if (ans == 1)
System.out.println("Awww, how unfortunate!");
if (ans == 2)
System.out.println("You're amazing at this!");
if (ans == 3)
System.out.println("LOL!");
if (ans == 4)
System.out.println("WTF!! That's horrible!");

System.out.print("Are you male? ");
input.nextLine();
int ans1 = (int)(Math.random() * 5);
if (ans1 == 0)
System.out.println("That's awesome!");
if (ans1 == 1)
System.out.println("Awww, how unfortunate!");
if (ans1 == 2)
System.out.println("You're amazing at this!");
if (ans1 == 3)
System.out.println("LOL!");
if (ans1 == 4)
System.out.println("WTF!! That's horrible!");

System.out.print("Are you female?");
input.nextLine();
int ans2 = (int)(Math.random() * 5);
if (ans2 == 0)
System.out.println("That's awesome!");
if (ans2 == 1)
System.out.println("Awww, how unfortunate!");
if (ans2 == 2)
System.out.println("You're amazing at this!");
if (ans2 == 3)
System.out.println("LOL!");
if (ans2 == 4)
System.out.println("WTF!! That's horrible!");

System.out.print("Are you in school right now?");
input.nextLine();
int ans3 = (int)(Math.random() * 5);
if (ans3 == 0)
System.out.println("So angry when you're sober!");
if (ans3 == 1)
System.out.println("Awww, how unfortunate!");
if (ans3 == 2)
System.out.println("You're amazing at this!");
if (ans3 == 3)
System.out.println("LOL!");
if (ans3 == 4)
System.out.println("WTF!! That's horrible!");

String userinput = input.nextLine();
if (userinput.equalsIgnoreCase("quit"))
break;
}
}
}
  1. 有没有什么方法可以对我提出的每个问题使用我的 IF 语句,而不必更改每个问题的字符串名称?
  2. 有没有办法为那些 if 语句创建一个方法 (?),这样我就不必为我提出的每个问题都写出它们?
  3. 如果用户在 10 秒内没有输入答案,我想要一个计时器来提示他们回答,我该怎么做?

最佳答案

你可以有一个字符串数组并根据输入ans打印它们:

    String str[] = {"That's awesome!", "Awww, how unfortunate!",
"You're amazing at this!", "LOL!", "WTF!! That's horrible!"};

/* code */

while(true)
{
System.out.print("Does your name start with the letter H? ");
input.nextLine();
int ans = (int)(Math.random() * str.length);
System.out.println(str[ans]);

/* code */
}

关于Java...While循环程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com