• 0

[Java] Reading a line of text from Console?


Question

I'm trying to read a integer number from the keyboard and I have the following code

String line;
  int val = 0;
  BufferedReader is = new BufferedReader (new InputStreamReader (System.in));
  System.out.println("Type a number: ");
  line = is.readLine();
  val = Integer.parseInt(line);
  System.out.println("I read this number "+ val);

But when I run the program, the console displays "Type a number: " and before letting me even type a number, it gives me all kinds of errors, complaining that I'm trying to parse an empty string to an integer. Can anyone tell me what's wrong?

Link to comment
Share on other sites

16 answers to this question

Recommended Posts

  • 0

import java.io.*;

public class ReadString {

public static void main (String[] args) {

// prompt the user to enter their name

System.out.print("Enter your name: ");

// open up standard input

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String userName = null;

// read the username from the command-line; need to use try/catch with the

// readLine() method

try {

userName = br.readLine();

} catch (IOException ioe) {

System.out.println("IO error trying to read your name!");

System.exit(1);

}

System.out.println("Thanks for the name, " + userName);

}

} // end of ReadString class

Link to comment
Share on other sites

  • 0

if you want to read input for a while do something like this

String s;

try {

while ( (s = br.readLine ()) != null ) {

// do something

System.out.println(s);

if (s.equalsIgnoreCase("EXIT"))

break;

}

}

catch ( IOException ioe ) {

// won't happen too often from the keyboard

}

Link to comment
Share on other sites

  • 0

Okay I figured out something, the piece of code that I just posted was actually a function, and if I put that code into a empty main function, it works fine. So something must be wrong with my original code. Here it is:

public static void main(String[] args) throws IOException
	{
  int number = 0;
  char response;
  System.out.print("Calculate a square root? (y/n): ");
  
  response = (char)System.in.read();
  
  getNumber(number);
	}
	public static void getNumber(int number) throws IOException
	{
  BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
  String num = null;
  System.out.print ("Please enter a positive real number: ");
  num = is.readLine();
  number = Integer.parseInt(num);
  if (number < 0)
  {
 	 System.out.println("\n***Sorry, that is not a positive real number! ***");
  }
	}

And the computer won't let me type when I run this program. Anyone know why? I am pretty sure nothing's wrong, everything compiles, so I don't know what's wrong at all!

Link to comment
Share on other sites

  • 0

I reworte the program quickly,

on another note you problem in your original code was you tried to parse "" as a number.

I did this to check for "". if not "" then it is valid input

while ( (s = is.readLine ()) != null ) {

if (!s.equals(""))

break;

Link to comment
Share on other sites

  • 0
on another note you problem in your original code was you tried to parse "" as a number.

I know, but the problem is I didn't even type a thing, I couldn't type. The program would run and skip straight to the error, without me typing anything.

Link to comment
Share on other sites

  • 0

//this is a bit better in terms of structure/OOP

public class SqRoot {

private BufferedReader is = new BufferedReader(new InputStreamReader(System.in));

//main class

public static void main(String[] args)

{

SqRoot = new SqRoot();

}

//constructor

SqRoot()

{

super();

run();

}

//similar to main stub

public void run()

{

try

{

//get input

printHeader();

System.out.print("Calculate a square root? (y/n): ");

String response = getConsoleInput();

if (response.equalsIgnoreCase("Y"))

getNumber();

}

catch (Exception e)

{

System.out.println("Error Reading From Standard Input: "+e.getMessage());

}

System.out.println("Quitting Program!");

}

// reads console input

private String getConsoleInput() throws IOException

{

String s;

while ( (s = is.readLine ()) != null )

{

if (!s.equals(""))

break;

}

return s;

}

//get the square of a number

public void getNumber()

{

String s = "";

while(true)

{ try

{

System.out.print("Please enter a positive real number (Type 'Q' for Quit ): ");

s = getConsoleInput();

if(s.equalsIgnoreCase("Q"))

break;

else

{

int num = Integer.parseInt(s);

if (num < 0)

throw new Exception("Can Not Square 0");

else

System.out.println("Sqare root of "+num+" is xxx");

}

}catch(Exception e)

{

System.out.println("\n***Sorry ["+s+"] is not a positive real number! ***");

}

}

}

// print header

private void printHeader()

{

System.out.println("**********************************");

System.out.println("* Square Root Me *");

System.out.println("**********************************");

}

}

Link to comment
Share on other sites

  • 0

I appreciate your help liykh001 but this does not help me explain why my original code wouldn't work. Can you spot anything wrong?? Thanks for the help though!

Link to comment
Share on other sites

  • 0
I know, but the problem is I didn't even type a thing, I couldn't type.  The program would run and skip straight to the error, without me typing anything.

this is because the system already read a blank string, all you have to do is test for null and "". if it is null or "", then try and read the next line.

thus the while loop I put in the code

(REASON Readln didnt allow you to enter anything was because it had already picked up the Return/Enter character entered by you on the previous line)... ie buffer had "" in it so it didnt wait for you to enter anything

The return character is translated into ""

you need to test for "" and nulls returned by readln()

Edited by liykh001
Link to comment
Share on other sites

  • 0

System.out.print ("Please enter a positive real number: ");

num = is.readLine();

number = Integer.parseInt(num);

CHANGE TO THIS

System.out.print ("Please enter a positive real number: ");

while ( (num = is.readLine ()) != null )

{

//if NOT = ""

if (!num.equals(""))

break;

}

number = Integer.parseInt(num);

Link to comment
Share on other sites

  • 0
CHANGE TO THIS

System.out.print ("Please enter a positive real number: ");

while ( (num = is.readLine ()) != null )

{

//if NOT = ""

if (!num.equals(""))

break;

}

number = Integer.parseInt(num);

Thanks! It works now. But what do you mean by already read in a blank string?? Where did it read in a blank string?

Link to comment
Share on other sites

  • 0
Thanks!? It works now.? But what do you mean by already read in a blank string??? Where did it read in a blank string?

I'll give u an exampl/n/i> = newline character which is "" when converted to string - new line char is created when you press enter or return key)

OUT refers to system.out

IN refers to what you have entered into the console

OUT Line 1>Calculate a square root? (y/n):

IN Line 1&y/n/i>

when you get Char = y - t/n/i> is still in the standard in buffer

OUT Line2>Enter Number:

IN Line2&/n/i> - before you even get a change to type this is read in

- the readln picked up the remaing string inputed by you from the previous line

I think your problem might be caused by

response = (char)System.in.read();

try using readln!!!!!!!!

on another note have a look at my example class I created. notice I dont need to use static functions

you should always create an instance of you class as I have done in my example main method.

Link to comment
Share on other sites

  • 0
when you get Char = y - the /n is still in the standard in buffer

OHHHH that's why.....I guess I will use readLine from now on to prevent any more errors like these. By the way, does readLine remove the \n character from the input stream??

Link to comment
Share on other sites

  • 0

Yeah I tried it, readLine() does remove the \n character from the input stream, so I guess I'll be using readLine() from now on to prevent any problems with the \n character still left on the input stream! Thanks liykh001!! You really helped me out a lot!

Link to comment
Share on other sites

  • 0

Your welcome,

As I said before, look at the class I designed. This class is OOP, the class you designed was more procedual programming based.

Although readLine picks up the \n char from the buffer, you should alway have a try catch and test for "" characters. what happens if you try and cast input which is non-integer? you should handle these exception.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.