Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Simple solution to input?

  Asked By: Lloyd    Date: May 18    Category: Java    Views: 859
  

Am writing a program that requires a few user inputs. The problem is
then the user enters nothing and hits return or say enters a char
when I've asked for an int, the thing crashes.

Being a newbie (using the consolewindow element of java along with
java), I've been typing stuff like the following:

c.out.println("Do you wish to proceed? Y or N)
response =c.input.readString().charAt(0)

response here being declared early on as char response

Fine if a char is entered, but not when an int or just return is hit!

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Timothy Patterson     Answered On: May 18

Try using a BufferedReader. Assuming c.input is an InputStream object,
you can use

BufferedReader input  = new BufferedReader(c.input);

Then just do "input.readLine();" which returns a String and then
convert it to the type you actually want.

 
Answer #2    Answered By: Jezza Brown     Answered On: May 18

String line = c.input.readString();
if(line==null || line.length==0)
{
deal with no input
}
else
{
response = line.charAt(0);
..........
}

 
Answer #3    Answered By: Norman Ray     Answered On: May 18

while(!(response=='Y'||response=='N')){
c.out.println("Do you wish to proceed? Y or N)
try{
response =c.input.readString().charAt(0)
}catch(Exception ignore){
response='?';
}
}

Excepitons all for newbies, so what was the question.

 
Answer #4    Answered By: Leon Evans     Answered On: May 18

Try this,
------------------------------------------------------------
.......... you code..........
try {

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

String userText = in.readLine(); // return  String from System's default input
stream

// Converting user input  from String to int

int userValue = 0; // to be safe from null value
userValue = Integer.parseInt( userText ); // this will throw
NumberFormatException if user  have entered  something except integer value

// This section will only print if user input was interger
System.out.println(" You entered: " + userValue );

}
catch(NumberFormatException numException) {
System.out.println("Sorry you have not enter an integer, Exception is: " +
numException);
}

 
Didn't find what you were looking for? Find more on Simple solution to input? Or get search suggestion and latest updates.




Tagged: