I am trying to take an integer as user input and store it in a list until the user hits 'q'. At the moment the user inputs 'q', the loop gets terminated.
The code is showing an InputMismatch
error:
import java.util.*;
public class SampleArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
int n;
List<Integer> array = new ArrayList();
while (true) {
n = sc.nextInt();
s = sc.nextLine();
if (s.equals("q")) {
break;
} else {
array.add(n);
}
}
Collections.sort(array);
System.out.println(array);
}
}
CodePudding user response:
Are you trying to implement it like the example below?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
List<Integer> array = new ArrayList();
while (true) {
s = sc.nextLine();
if (s.equalsIgnoreCase("q")) {
break;
}
int num = Integer.parseInt(s);
array.add(num);
}
Collections.sort(array);
System.out.println(array);
}
}
CodePudding user response:
Looks like q
is trying to be stored as an int
, so this should work:
All numbers stored as a String
can be parsed as an int
with the parseInt()
method.
s = sc.nextLine();
if (!s.equals("q"))
{
array.add(Integer.parseInt(s));
}
else
{
break;
}