Java read system input in while loop - java

here is a very simple code, in which i am trying to take input from keyboard in a loop. For every input, the loop is automatically running two extra times and taking the values 13 and 10, no matter what i give as input. can you please point out what i am doing wrong.
CODE:
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
boolean loop_cond=true;
int n=1;
while(loop_cond==true)
{
try
{
System.out.print("input : ");
n=br.read();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.print(n+"\n");
}
} // end Main
OUTPUT :
input : 6
54
input : 13
input : 10
input : 9
57
input : 13
input : 10
input : 1
49
input : 13
input : 10
input :

Those are probably \r\n values. Try Scanner to take in values.
Scanner input = new Scanner(System.in);
int i = input.nextInt();

Change
n=br.read();
to
n = Integer.parseInt(br.readLine());
But I would recommend you to use Scanner class to avoid the Integer conversion.

Related

Using scanner various times in a loop Java

I'm new in this, i'm trying to write a code which stores user input in a array of n length (the length is also decided by the user).
So I decided to use a while loop to use Scanner n times, so that each time the user could store an String in that location as the loop advances.
But when I run the code, it just prints the statements don't letting me (or the user) to input the String.
public static void main(String[] args) {
String[] contadores;
Scanner cont= new Scanner(System.in);
System.out.println("Input the length of the array + 1: ");
int cuenta = cont.nextInt();
// Thread.sleep(4000);
contadores = new String[cuenta];
Scanner d = new Scanner(System.in);
int i=0;
while (i<= (contadores.length-1)) {
System.out.println("Input the word in the space: "+(i));
String libro = d.toString();
contadores[i] = libro;
i++;
}
When I run it, the output is:
Input the length of the array + 1:
3
Input the word in the space: 0
Input the word in the space: 1
Input the word in the space: 2
As you see it doesn't give me enough time to input something, I don't know if it JDK (I think not), or it is because is inside the main, I tried using Thread.sleep(4000); but the output is an error Unhandled exception type InterruptedException.
The problem is that you are not scanning inside the while loop. You need to scan the words the way you have scanned the integer. Instead of using d.next(), you've used d.toString().
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] contadores;
Scanner cont = new Scanner(System.in);
System.out.print("Input the length of the array: ");
int cuenta = cont.nextInt();
contadores = new String[cuenta];
int i = 0;
while (i < contadores.length) {
System.out.print("Input the word for the index " + (i) + ": ");
String libro = cont.next();
contadores[i] = libro;
i++;
}
// Display the array
for (String s : contadores) {
System.out.println(s);
}
}
}
A sample run:
Input the length of the array: 4
Input the word for the index 0: Hello
Input the word for the index 1: World
Input the word for the index 2: Good
Input the word for the index 3: Morning
Hello
World
Good
Morning
Also, note that I've used only one instance of Scanner. You do not need two instances of Scanner. You can reuse the same instance of Scanner everywhere in your program.

Multiple Scanner Inputs (Java)

I am currently learning Java and had a question:
I know that using Scanner will allow me to receive input from the console, but how do I receive multiple inputs on one line, rather than just one input per line?
For example:
Enter input: 1 3 5
You don't need multiple scanners. one is more than enough
By an input like 1 3 5 you can read that as a whole line(string)
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
System.out.println(input1);
or just get integer by integer
int inputA1 = sc.nextInt();
int inputA2 = sc.nextInt();
int inputA3 = sc.nextInt();
System.out.println("--------");
System.out.println(inputA1);
System.out.println(inputA2);
System.out.println(inputA3);
You can use below function that will return you multiple inputs from scanner
public List<String> getInputs(String inputseparator)
{
System.out.println("You Message here");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
return line.split(inputseparator);
}
and you can use it like that
List<String> inputs = getInputs(" ");
//iterate inputs and do what you want to . .
You can use nextLine() method of scanner.Below is sample code.
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
//sample input: 123 apple 314 orange
System.out.println("Enter multiple inputs on one line");
String st = s.nextLine();
s = new Scanner(st).useDelimiter("\\s");
//once the input is read from console in one line, you have to manually separate it using scanner methods.
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}
}

