gpt4 book ai didi

java - 简单的输入限制问题

转载 作者:行者123 更新时间:2023-12-02 12:00:44 25 4
gpt4 key购买 nike

我有一个程序,首先我需要输入命令 - help,以及为什么要从 2 个命令中选择 - exp 或 sum 等等。起初,应该总是输入help,但是我无法输入help,但我可以立即输入exp或sum,我如何发出通知,以便如果我输入exp或sum,控制台写给我:输入help命令首先

我的代码:

import utils.Calculator;

import java.util.Scanner;

public class Never {

public static final String STOP = "-stop";

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
System.out.println("Enter command: for the initial operation of the program, type "help");
String word = scan.nextLine();

while (!word.equals(STOP)) {
switch (word) {

case "help": {
System.out.println("exp - outputs the root of a number");
System.out.println("sum - displays the sum of two numbers");
}
break;
case "exp": {
long result = Calculator.exp(scan.nextInt());
System.out.println(result);
}
break;
case "sum": {
System.out.println("Enter first number");
int first = scan.nextInt();
System.out.println("Enter second number");
int second = scan.nextInt();


long result = Calculator.sum(first, second);


System.out.println(result);

}
break;
default: {
System.out.println("Now exit programm");
}

}

word = scan.nextLine();

}

}

}

最佳答案

在第一个 while 循环之前放置一个 do-while 循环:

Scanner scan = new Scanner(System.in);
String word;
do {
System.out.println("Enter command: for the initial operation of the program, type "help");
word = scan.nextLine();
} while(!word.equals("help"));

// the rest of the code

这样程序会检查很多次,直到用户输入帮助

关于java - 简单的输入限制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268462/

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