【问题标题】:The while loop double prints first before entering a value [closed]while 循环在输入值之前先进行双重打印[关闭]
【发布时间】:2019-09-09 15:03:31
【问题描述】:

String asd 在请求切换器的输入之前打印 double,我现在感到绝望。我希望字符串“asd”只打印一次,但在我的情况下打印两次,我的猜测是错误或循环,对不起,我在这里很新并开始编程

public class FruitBasket {

static String option;
static String choice1;
static int catcher;
static int counter1 = 1;
static int counter = 0;
static String eater = "e";
static Scanner sc = new Scanner(System.in);       
static Stack<String> basket = new Stack();
static String switcher;

public static void main(String[] args) {

    catching();

}

static void catching(){

    System.out.println("Catch and eat any of these fruits: " + "'apple', 'orange', 'mango', 'guava'" );
    System.out.println("A apple, O orange, M mango, G guava");
    System.out.print("How many fruits would you like to catch? ");
    catcher = sc.nextInt();

    switches();
     }

     static void switches(){

    while(counter1 < catcher)  {
    String asd = "Fruit " + counter1 + " of " + catcher + ":";
    System.out.print(asd);

    switcher = sc.nextLine();
         switch (switcher) {
            case "a":
                basket.push("apple");
                counter++;
                counter1++;
                break;

【问题讨论】:

  • 您没有向我们展示如何初始化计数器和捕手,我尝试使用捕手 = 4 和计数器 = 0 并且字符串 asd 没有打印两次。
  • 请原谅我太菜鸟了。 int 计数器只是“静态 int 计数器”;捕手是 "System.out.print("你想捕多少水果?"); catcher = sc.nextInt();""
  • Java 和 JavaScript 是完全不相关的语言。

标签: java stack


【解决方案1】:

这是因为您使用 sc.nextInt() 来获取用户的输入并且它不消耗线路所以当您使用 switcher = sc.nextLine();它仍然会读取用户之前输入的数字。

你可以在 catcher = sc.nextInt(); 之后添加这个消费线:

    if (sc.hasNextLine()){
        sc.nextLine();
    }

或者你也可以使用:

catcher = Integer.parseInt(sc.nextLine());

将用户输入转换为整数值,它也可以工作。

【讨论】:

  • 这段代码救了我,非常感谢先生!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多