Reputation: 37
I'm trying to gather user inputs and sort them after the input "bye" is given. However I don't understand how to accomplish the "bye" part. Here is what I have so far. Can someone explain why I can't add nextLine() instead of nextInt() and change things to Strings. I could then break out of the while statement with the string "bye" but none of it has worked for me so far.
import java.util.*;
public class Work {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] values = new int[1];
int currentSize = 0;
System.out.print("Type a number ");
while( s.hasNextInt())
{
if(currentSize >= values.length)
{
values = Arrays.copyOf(values, values.length + 1);
}
System.out.print("Type: ");
values[currentSize] = s.nextInt();
currentSize++;
Arrays.sort(values);
System.out.print(Arrays.toString( values ) );
}
}
}
Upvotes: 2
Views: 90
Reputation: 828
Well, the answer posted by James is appropriate!
Although, if you want to exit the loop when user enters "bye" and use the nextLine() then here is another solution.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] values = new int[1];
int currentSize = 0;
System.out.print("Type a number ");
while (s.hasNext()) {
// assign it to local var
String input = s.nextLine();
// check for bye
if (!input.equalsIgnoreCase("bye")) {
if (currentSize >= values.length) {
values = Arrays.copyOf(values, values.length + 1);
}
System.out.print("Type: ");
// add the input value.
values[currentSize] = Integer.parseInt(input.trim());
currentSize++;
Arrays.sort(values);
System.out.print(Arrays.toString(values));
} else {
System.out.println("exiting...");
System.exit(1);
}
}
}
This one adds some branching in code for user input string comparison using if-else loop.
Hope it helps!
Upvotes: 0
Reputation: 17548
Can someone explain why I can't add nextLine() instead of nextInt() and change things to Strings.
You can, you just have to handle the conversions.
String input = null;
while(!"bye".equalsIgnoreCase(input))
{
value = Integer.parseInt(input.trim());
//..do stuff with the int value
input = s.nextLine();
}
You may need to handle NumberFormatException
if you don't want to trust that the user will enter numbers.
Upvotes: 2