Can't print line after looping through scanner input - Java - java

Why does this not print 'done'?
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
System.out.println(s.nextInt());
}
System.out.println("done");
}
}
It prints the input just fine, but doesn't print the word done.
EDIT if I input integers separated by space in the console and then hit enter, it prints all the integers I entered on a separate line, but it just doesn't print the word done after all that
EDIT
this works… but seems not very elegant
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int temp;
while (s.hasNext()) {
temp = s.nextInt();
if (temp != -99) {
System.out.println(temp);
} else {
break;
}
}
System.out.println("done");
}
}

What you are seeing is that Scanner is blocking on the input stream where there are no characters, and is just waiting for more. To signal the end of the stream, the 'end of stream' character has to be sent. That is ctrl-d on linux.
From the documentation of java.util.Scanner (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html).
Both hasNext
and next methods may block waiting for further input. Whether a hasNext method
blocks has no connection to whether or not its associated next method will block.
For example, from a linux command prompt
> javac Main.java
> java Main
> 810
810
> 22
22
> foo
java.util.InputMismatchException
> java Main
> 1
1
> ctrl-D
done
Another way to test this is to echo a line or cat a file into your program:
> echo 2 | java Main
2
done
EDIT:
Given the desired outcome described in the comments below; Give the following a try, it will read in only one line. Parse the space separated ints out, echo them one per line and then print done.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
*
*/
public class Main {
public static void main(String[] args) throws IOException {
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
Scanner s = new Scanner(str);
while (s.hasNext()) {
System.out.println(s.nextInt());
}
System.out.println("done");
}
}
EDIT EDIT: Cleaned up the answer and worked in information from the comments.

Related

How to read float input without knowing size in java?

Sample Input:
9.1 9.0 8.9 8.8 9.4 7.9 8.6 9.8
Here is my code for getting input.
I dont know how to get this type of input without knowing the number of inputs.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class Diving_Competition {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
lst.add(in.nextFloat());
}
System.out.print(lst);
in.close();
}
}
This loop runs infinite time. How to get input in a single line without knowing its size?
I'm from python background
As long as there are numerical inputs, your code will not exit the while loop because the condtion in.hasNextFloat() is satisfied.
Assuming you are entering the sample in the terminal: To exit the loop, just enter any non-numerical value like a or enter the EOF-command. In Unix this is Ctrl+D and in Windows it is Ctrl+Z (not sure about Windows-Command)
Haven't java in a bit but I think this works. I read the whole line and separate them.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class read {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
String string = in.nextLine();
String[] stringLst = string.split(" ");
ArrayList<Float> numLst = new ArrayList<Float>();
for (String num : stringLst) {
numLst.add(Float.parseFloat(num));
}
System.out.print(numLst);
in.close();
}
}
The best way to figure out such issues is either by debugger OR use console to print helpful information. Your program is perfectly fine, it hangs because it is expecting an input that needs to be entered (unless you want to scan input as program args then its a different question).
Here I made a simple change in your program
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
float x = in.nextFloat();
System.out.println("Number Entered: " + x);
lst.add(x);
}
System.out.print(lst);
in.close();
}
and here is console output
2.3
Number Entered: 2.3
re
[2.3]
Notice how to end the input, I had to enter non-float letters. If I don't enter that, the program will continue to take input from the console, one-by-one.
That being said, from your question it looks like you want to get a line of float input from console. If that the case, then you should read by line and parse it based on "space" character.

Program that returns input \t as *

The code is supposed to read an unidentified number of inputs from the keyboard and return any tabs as *. My program seems to work when I run it in eclipse and get no errors. When I turn in the code on the submission website, this is the error I get.
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1589) at replaceHW.main(replaceHW.java:9)
import java.util.Scanner;
public class replaceHW {
public static void main(String[] args) {
//write a program that converts all TABS in your code
//with STARS i.e. *
Scanner in = new Scanner(System.in);
String ans;
while(!(ans = in.nextLine()).equals(""))
System.out.println(ans.replace("\t","*"));
}
}
Your problem is simple: nextLine() works in tandem with hasNextLine(): the correct code is:
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (!"".equals(line)) {
System.out.println(ans.replace("\t","*"));
}
}
The try-with-resources is best practice. But be wary than with System.in, it will close it when done.
hasNextLine() will try to read has much input is needed to find a line.

