hasNext() function does no terminate while loop - java

public class EOF {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=1;
while(sc.hasNextLine()==true)
{
String str = sc.nextLine();
System.out.println(i+" "+str);
i++;
}
System.out.println("completed");
}
}
The last line System.out.println("completed"); is not executing. The loop does not terminate and is continuously running.

From the documentation for Scanner.hasNextLine():
This method may block while waiting for input.
That means that if there isn't input waiting to be returned, it will sit and wait for more input to come in.
If your Scanner is accepting input from System.in, you need to find a better way of deciding when you want to finish input. For instance, if the user types "quit", or if they input a blank line.

please use this
public class EOF {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=1;
while(sc.hasNextLine()==true)
{
String str = sc.nextLine();
System.out.println(i+" "+str);
i++;
if(str.equals("stop")){
break;
}
}
System.out.println("completed");
}
}

Related

Java program for splitting strings with line breaks and stops with no entry not working?

This is the problem I'm trying to solve:
My code is the following:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why. Any explanations?
You should arrange your code like:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true) part:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:
Scanner scanner = new Scanner(System.in);
outside of the while loop.
The reason:
You only need to create a single Scanner object. This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.
You can also think about it more mechanically than that:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right? Its quite a similar thing in this case.

How do I make this loop such that the output is the same as the input unless i press "end" then the programme ends?

