When I'm using a bufferedreader, It will skip a line then read the input the user enters. Is there a way to have it read something that comes after a line in the console from something such as a System.out.print();?
Example: "Enter your age here: " (read here)
instead of: "Enter your age here: "
(reads here)
I don't necessarily need to use a bufferedreader for all that matters, I just want it to read something after the line, not under it.
EDIT: code from a program I had laying around, which is a good example.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
int y;
int z;
int x = 0;
String line2 = "empty";
String line = "empty";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("enter 2 numbers of which the first is larger than the second");
try {
line = br.readLine();
}
catch (Exception e) {
e.printStackTrace();
}
try {
line2 = br2.readLine();
}
catch (Exception e) {
e.printStackTrace();
}
y = Integer.parseInt(line);
z = Integer.parseInt(line2);
if (y < 9 && y > 5 && z > 5 && z < 9) {
if (y > z) {
x = (int) ((Math.random() * (y - z)) + z);
}
if (z > y) {
x = (int) ((Math.random() * (z - y)) + y);
}
}else System.out.println("only numbers between 5 and 9!");
int[] getallen = new int[x];
for (int i = 0; i < x; i++) {
getallen[i] = (int) ((Math.random() * (y - z)) + z);
System.out.println(getallen[i]);
}
}
}
output:
"enter 2 numbers of which the first is larger than the second
2
5
only numbers between 5 and 9!"
what I want:
"enter 2 numbers of which the first is larger than the second 2 5
only numbers between 5 and 9!"
variable names are in Dutch, but they aren't really relevant to my question anyway.
I made a simple programm and it worked with Eclipse by just changing the System.out.println(...)
to System.out.print(...)
. But you will have the problem to separate the numbers e.g. Enter number(s): 1 2 3
will return 1 2 3
as one string.
Therefore I would suggest you to use a Scanner
for reading the inputs because it has a nextInt()
method, which you can pull constantly for numbers (e.g. Enter number(s): 1 2 3
will give you at first call 1
, at second call 2
and at third call 3
)
Example:
public static void main(String[] args) {
int number = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number(s): ");
while(scanner.hasNextInt()) {
number = scanner.nextInt();
System.out.println("Number was " + number);
}
}