import java.util.Scanner;
public class smth {
Scanner input = new Scanner(System.in);
int array[]={};
}
what can i do next, to store every number I input from keyboard into array.
A while()
loop involving the Scanner object would be beneficial. You don't need to reinitialize/redeclare it every time through the loop.
import java.util.Scanner;
public class smth {
final int SIZE = 10; // You need to define a size.
Scanner input = new Scanner(System.in);
int array[]= new int[SIZE];
public void readFromTerminal() {
System.out.println("Read lines, please enter some other character to stop.");
String in = input.nextLine();
while ( ) { } // I encourage you to fill in the blanks!
}
}
[EDIT] If you want the user to be able to enter an "unlimited" number of integers, then an ArrayList<Integer>
would be more ideal.
import java.util.Scanner;
public class smth {
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>(); // Please reference the documentation to see why I'm using the Integer wrapper class, and not a standard int.
public void readFromTerminal() {
System.out.println("Read lines, please enter some other character to stop.");
String in = input.nextLine();
while ( ) { } // I encourage you to fill in the blanks!
}
}
Scanner input = new Scanner(System.in);
ArrayList<Integer> al = new ArrayList<Integer>();
int check=0;
while(true){
check = input.nextInt();
if(check == 0) break;
al.add(check);
}
for (int i : al) {
System.out.print(i);
}
}
That's what I did. When user enters "0", it breaks.
You are going to want to wrap that in a while loop based on some condition. For now, it can just be while(true)...
, but later on you are going to want to use a condition that will terminate at some point.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.