I\'ve been trying to print the output in two separate lines, I used System.out.println()
and also System.out.println(\"\\n\")
but I only seem to be get
Maybe use a do while and use try and catch. Because when you enter a character instead of a number your program is going to crash.
public class StoreToArray
{
Scanner input = new Scanner(System.in);
ArrayList<Integer> al = new ArrayList<Integer>();
public static void main(String args [])
{
//Access method using object reference
StoreToArray t = new StoreToArray();
t.readFromTerminal();
}
public void readFromTerminal() {
System.out.println("Read lines, please enter some other character to stop.");
int check=0;
do{
try {
check = input.nextInt();
if(check != 0)
al.add(check);
}
catch(InputMismatchException e)
{
System.out.println("Failed to convert to int.");
check = 0;
}
}while(check != 0);
for (int i : al) {
System.out.println(i);
}
}
}
If i understand your question correctly, may be this is what you need
public void readFromTerminal() {
System.out
.println("Read lines, please enter some other character to stop.");
int check = 0;
while (true) {
check = input.nextInt();
al.add(check);
if (check == 0) {
break;
}
}
for (int i : al) {
System.out.print(i+ "\n");
}
}
The line:
String in = input.nextLine();
is capturing your first number entered and it is never added to the list al.
So, if you enter:
45
40
67
0
the output is:
[40, 67] (using System.out.println(al))
or:
4067 (using your for loop).
Note, the loop is broken by entering 0, not non-numeric characters as the first output text line would suggest.
Read lines, please enter some other character to stop
should really read
Read lines, please enter 0 to stop
[EDIT]
To add/display numbers to the list correctly:
1) Remove the line:
String in = input.nextLine();
2) Remove the for loop at the end and replace it with:
System.out.println(al);