Hi I am new to java programming and I have this code and I want to know how to make it run until i type "end" then it stops.
Can anyone help? I keep getting an error
public static void main(String [] args){
String code_trigger_starter_str = "start";
String code_trigger_ender_str = "end";
//boolean program_running_bool = false;
Scanner kybd_inpt = new Scanner(System.in);
String kybd_input_str = kybd_inpt.nextLine();
re_run_word_input(code_trigger_starter_str,code_trigger_ender_str);
// exit_code(code_trigger_ender_str);
}
private static void re_run_word_input(String code_trigger_starter_str,String code_trigger_ender_str) {
//boolean program_running_bool = true;
System.out.println("Enter a word");
Scanner kybd = new Scanner(System.in);
String kybd_new_word = kybd.nextLine();
//if(kybd_input_str.equals(code_trigger_starter_str));{
//System.out.println(kybd_new_word);
if(!kybd_new_word.equals(code_trigger_ender_str)) {
System.out.println(kybd_new_word);
}
else {
if (kybd_new_word.equals(code_trigger_ender_str)) {
System.out.println("Program ended");
}
}
}
I found a solution that works. I used a do while loop.
import java.util.Scanner;
public class WeekendAssignment {
public static void main(String [] args){
//Initialize start and end variables
String code_trigger_starter_str = "start";
String code_trigger_ender_str = "end";
// receive start input in string kybd_input_str
Scanner kybd_inpt = new Scanner(System.in);
String kybd_input_str = kybd_inpt.nextLine();
//using do-while loop to run the method continuously
do {
re_run_word_input(code_trigger_starter_str,code_trigger_ender_str);
}
while (true);
}
//create a new method to receive new words input and output the new word
private static void re_run_word_input(String code_trigger_starter_str,String code_trigger_ender_str) {
//Tell user to input a word
System.out.println("Enter a word");
Scanner kybd = new Scanner(System.in);
String kybd_new_word = kybd.nextLine();
//set condition using if and else statements
if(!kybd_new_word.equals(code_trigger_ender_str)) {
System.out.println(kybd_new_word);
}
else {// if user inputs "end" code has to terminate
if (kybd_new_word.equals(code_trigger_ender_str)) {
System.out.println("Program ended");
System.exit(0);
}
}

How to validate scanner input using a different method?

import java.util.Scanner
public class Editable {
/* Return true if amount is within MIN_AMOUNT and MAX_AMOUNT
*/
public static boolean isValidAmount(double amount) {
return amount > MIN_AMOUNT && amount < MAX_AMOUNT;
}
/* Asks user to input amount until isValidAmount is true.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(system.in);
}
I'm new to Java and I've been struggling with this for quite a bit.
I'm asking for user input in main and I need it to keep asking for user input until isValidAmount returns true. I have tried multiple different solutions but can't seem to get it to work.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double inputAmount = 0;
try {
while (!isValidAmount(inputAmount)) {
System.out.println("Enter amount:");
inputAmount = scanner.nextDouble();
scanner.next();
}
} catch (Exception e) {
System.out.println("Input error.");
scanner.next();
}
First you only need a nextDouble. scanner.next() would read the next value and discard it. Also, try using a do while loop:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double inputAmount = 0;
try {
do {
System.out.println("Enter amount:");
inputAmount = scanner.nextDouble();
} while (!isValidAmount(inputAmount));
} catch (Exception e) {
System.out.println("Input error.");
scanner.next();
}
}
I think perhaps your inputAmount was already a valid value before prompting the user. The do while loop will always execute the statements between the brackets before checking the condition. The while loop will no execute the statements in the brackets if the condition is already false.
Just comment out scanner.next();. You don't need it. Your program is perfect otherwise. (I am assuming that MIN_AMOUNT is declared to be > 0).

Multi-word scanner input in java?

So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}

Java: why is this code not working? Infinite loop?

So as you may be able to tell from my attempt, I'm trying to figure out how I'd make a program which gives the user 5 seconds to enter some lines of text, then the Scanner will count how many lines were entered. I've just started learning Java as my 2nd language, so please try to explain everything as simply as possible :)
I've got two theories as to why it's not working. The first is that nextLine() will return the whole line, regardless of whether it's empty or not meaning rather than NL equaling "", it will actually equal the whole line (ie " "). And my second theory is that I've got no idea what I'm doing and the program flow is all over the place. Anyway, here's my code:
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
String NL = ScanObj.nextLine();
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (!NL.equals("")){
Count++;
NL = ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}
Oh, I forgot to mention hasNext() was what I originally tried:
import java.util.Scanner;
class OrigClass{
public static void main(String args[]){
Scanner ScanObj = new Scanner(System.in);
int Count = 0;
try{
Thread.sleep(5000);}
catch (InterruptedException e){
e.printStackTrace();
}
while (ScanObj.hasNext() == true){
Count++;
ScanObj.nextLine();
}
System.out.print("You Entered " + Count + " Lines.");
ScanObj.close();
}
}
From the looks of it, this code should work. My only guess is that you are manually entering the input and are forgetting to signal the end of input with CTRL+D. However, doing this, you'll get a NoSuchElementException if you do not use ScanObj.hasNext().
You could also run your code using input redirection. java OrigClass < data
A better way to do this would be the following:
import java.util.Scanner;
public class Sc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 0;
String nl; // = scan.nextLine();
//while (!NL.equals(""))
while(scan.hasNext())
{
count++;
nl = scan.nextLine();
}
System.out.println("Done! Count: " + count);
scan.close();
}
}
The difference here is that we save the first nextLine() until we're in the while loop. This will give an accurate count of how many lines are in the input.
Just don't forget to signal end of input with CTRL+D.
Well this solution is not really good. but works.
public class FiveSecond {
public static void main(String args[]){
new Thread(new Count(new Reader())).start();
}
}
class Count implements Runnable{
Reader r;Thread t;
Robot ro;
public Count(Reader t){this.r=t;
try {
ro=new Robot();
} catch (AWTException e) {e.printStackTrace();}
}
#Override
public void run() {
t=new Thread(r);
//t.setDaemon(true); //[S2]
t.start();
try{
Thread.sleep(5000);
}catch(Exception e){}
t.interrupt();
//Implicitly press the enter key in order to release the readLine() method :D
//not recommended, and it's not a good idea, but works
ro.keyPress(KeyEvent.VK_ENTER);
ro.keyRelease(KeyEvent.VK_ENTER);
/*
* this is possible to save the strings lines in somewhere in order to access from invoker application
* or send back the strings by socket, etc . . .
*/
System.out.println("number of entered lines "+r.getCount()+"\n");
//you would run this main as a process and get the number of counts
//System.exit(r.getCount()); //[S2]
}
}
class Reader implements Runnable{
private List<String> lines;
private volatile int count;
private BufferedReader br;
public Reader(){
lines=new ArrayList<String>();
br=new BufferedReader(new InputStreamReader(System.in));
}
#Override
public void run() {
try{String line;
System.out.println("you have 5 second to detect a 2048 length character, then your system will broken");
while((line=br.readLine())!=null){
if(!Thread.currentThread().isInterrupted()){
count++;lines.add(line);}else{break;}
}
//for showing the lines entered
//System.out.println(lines.toString());
}catch(Exception ex){}
}
public int getCount(){return this.count;}
}
but the best approach is about running a separated process to count the lines, and you would just remove the [S2] comments to achieve it.

Categories

Resources