我想在链表中添加一些数字,但是在我的循环中,当我想结束添加并键入"exit"时,出现了一个异常:
Exception in thread "main" java.lang.NumberFormatException: For input string: "exit"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Main.main(Main.java:16)
代码import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static final String EXIT = "exit";
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> list = new LinkedList<>();
Scanner input = new Scanner(System.in);
String temp;
System.out.println("Add number: ");
while((temp=input.nextLine()) != "exit"){
int i = Integer.parseInt(temp);
list.add(i);
System.out.println("Add number:");
}
System.out.println("Completed. The summary is: ");
int suma = 0;
for(Integer skl : list){
suma += skl;
}
System.out.println(suma);
}
}
不使用
input.nextLine() != "exit"
试
!(input.nextLine().equals("exit"))
这是一个经典的字符串比较问题。
使用:
while(!"exit".equals(temp=input.nextLine()){