Converting a string input from user to a numeric (int) value.
I've been trying different methods for converting a user string input into an int I could compare and build an "if-then" statement. Every time I tried testing it, it just threw exception. Can anyone look at my Java code and help me find the way? I'm clueless about it (also a noob in programming). If I'm breaking any rules please let me know I'm new here. Thank you.
Anyway, here is the code:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mis开发者_如何学运维typed the answer.");
e.getMessage();
}
It seems like you are trying to convert the string (which should be a single character, Y or N) into its character value, and then retrieve the numerical representation of the character.
If you want to turn Y or N into their decimal representation, you have to perform a cast to int:
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i; //The important part
System.out.println(integerChar);
This will return the integer representation of the character that the user input. It may also be useful to call the String.toUpperCase() method in order to ensure that different inputs of Y/N or y/n do not give different values.
However, you could also do an if-else based upon the character itself, rather than converting it to an integer.
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
//Handle yes
} else if (i == 'N') {
//Handle no
} else {
System.out.println("You've mistyped the answer.");
}
I think you meant to ask them to Enter 0 for yes and 1 for No ? Maybe?
You're asking the user to type Y or N and then you're trying to parse that to an integer. That will always throw an exception.
EDIT -- As others have pointed out, if you want to continue to use Y or N, you should do something along the lines of
String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}
parseInt is just for converting text numbers into integers: everything else gets a NumberFormatException.
If you want the decimal ASCII value of a character, just cast it to an int.
Use if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) {
instead.
Or (as Mark pointed) if (addNewUser.toLowerCase().startsWith("y")) {
.
BTW maybe look at Apache Commons CLI?
You cannot convert String
to int
, unless you know the String
contains a valid integer.
Firstly, using the Scanner class for input is better, since its faster
and you don't need to get into the hassle of using streams, if you're
a beginner. This is how Scanner
will be used to take input:
import java.util.Scanner; // this is where the Scanner class resides
...
Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y')
{ } // do something
else if(choice == 'N')
{ } // do something
else
System.err.println("Wrong choice!");
This code could also be shortened to one line (however you won't be able to check a third "wrong choice" condition):
if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
{ } // do something
else // for 'N'
{ } // do something
Secondly, char
to int
conversion just requires an explicit type
cast:
char ch = 'A';
int i = (int)ch; // explicit type casting, 'i' is now 65 (ascii code of 'A')
Thirdly, even if you take input from a buffered input stream, you
will take input in a String
. So extracting the first character from
the string and checking it, simply requires a call to the charAt()
function with 0 as a parameter. It returns a character, which can
then be compared to a single character in single quotes like this:
String s = in.readLine();
if(s.charAt(0) == 'Y') { } // do something
Fourthly, its a very bad idea to put the whole program in a try
block and catch
Exception
at the end. An IOException
can be
thrown by the readline()
function, and parseInt()
could throw a
NumberFormatException
, so you won't be able to handle the 2
exceptions separately. In this question, the code is small enough for
this to be ignored, but in practice, there will be many functions
that can throw exceptions, hence it becomes easy to lose track of exactly which function threw what exception and proper exception handling becomes quite difficult.
精彩评论