首页 > 解决方案 > 在我的 Java 程序中读取第二个用户输入不起作用

问题描述

我想制作一个程序,要求用户输入他们想购买多少台笔记本电脑,然后询问他们笔记本电脑的价格是否不同。如果答案是“是”,它将根据笔记本电脑的数量重复该问题。否则它只会询问一次,然后计算笔记本电脑的成本

我明白了:

How many laptops do you want to buy? 3
Do they have different price (yes/no)? Enter laptop/s price:
import java.util.Scanner;

public class LaptopCostCalculatorV2 {
    public static void main(String[] args) {
        int laptopsPrice = 0;
        int laptopQuantity;

        Scanner scan = new Scanner(System.in);

        System.out.print("How many laptops do you want to buy? ");
        laptopQuantity = scan.nextInt();
        System.out.print("Do they have different price (yes/no)? ");
        String choose = scan.nextLine();
        if (choose.equals("yes")) {
            for (int i = 0; i < laptopQuantity; i++) {
                System.out.println("Enter laptop price");
                laptopsPrice = scan.nextInt();
            }
        } else {
            System.out.println("Enter laptop/s price: ");
            int laptopPrice = scan.nextInt();
        }
    }
}

为什么它不让我输入第二个问题的答案?

标签: java

解决方案


import java.util.Scanner;

public class LaptopCostCalculatorV2 {
    public static void main(String[] args) {
        int laptopsPrice = 0;
        int laptopQuantity;

        Scanner scan = new Scanner(System.in);

        System.out.print("How many laptops do you want to buy? ");
        laptopQuantity = scan.nextInt();
        scan.nextLine();
        System.out.print("Do they have different price (yes/no)? ");
        String choose = scan.nextLine();
        if ("yes".equals(choose)) {
            for (int i = 0; i < laptopQuantity; i++) {
                System.out.println("Enter laptop price");
                laptopsPrice += scan.nextInt();
                scan.nextLine();
            }
        } else {
            System.out.println("Enter laptop/s price: ");
            laptopsPrice += scan.nextInt() * laptopQuantity;
            scan.nextLine();
        }
        System.out.println("Total is: " + laptopsPrice);
    }
}

nextInt读取缓冲区中的下一个整数,但不会自动“跳”到下一行。这种行为使您可以在一行中连续调用 读取多个整数nextInt(),但要开始读取下一行,nextLine()则应遵循调用。nextLine()实际上跳过换行符并返回之前剩余的任何内容。由于我们对阅读其余部分不感兴趣,因此我们只是丢弃了它的返回值。If 12 whateveris the line then12将是 的结果nextInt(),并且" whatever"将是 follow的结果nextLine()。即使用户只输入12了,nextLine()尽管它只会返回一个空字符串,但它也是必需的""


推荐阅读