Java BufferedReader readLine() suddenly not working after read() - java

I am currently having a problem with my loop. After I inputted a string once, it prompts the user and when the loop conditions were met, it just keeps asking the user "do you want to continue?" and was unable to enter another string.
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
LinkedList<String> strList = new LinkedList();
char choice;
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
choice = (char)bfr.read();
}
while(choice == 'Y');
}

You need to get the newline character out of the keyboard buffer. You can do this like this:
do
{
System.out.print("Add Content: ");
strList.add(bfr.readLine());
System.out.print("Do you want to add again? Y/N?");
//choice = (char)bfr.read();
choice = bfr.readLine().charAt(0); // you might want to check that a character actually has been entered. If no Y or N has been entered, you will get an IndexOutOfBoundsException
}
while(choice == 'Y');

Usually the terminal only sends the data once you hit enter. So you get an empty line when you perform readLine again. You have to read a line, then check if it contains Y instead. Or read the empty line afterwards, whichever you think is less error prone.
I tend to use the earlier and read a full line, then check what it contains.

Don't forget that for something simple as this program you can use the convenient java.io.Console class.
Console console = System.console();
LinkedList<String> list = new LinkedList<>();
char choice = 'N';
do {
System.out.print("Add Content: ");
list.add(console.readLine());
System.out.print("Do you want to add again? Y/N?\n");
choice = console.readLine().charAt(0);
} while (choice == 'Y' || choice == 'y');

