Facing problem while trying to print using PrintWriter.
Problem Description:
I am expecting to print the Press options first then take the user input but using out.println i can't do that. It's not printing the options while i run the program. It just waits for an input while i give the input it then prints the Press options.
Note: if i use System.out.println then it works as expected.
Tried it like below
public class Calculator {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer took = new StringTokenizer(" ");
String operator;
// System.out.println("Press '+' for Additon");
// System.out.println("Press '-' for Subtraction");
// System.out.println("Press '*' for multiplication");
out.println("Press '+' for Additon");
out.println("Press '-' for Subtraction");
out.println("Press '*' for multiplication");
out.println("Press '/' for Division");
operator=in.readLine();
switch (operator) {
case "+":
out.println("Add");
break;
case "-":
out.println("Subtract");
break;
case "*":
out.println("Multiply");;
break;
case "/":
out.println("Division");
break;
}
in.close();
out.close();
}
}
Input:
*
Output:
Press '+' for Additon
Press '-' for Subtraction
Press '*' for multiplication
Press '/' for Division
Multiply
Do:
out.flush();
Before you read in, and then before you close the out.
Or you can do:
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out), true);
What the true does is sets it to auto flush every time you print.
Suggest reviewing the Javadoc for the PrintWriter.
Related
I have a lexer that accepts Reader object. Initially it is intended to parse files, but
I want to run lexer with stdin to make a repl
so, here is my code
private static void launchRepl() {
final var reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("> ");
var lexer = new Lexer(reader);
while (true) {
var token = lexer.readToken();
var ttype = token.tokenType();
if (ttype == TokenType.Eof || ttype == TokenType.StatementEnd) {
break;
}
System.out.println(token);
}
}
}
In the language i tokenize, new line is of TokenType.StatementEnd. But when I write new input to the console and hit enter, my lexer does not see this new line character and blocks, until i press enter one more time. So it works like:
> 1 + 2
Number 1
Operator +
Number 2
(waiting for another enter) *hits enter*
>
I want to fix so it sees \n at the end of the prompt
Running into an error with this project I'm working on for a computer science course, and hoping someone can give me insight into what may be happening. A bit of background to what's occurring in the code:
In the below code, I have the start of my program which displays a UI menu and asks for user input and uses a switch statement to run appropriate methods based on user input.
/**
* Start of program
*/
public static void main(String[] args) {
Library library = new Library();
char userChoice; //Stores what menu item the user chose
Scanner userMenuChoiceScanner = new Scanner(System.in);
boolean loop = true;
displayMenu(); //Displays main UI menu
userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0)); //Gets user's menu choice
/*Loops UI menu afer user has made menu choice and exits loop if user choses 'q' from menu.*/
while(loop) {
/* Switch descides what menu choice user has made and whether to prin menu UI again, load,
* search, print, or analyze a music catalog, or to quit program.
*/
switch(userChoice) {
case 'm':
System.out.println();
displayMenu();
userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
break;
case 'p':
System.out.println();
if(library.getBooks().size() != 0) {
printLibrary(library);
} else {
System.out.println("There are no books in the library. Please add a book first.");
}
System.out.print("Please enter a command (press 'm' for Menu):");
userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
break;
case 'a':
System.out.println();
addBookToLibrary(library);
System.out.print("Please enter a command (press 'm' for Menu):");
userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
break;
case 'd':
System.out.println();
if(library.getBooks().size() != 0) {
deleteBookFromLibrary(library);
} else {
System.out.println("There are no books in the library. Please add a book first.");
}
System.out.print("Please enter a command (press 'm' for Menu):");
userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
break;
case 'r':
System.out.println();
if(library.getBooks().size() != 0) {
readBookFromLibrary(library);
} else {
System.out.println("There are no books in the library. Please add a book first.");
}
System.out.print("Please enter a command (press 'm' for Menu):");
userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
break;
case 'q':
System.out.println();
System.out.println("Thank you! Goodbye!");
loop = false;
break;
default:
System.out.println();
System.out.println("Invalid selection!");
System.out.print("Please enter a command (press 'm' for Menu):");
userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
System.out.println();
}
}
userMenuChoiceScanner.close();
}
What's occuring is when tthe user makes a choice, it goes into the appropriate methods and fulfills it's tasks there, then when it returns to the switch statement to get a new user input, it throws a java.util.NoSuchElementException error as if the scanner stream was closed, but I don't close the scanner until the end (the stream should still be open).
The switch statement is set up in a way where a book must be added (the user must chose 'a' first) before any other option can be chosen. Here is the code to he addBookToLibrary() method which has a couple scanners which are opened and closed. I assume maybe closing out these scanners may be causing the issue?
/**
* Adds new book to library
* #param library ArrayList object which holds book objects
*/
public static void addBookToLibrary(Library library) {
Scanner addBookScanner = new Scanner(System.in);
String title = "";
String author = "";
String genre = "";
String filename = "";
boolean addStatus = false;
/*Asks user for book details */
System.out.println("Enter the details of the book you want to add to the library:");
System.out.println("What is the book title?");
title = addBookScanner.nextLine();
System.out.println("What is the author's name?");
author = addBookScanner.nextLine();
System.out.println("What is book genre?");
genre = addBookScanner.nextLine();
System.out.println("What is the book's filename?");
filename = addBookScanner.nextLine();
addBookScanner.close();
Book newBook = new Book(author, title); //creates new book with author and title set
newBook.setGenre(genre); //sets book genre
File bookFile = new File(System.getProperty("user.dir") + '\\' + filename); //used to check if file user provided exists
System.out.println(bookFile);
/*Checks to see if file user provided actually exists*/
if(bookFile.exists()) {
try {
newBook.setFilename(filename);
}catch(Exception e) {
}
}
else {
Scanner getNewFilenameScanner = new Scanner(System.in);
//Continues to ask user for new filename if file doesn't exist
do {
System.out.println("I'm sorry, but the file you specified does not exist.");
System.out.print("Enter a new file name:");
bookFile = new File(getNewFilenameScanner.nextLine());
}while (!(bookFile.exists()));
getNewFilenameScanner.close();
}
addStatus = library.addBook(newBook); //adds book to library
if(addStatus) {
System.out.println("Book was successfully added!");
}
else {
System.out.println("Book was not successfully added. Please try again.");
}
}
This code worked perfectly in a previous project, so I'm not certain why it's not working now. Any help would be greatly appreciated.
Thank you so much
In your addBookToLibrary method, you close the Scanners after you are done using them. However, those scanners are connected to System.in, the standard input stream. Closing those scanners will also close the standard input stream, according to the documentation.
What else is connected to the standard input stream? userMenuChoiceScanner! After the standard input stream is closed, userMenuChoiceScanner can't read from it, hence throwing an exception.
Note that although userMenuChoiceScanner is not closed until the very end, the stream that it is reading from is closed.
In fact, you don't need to create multiple scanners here. You only need to use one scanner, and pass it around to different methods. For example, addBookToLibrary could accept a Scanner:
public static void addBookToLibrary(Library library, Scanner s) {
And it will only use s to read inputs. You can pass your userMenuChoiceScanner to it:
addBookToLibrary(library, userMenuChoiceScanner);
As a general rule, you should not close anything that is not opened by you. You didn't open the standard input stream (the JVM did), so you shouldn't close it.
I've been writing my first Java script and have ran into an issue. I do not understand why when this is ran the program waits for the user to input something on the first time the loop runs, then the input is dealt with and the corresponding response is made, but the second time it runs it gets stuck in an infinite loop without waiting for the user's input. For the record, I do want this to be an infinite loop, except that the program should end if the user enters "3". If after each case I write "keep_going = false;" the program functions, but doesn't keep looping, obviously. All help is appreciated, thanks!
import java.io.*;
class Choice
{
public static void main (String[] args)
{
String input = "";
Boolean keep_going = true;
while (keep_going)
{
input = "";
System.out.println("Welcome to my program! Would you like to:");
System.out.println("1. Say hi.");
System.out.println("2. Find out my favourite colour.");
System.out.println("3. End the program.");
System.out.println(">");
System.out.print( "> " );
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader buffer = new BufferedReader( isr );
try
{
input = buffer.readLine();
buffer.close() ;
}
catch (IOException e )
{
System.out.println(e);
}
switch (input)
{
case "1": System.out.println("Hi!"); break;
case "2": System.out.println("My favourite colour is blue!"); break;
case "3": return;
default : System.out.println(input + " is not a valid option. Please try again.");
}
}
}
}
the infinite loop was due to line buffer.close() ;
Make this adjustments
remove buffer.close() ;
//buffer.close() ;
case "3": keep_going=false;break;
I am trying to open a text file within a switch statement but I am getting the error 'Illegal start of expression'. I am new to Java so as simple as possible explanation would be appreciated!
Here is my code, ignore the other switch cases:
import java.util.Scanner;
public class journeyPlanner {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println(" -- MAIN MENU -- \n 1: Display Journeys \n 2: Identify Suitable Journeys \n Q: Quit \n Pick:");
String Choose = in.next();
switch (Choose) {
case "1" : BufferedReader in = new BufferedReader(new FileReader (<"Input.txt">));
break;
case "2" : System.out.println("You answered: " + Choose + ". Please try again.");
break;
case "Q" : System.out.println("You answered: " + Choose + ". That is correct!");
break;
default:
System.out.println("Please select a valid answer choice.");
}
}
}
Lets break down the 3 things wrong here:
< and > surrounding the filename
duplicate variable declaration in
missing throws
First off the compiler complains about the < and >. Fixing them will show problem number 2, fixing that will reveal problem number 3.
All three can be resolved by changing the main to throwing an exception (or alternatively / better catching it):
public static void main(String[] args) throws FileNotFoundException
and changing the BufferedReader line to:
case "1" : BufferedReader in2 = new BufferedReader(new FileReader ("Input.txt")); break;
Final recommendation: indent your code properly
Hum, you've got a duplicate variable in and you have a syntax error new FileReader("Input.txt").
I suggest you to use a real ide that can help you on this kind of syntax errors...
I think you got an syntax error there:
new FileReader (<"Input.txt">)
Remove the greater and lower than sign and it should work.
Another error is that you named two variables the same in ONE method:
Scanner in
and
BufferedReader in
I think it has nothing to do with the "switch/case" syntax.
To gain more "overview" over your switch case, you can set braces:
switch (bla) {
case FOO: {
// [...]
break;
}
}
Well this worked for me:
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
Scanner in = new Scanner(System.in);
System.out.println(" -- MAIN MENU -- \n 1: Display Journeys \n 2: Identify Suitable Journeys \n Q: Quit \n Pick:");
String Choose = in.next();
switch (Choose) {
case "1":
{
// first we'll try to open the file
try {
BufferedReader br = new BufferedReader(new FileReader("Input.txt"));
} catch (FileNotFoundException ex) {
// if the file does not exist, we'll create one
PrintWriter writer = new PrintWriter("Input.txt", "UTF-8");
}
}
break;
Of course I had to add some imports (BufferedReader, FileNotFoundException, FileReader, PrintWriter, UnsupportedEncodingException, Scanner).
The problem was that you have already assigned variable in (Scanner) and then you created BufferReader in.
Second problem was that you used angular brackets where you shouldn't.
You can skip the try catch block for checking the existence of the file. Hope it helps.
I'm writing a java program that will take int input as a option from the user. Based on the input the program will go to different method.But when i run code it gives the following error
Exception in thread "main" java.lang.NullPointerException
at lab1.EchoClient.main(EchoClient.java:25)
part of my code
private Scanner reader;
public static void main(String[] args){
EchoClient c = new EchoClient();
int option;
System.out.println("Welcome");
System.out.println("Select one of the following options:");
System.out.println("1 - Iterative Server");
System.out.println("2 - Concurrent Server");
System.out.println("3 - Exit");
option = c.reader.nextInt(); // Line No 25
switch(option){
case 1:
c.iterative();//calls the iterative method
break;
case 2:
//some method
break;
case 3:
System.out.println ("bye bye");
break;
}//end of switch()
}//end of main()
public void iterative(){
String address;
String ip="";
try{
System.out.println ("Please enter your correct ip address");
BufferedReader getip= new BufferedReader (newInputStreamReader(System.in));
ip=getip.readLine();
}
catch (IOException error){
System.err.println("Error occured");
}
At line 25 is the line : option = c.reader.nextInt();
You need to build reader according to the instance you want to scan.
In your case this should look like:
Scanner reader = new Scanner(System.in);
Then, following your code snippet, you should set the reader owned by your instance of EchoClient to the built Scanner.
reader is never initialized, so it's still null.
It looks like when you create your new EchoReader c, it doesn't set the reader attribute - then when you try c.reader, you get null, leading to the NPE when calling nextInt(). Double-check that your EchoReader constructor sets the reader attribute.
reader is never initialised as far as I can tell
...did you define your private Scanner reader?
Scanner reader = new Scanner(System.in);