java - 如何解决错误以及如何使用 oops 概念做得更好?
问题描述
我正在学习java程序。我有一个问题要解决。问题是
enter the no . of people:
enter the product_name, price, stock_available:
total amount is price * no. of people
如果可用库存少于人数,则打印值 0
例子:
**input:**
no . of people : 3
product_name, price, stock_available: book, 100, 3
**output:** 300
public class Product {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people=sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
int quantity=Integer.parseInt(string[2]);
int price=Integer.parseInt(string[1]);
if(people<=quantity) {
System.out.println("Total amout is:"+(price*people));
}
else
{
System.out.println("value is "+0);
}
}
}
控制台错误:
Enter the no . of people:
3
Enter the product_name, price, quantity_available:
book
30
Exception in thread "main" java.lang.NumberFormatException: For input string: "book"
如何解决这个错误以及如何更好地使用 oops 概念?
解决方案
您的问题是您正在使用:
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
这sc.nextLine()
同时接受输入。现在问题是sc.nextLine()
读取一行,直到遇到'\n'
或。enter
现在,对于 for 循环中的第一个循环,它将 a'\n'
放入缓冲区中。因为 nextLine() 在'\n'
遇到时停止接受输入。因此,在下一个周期中, 的值string[1] = '\n'
。当您尝试将其解析为 Integer 时,会发生错误。因为这不是整数。
尝试这个:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people = sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.next();
}
int price = Integer.parseInt(string[1]);
int quantity = Integer.parseInt(string[2]);
if(people <= quantity) {
System.out.println("Total amount is: "+ (price*people));
}
else
{
System.out.println("value is: "+0);
}
}
推荐阅读
- python - 如何删除 sklearn(python3) 中的弃用错误?
- java - 为什么在java中克隆对象时出现运行时异常
- .net - BaseController 中的 .NET Core 依赖注入
- wiremock - 在wiremock中录制时如何忽略身体
- mysql - 将mysql保存到文件中
- xml - 使用 XSLT 分隔 XML 文件但无法获取交叉标记的值
- c# - What is the best way to log all commands and responses in Akka.net?
- java - 如何通过 Java 读取 PSD 格式的图像?
- javascript - 如何在同一页面上连接两个暗模式按钮?
- redux - 使用redux和react进行嵌套对象解构