This work (don't forget library):
public static void main(String[] args) throws IOException
{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
List<String> strList = new ArrayList<String>();
String choice;
do {
System.out.println("Add Content: ");
strList.add(bfr.readLine());
System.out.println("Do you want to add again? Y/N?");
choice = bfr.readLine();
} while(choice.equals("Y"));
System.out.println("End.");
}

Try this :
public static void main(String[] args) throws IOException
{
Scanner scan=new Scanner(System.in);
LinkedList<String> strList = new LinkedList();
String choice;`
do
{
System.out.print("Add Content: ");
strList.add(scan.nextLine());
System.out.print("Do you want to add again? Y/N?");
choice = scan.nextLine();
}
while(choice.equals("Y"));
}

Related

how to break or continue a loop from user input

I'm trying to write a code that loops when y is entered and stops when n is entered, this is what I have so far.
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext());{
input.hasNext("y");
}
I have no clue how to continue.
For more readable code you can use a boolean variable and assign it to true according to your input equals to "y" condition
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean stopFlag= false;
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
String userInput =input.next();
if(!userInput.equals("y"))
stopFlag=true;
}while (!stopFlag);
}
You can do this:
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String temp = input.next();
if(temp.equals("y")) {
// if you need to do something do it here
continue; // will go to the next iteration
} else if(temp.equals("n")) {
break; // will exit the loop
}
}
If you are persistent on using do...while then you can try:
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext() && !input.next().equals("n"));

How to take multi-line input in Java

I'm trying to take multi-line user input in Java and split the lines into an array, I need this to solve a problem for an online judge. I'm using a Scanner to take input. I cant determine the end of input. I always get an infinite loop, since I don't know the size of input (i.e number of lines)
Terminating input with an empty String (clicking enter) is still an infinite loop. Code provided below.
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine() == true){
in.add(s.nextLine());
//infinite loop
}
}
I'm not even sure why the loop executes the first time. I believe the hasNextLine() should be false the first time ,since no input was taken yet. Any help or clarification appreciated.
You could use the empty line as a loop-breaker:
while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}
You could end the loop with something like below. Here, the String "END" (case-insenstive) is used to signify end of the multi-line content:
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine()) {
String line = s.nextLine();
in.add(line);
if (line != null && line.equalsIgnoreCase("END")) {
System.out.println("Output list : " + in);
break;
}
}
}
You can use this code. It returns when the user press Enter on an empty line.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> arrayLines = new ArrayList<>();
String line;
while(true){
line = scanner.nextLine();
if(line.equals("")){
break;
}
else {
System.out.println(line);
arrayLines.add(line);
}
}
System.out.println(arrayLines);
}
}
Best
You can do somthing like this:
while (s.hasNextLine() == true){
String line = s.nextLine();
if ("".equals(line)) {
break;
}
in.add(line);
//infinite loop
}

Java Input not working (Beginner)

For some reason, my code will not accept input on the last line "What would you like to order: "
Could anyone tell me what my error is here? It is compiling correctly and everything. I am only a beginner so please tell me in basic terms.
import java.util.Scanner;
import java.util.*;
class RestaurantMain {
public static void main(String[] args)
{
//Create an array list
ArrayList menu = new ArrayList();
//Variables//
int choice;
int customerChoice;
boolean trueFalse;
int restart = 0;
String choice2;
String addItems = "";
int menuCount = 0;
int indexCount = 0;
String item = "";
//Import input device
Scanner in = new Scanner(System.in);
ArrayList theMenu = new ArrayList();
System.out.println("Welcome to the Cooper's restaurant system!");
System.out.println("How can I help?");
System.out.println("");
System.out.println("1. Customer System");
System.out.println("2. Management System");
System.out.println("");
System.out.println("");
System.out.print("Which option do you choose: ");
choice = in.nextInt();
if (choice == 1) {
System.out.println("Our menu's are as follows:");
System.out.println("");
System.out.println("1. Drinks");
System.out.println("2. Starters");
System.out.println("3. Mains");
System.out.println("4. Desserts");
System.out.println("");
System.out.println("Please note - You MUST order 5 items.");
System.out.println("");
System.out.print("What menu would you like to follow? ");
customerChoice = in.nextInt();
if (customerChoice == 1) {
System.out.println("Drinks Menu");
System.out.println("Would you like to order? ");
choice2 = in.nextLine();
if (choice2 == "yes") {
System.out.println("Please enter the amount of items you want to order: ");
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
}
if (customerChoice == 2) {
System.out.println("Starters Menu");
}
if (customerChoice == 3) {
System.out.println("Mains menu");
}
if (customerChoice == 4) {
System.out.println("Desserts Menu");
}
You need to call in.nextLine() right after the line where you call in.nextInt()
The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine()
customerChoice = in.nextInt();
in.nextLine();
This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line. Consider using a BufferedReader object instead!
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int integer = Integer.parseInt(reader.readLine());
This will throw the same errors that Scanner.nextInt() does if the input can't be parsed as an integer.
Regarding your comment about errors, there is one:
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
Should instead be like the following:
while(indexCount <= menuCount){
System.out.println("Please enter your item: ");
item = in.nextLine();
theMenu.add(item);
}
Also, it isn't strictly necessary, but I suggest that you do declare the ArrayList's generic type when instantiating the list, so that further calls to theMenu.get() don't need to be casted to a String.
ArrayList<String> theMenu = new ArrayList<String>();
When comparing strings, ensure that you use the str.equals("string to compare with") method, instead of the equality operator (==). Therefore for example, choice2 == "yes" should instead be choice2.equals("yes"). Using equalsIgnoreCase instead of equals would ignore case differences, which may be useful in this situation.
insted of in.nextLine(); function you just try another scanner functions like 'in.next()'. just R&D with the methods that already give the JVM itself.
you just use correct the logic and use equal() or equlIgnoreCase() methods insted of "=" operator.

reading single character in java

public class pattern7 {
public static void main(String args[])
throws java.io.IOException{
char c;
do
{
System.out.print("*");
System.out.println("\ndo you want more");
c=(char)System.in.read();
}while(c=='y');
}
}
the above code should print the * as long as i press 'y' but it does not do so. it let the user to enter choice just once. i know the reason behind this as it uses "enter" as its second value. but i don't know how to make it work. suggest me the code to do the same action properly
it takes enter key press as a new character. So capture that key press add another read command.
do
{
System.out.print("*");
System.out.println("\ndo you want more");
do {
c=(char)System.in.read();
} while (Character.isWhitespace(c));
} while (c=='y');
If the 'y' character will always be followed by an enter, just always read the full line and check if it only contains the 'y' character:
Option 1: BufferedReader
You can use InputStreamReader in combination with BufferedReader to get the full line the user entered. After that, you check that it is not null and only contains 'y'.
try {
// Get the object of DataInputStream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null && line.equals("y") ) {
System.out.print("*");
System.out.println("\ndo you want more?");
}
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Option 2: Scanner
The same as above can be achieved by using the java.util.Scanner class:
Scanner scan = new Scanner(System.in);
scan.nextLine(); // reads a line from the console. Can be used instead of br.readLine();
You can do this by using Scanner. Here is my code-
public class pattern7 {
public static void main(String args[])
throws java.io.IOException{
char c;
Scanner reader = new Scanner(System.in);
do
{
System.out.print("*");
System.out.println("\ndo you want more");
c=reader.next().charAt(0);
}while(c=='y');
}
}

Java: Using scanner to read in boolean values failing.

import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}

Categories

Resources