错误 java.lang.NumberFormatException 如果我尝试将 2 个单词插入单个字符串(Java)!!
显示的错误是:
Enter item Chicken rice 输入金额(第纳尔)
线程“main”中的异常 java.lang.NumberFormatException: For input 字符串:“大米”在 java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) 在 java.base/java.lang.Integer.parseInt(Integer.java:668) 处 java.base/java.lang.Integer.valueOf(Integer.java:999) 在 Sampleproject1/t4.Main.main(Main.java:65)
import java.util.*;
class Expense implements Comparable<Expense>{
String expenseCategory;
Integer amount;
public String getExpenseCategory() {
return expenseCategory;
}
public void setExpenseCategory(String expenseCategory) {
this.expenseCategory = expenseCategory;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Expense(String expC , Integer amount) {
this.expenseCategory=expC;
this.amount = amount;
}
public String toString() {
return expenseCategory+ " " +amount;
}
public int compareTo(Expense e) {
if(amount>e.amount){
return 1;
}else if(amount<e.amount){
return -1;
}else{
return 0;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeSet<Expense> set1 = new TreeSet<Expense>();
int tamount=0;
while(true) {
System.out.println("Enter item");
String expC = sc.next();
System.out.println("Enter amount(Dinar)");
String amt = sc.next();
tamount = tamount + Integer.valueOf(amt);
set1.add(new Expense(expC,Integer.valueOf(amt)));
System.out.println("Do you want to continue(yes/no):");
String cond = sc.next();
if(cond.equals("no")) {
break;
}else {continue;}
}
System.out.println("Total dinar required is:");
System.out.println("Category Amount(Dinar)");
Iterator x = set1.descendingIterator();
while(x.hasNext()) {
System.out.println(x.next());
}
System.out.println("Total amount needed in Dinar:"+ tamount);
System.out.println("Total amount needed in Rupees:"+ tamount*18.565);
}
}
Output should be like :
Enter item
Fried Rice
Enter amount(Dinar)
20
Do you want to continue(yes/no):
yes
Enter item
Chicken Lollipop
Enter amount(Dinar)
25
Do you want to continue(yes/no):
yes
Enter item
Coffee
Enter amount(Dinar)
5
Do you want to continue(yes/no):
no
Total dinar required is:
Item Amount(Dinar)
Chicken Lollipop25
Fried Rice 20
Coffee 5
Total amount needed in Dinar: 50
Total amount needed in Rupees: 928.25
如果我使用 nextLine();一些输入被跳过!!
从您的示例中可以清楚地看出,您打算将“输入”键作为输入之间的分隔符。但是,开箱即用,扫描仪将 any whitespace 视为分隔符。简单地告诉它你只想要换行符。
new Scanner(System.in)
之后立即:
scanner.useDelimiter("\\R");
\\R
是“任何换行变体”的正则表达式。
通过为所有语句添加 nextLine() 来修复它