java.util.NoSuchElementException

Scanner sc=new Scanner(System.in);
int k=sc.nextInt();
sc.nextLine();
while(k-->0)
{
boolean t =false;
int n=sc.nextInt();
int l=sc.nextInt();
int i,j,m;
int a[]= new int[n];
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<n-2;i++)
{
for(j=i+1;j<n-1;j++)
{
for(k=j+1;k<n;k++)
{
if((a[i]+a[j]+a[k])==l)
{
t=true;
break;
}
}
}
}
String f= t?"true":"false";
System.out.println(f);
}
sc.close();
Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Solution.main(Solution.java:17)
Sample Input
3
5 60
1 20 40 100 80
Sample output false
What did i tried?
if(sc.hasNextInt())
n=sc.nextInt();
if(sc.hasNextInt())
l=sc.nextInt();
I'm getting more duplicate outputs(i.e false) for the supposed hasNextInt() fix.
3
5 60
1 20 40 100 80
false
This is what I am getting after running your code. Your code is correct I guess. But you are not giving input to it.
java.util.NoSuchElementException is thrown when scanner can not find what you asked it to read.
Give exactly correct input.
It seems that you have closed the scanner before in your code. Do not close it & re-instantiate it in program, rather initialize it once at start of main program & close it at the end of main program.
Scanner is closed as its resources closed because it implements
Closeable interface.
Like in below example -
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println(System.in.available());
scanner.close();
scanner = new Scanner(System.in);
// System.out.println(System.in.available());
// If you uncomment above: It will give you java.io.IOException: Stream closed
String str = scanner.nextLine();
}
Derived this answer from post: java.util.NoSuchElementException - Scanner reading user input
put an iteration at the start, and check for condition like this:
do {
//Here the code
} while (i.hasNextInt());
and for the scanner error you should check if scanner has one like this
Scanner sc =new Scanner(System.in);
if (sc.hasNext()) {
//here the code
}

Basic Code error

this is the basic program which im trying
public class keyboardinput {
public static void main(String[] args) throws java.io.IOException {
int a ;
System.out.println ("enter the text");
a = (int) System.in.read();
System.out.println ("the entered value is :"+a );
}
}
when executed, its showing the below response
enter the text
1
the entered value is :49
when i enter 1, why is not showing the entered value is 1
Could you please let me know why the output is showing equivalent asci values instead of what i entered in input
You cannot just cast from a byte to an int, as you are doing here:
a = (int) System.in.read();
System.in.read() returns an integer, but the result will be the ASCII code for the character 1, which is 49.
I suggest using a Scanner:
Scanner s = new Scanner(System.in);
a = s.nextInt();
49 is ASCII code of symbol 1 which you are explicitly case to int. To read int value use something like this:
try (BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))) {
a = Integer.parseInt(bf.readLine());
System.out.println("the entered value is :" + a);
}

Printing the last number only from a loop

If I have a while loop that goes through a file and prints the numbers, how would I make it to where it only prints the very last number.
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
This is the output I'm currently getting. How would I make get it to where it would just print out 19
And how would I get it to work to where the numbers start at 1 instead of 0?
Currently my loop looks like this:
if (math == last){
System.out.println(Score++);
}
math is another method which computes equations, and last is the answer inputed from a file, and the loop currently just checked if the math matches the inputed answer in order to "grade" the problems.
I can't use arrays, try/catch, or regex.
Just read through the file normally and store each line in a temporary variable. Once the reader finishes reading, print out the temporary variable.
public class ReaderExample {
public static void main(String[] args) throws IOException {
File file = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
String copy = "";
while((line = br.readLine() )!= null){
copy = line;
}
System.out.println(copy);
}
}
Using a Scanner
The same principle applies with a Scanner:
public class ReaderExample {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("input.txt"));
String line = "";
while(in.hasNext()){
line = in.nextLine();
}
System.out.println(line);
}
}
Without Invoking Scanner
public String getLast(Scanner scanner){
String line = "";
while(in.hasNext()){
line = in.nextLine();
}
return line;
}

Categories