java - 在我的 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();
}
}
}
为什么它不让我输入第二个问题的答案?
解决方案
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 whatever
is the line then12
将是 的结果nextInt()
,并且" whatever"
将是 follow的结果nextLine()
。即使用户只输入12
了,nextLine()
尽管它只会返回一个空字符串,但它也是必需的""
。
推荐阅读
- perl - 如何使用 Net::SMTP::TLS 发送电子邮件附件
- javascript - 在其他组件中使用 react this.state
- c# - 通过 .Net Web api 从 azure blob 下载文档
- android - 在不同高度的设备上实现闪屏
- android - 将查询游标数据转换为 URL 并在 AsyncTask 中运行
- angularjs - 如何将本地系统中存在的 .json 文件调用到 http 链接中?
- javascript - 我不明白错误:this.state.categories.map is not a function ReactJS
- sql - 表在 BEFORE DELETE 触发器上发生变异
- regex - 正则表达式匹配 flex 中字母的字符串输入中的字母重复
- sequelize.js - 运行同步()时“关系不存在”