Copied this exact code from my book and does not work

I copied this exact code from my textbook, and when I try to run it it does nothing but load, the file is in the same location of the java file, and the name is correct. Im using Dr. Java. So im just wondering why it wont run and just keeps loading. The book I am using is Java Illuminated 3rd edition. Also, the newscores.txt file just has 10 numbers, seperated by spaces.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class TestScoresAndSummaryStatistics {
public static void main(String[] args) throws IOException {
int number;
File inputFile = new File("newscores.txt");
Scanner scan = new Scanner(inputFile);
while (scan.hasNext()); {
number = scan.nextInt();
System.out.println(number);
}
System.out.println("End of file.");
}
}
you have a semicolon end of while statement .you should remove it.because of this semicolon your while loop run repeatedly and your code inside while loop become separate block from the loop.
while (scan.hasNext()); {
number = scan.nextInt();
System.out.println(number);
}
change to
while (scan.hasNext()) {
number = scan.nextInt();
System.out.println(number);
}

How to stop printing input at 42?

I'm doing a problem on a website where it inputs the numbers:
1
2
88
42
99
and it's supposed to output
1
2
88
The code is supposed to stop printing the input when it hits 42, and it works, but when I submit it to the site, it tells me that it gave the wrong answer.
Here's my code:
http://pastebin.com/y5e8DyHz
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int res;
for(int i=0;i <5; i++) {
res = scan.nextInt();
if (res!=42) {
System.out.println(res);
} else {
System.exit(0);
}
}
}
}
It works when I run it in IDEOne, so I'm not sure what the problem is. Thanks!
Note that a solution to the TEST problem is available in the SPOJ forums. It's a good example of how to process input as fast as possible in java.
Based on your requirement, you have to use it like shown below, even in your IDE
Scanner scan = new Scanner(System.in);
int res;
while (scan.hasNext()) {
res = scan.nextInt();
if (res != 42) {
System.out.println(res);
} else {
System.exit(0);
}
}
Reason being what #jrbeverly mentioned above as his comment
update 1:
If you meant "stop printing the input" as the program must exit on encountering '42',you are good. But if your requirement is just to discard printing the number, and let the program run and accept the next number, then remove System.exit(0) . because System.exit(0) means to terminate the JVM from further execution of the program
update 2:
As #Giovanni Botta mentioned below, the exact solution is provided in the mentioned link, snippet adding here
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String s;
while (!(s=r.readLine()).startsWith("42")) System.out.println(s);
}
}

java.util.Scanner does not return to Prompt

import java.util.Scanner;
class newClass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
System.out.println(s.next());
}
s.close();
}
}
This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?
This program does not return to prompt (I have been running it through the Terminal). Why is that?
Because s.hasNext() will block until further input is available and will only return false if it encounters end of stream.
From the docs:
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.
On a unix system you can end the stream by typing Ctrl+D which correctly returns control to the prompt, (or terminate the whole program by typing Ctrl+C).
How can I correct it?
You can either
reserve some input string used for terminating the program, as suggested by JJ, or
you could rely on the user closing the input stream with Ctrl+D, or you could
enclose the loop in a try/catch and let another thread interrupt the main thread which then exits gracefully.
do System.in.close() programatically from another thread.
This is a reply to a comment above. Here, the application will quit when receiving "quit".
import java.util.Scanner;
class newClass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String temp = s.next();
if(temp.trim().equals("quit"))
System.exit(0);
System.out.println(s.next());
}
s.close();
}
}
The Scanner will block waiting for input from System.in (standard input). You have to press Ctrl+C to exit the program, close the Input stream by pressing Ctrl+D or give the loop an exit condition (like typing "quit"), here is how you could do that:
import java.util.Scanner;
class newClass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String nextVal = s.next();
if (nextVal.equalsIgnoreCase("quit")) { break; }
System.out.println(nextVal);
}
s.close();
}
}

Categories

Resources