I have truly searched for the answer all over the Internet before coming here and I think that the answer will have something to do with the try/catch statements, but even after watching a couple tutorials on the topic I am not sure on how to implement that.
Anyways, I am trying to do a simple thing in my newbie reminders app that I am making (I am learning Java as my first language for about 3 months now).
I want the program to check the user's input and if it is a certain letter ("R") I want the program to do a certain stuff. If it is an integer from 0 to 100 then I want to do other stuff. And if its neither of them, then I want the "else" statement to work.
The issue that I can't get the "else" statement to work as I get the NumberFormatException error. For example if I enter some other letter i.e. "d" - I get this error message:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "d" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580) at
java.lang.Integer.parseInt(Integer.java:615) at
mash.Dialogue.startDialogue(Dialogue.java:51) at
mash.Dialogue.newRem(Dialogue.java:27) at
mash.Dialogue.startDialogue(Dialogue.java:38) at
mash.Dialogue.start(Dialogue.java:13) at mash.Main.main(Main.java:9)
Here is the code (I am sorry for any readability issues, this is the first time ever I am showing my code to somebody). You don't have to read the else if statement, as the issue seems to not depend on the text inside of that statement.
I would really appreciate if anybody could point me what is wrong with the code and how I would get to do what I intended. Some newcomer-friendly solution will be much appreciated.
Thank you in advance!
String secondLetter = mash.nextLine();
if(secondLetter.equals("r") || secondLetter.equals("R")) { //if the user enters R - create a new Reminder
newRem();
}
else if((Integer.parseInt(secondLetter) >= 0) && (Integer.parseInt(secondLetter) < maximum)) { //if the user enters number - check task list
tasks.remText(Integer.parseInt(secondLetter));
System.out.println("Enter 'D' to set the reminder as Done. Or enter 'T' to return to the list");
String v = mash.nextLine();
System.out.println(v);
if(v.equals("d")|| v.equals("D")) { //if user enters D - set the reminder as done
tasks.setDone(Integer.parseInt(secondLetter));
System.out.println("The reminder is now added to 'Done' list");
}
else if(v.equals("t")|| v.equals("T")) { //if user enters T - return to the list of reminders
tasks.display();
}
else {
System.out.println("Please enter the correct symbol");
}
}
else {
System.out.println("Enter the correct symbol");
}
You can check your input if it's a valid number before attempting to convert it. For example:
if(!secondLetter.matches("[0-9]+")) {
//it's not a number, so dont attempt to parse it to an int
}
place it in your if/else like this:
if(secondLetter.equals("r") || secondLetter.equals("R")) {
newRem();
} else if(!secondLetter.matches("[0-9]+")){
System.out.println("please type r or R or a number");
} else if((Integer.parseInt(secondLetter) >= 0) && ...
Short answer: docs.oracle.
Complete answer:
You can use Integer.parsInt (String s) only on a string that can be parserized into an integer. The letter "R" can not be a number, so it generates an exception.
if(Character.isLetter(secondLetter) && "R".equalsIgnoreCase(secondLetter)){
do code with "R"
}else if(Integer.parseInt(secondLetter) > 0 && Integer.parseInt(secondLetter) < 100){
do code with 0 < number < 100
}else{
do something else
}
Related
I need help with a SIMPLE Y/N Condition for my program. I don't really get it to work as I want to.
Unfortunately all the other topics I find is very confusing. I'm a very novice student in programming.
I want a Y/N Condition that wont crash and is not CASE SENSITIVE. so if Y or y it goes back to another menu, if n and N is just stop the program and if anything else is typed in it will loop until the Y or N conditions are met.
This is what i wrote:
String input = ScanString.nextLine();
while (!"Y".equals(input) || !"y".equals(input) || !"N".equals(input) || !"n".equals(input)) {
System.out.println("Please enter Y/N (Not case sensitive): ");
input = ScanString.nextLine();
}
if ("Y".equals(input) || "y".equals(input)) {
meny1();
} else if ("N".equals(input) || "n".equals(input)) {
}
When it runs, whatever I put in, it won't break the while loop.
while (!"Y".equals(input) || !"y".equals(input) ||... means "keep looping while the input isn't 'Y' or the input isn't 'y' or...". By definition, one of those conditions will always be true.
The simplest way to do what you're looking for would be a case insensitive comparison, and an and (&&) rather than or operator:
while (!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) {
That means "keep looping while the input isn't 'Y' or 'y' and the input isn't 'N' or 'n'.
Or the same in Yoda-speak, since you were using Yoda-speak:
while (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) {
Try this
while (!("Y".equalsIgnoreCase(input)) && !("N".equalsIgnoreCase(input))) {
}
Or
String[] validInputs = { "Y", "N" };
while(!Arrays.asList(validInputs).contains(input.toUpperCase())) {
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to write a program is for checking a real number, so i input "99aa", it says it is a right, but in fact, it should be wrong. i have check many time and i still can't fix the problem. can some one give me some hints?
public class jj {
public static void main( String[] args ) {
String num;
// Create a Scanner object for console input
Scanner input = new Scanner(System.in);
System.out.print("Enter the number: ");
num = new String( input.nextLine() );
for ( int i=0; i<=num.length(); i++ ) {
int j = num.charAt(i);
if (j>57 || j<42 || j==44 || j==47 ) {
System.out.print("This is not a real number.");
break;
} else
System.out.print("This is a real number.");
break;
}
}
}
I commented what's wrong with your logic but don't reinvent the wheel.
Use NumberUtils.isNumber from org.apache.commons.lang.math.NumberUtils :
Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).
if(NumberUtils.isNumber(num))
System.out.println("This is a valid number");
else
System.out.println("This is not a valid number");
Alternatively, if you want to check that you have only digits in your String, you can use
NumberUtils.isDigits:
Checks whether the String contains only digit characters.
boolean valid = NumberUtils.isDigits(num);
Your logic is wrong.
try this instead
if ((j >= 48 && j <= 57) || j==44 || j==47 ) {
}
You want to check whether it is between 48 (0) and 57 (9), boundaries included.
See the ascii table.
Sidenotes:
You're allowing j==47. 47 is /, dot is 46. What one do you want?
Your second break; will leave the iteration after the first cycle.
Try,
char ch = num.charAt(i);
if (!Character.isDigit(ch)) {
System.out.print("This is not a real number.");
break;
}
I'd just like to point out some logic trouble that's giving you some fits:
if (j>57 || j<42 || j==44 || j==47 ) {
System.out.print("This is not a real number.");
break;
} else
System.out.print("This is a real number.");
break;
}
First of all, nevermind the problems with the if check. Jeroen Vannevel's answer covers this.
After any number returns true on the if check, you print the error and break; the loop. This is fine (assuming we fix the if check). You don't need to check every digit if you know the first one is wrong, you can quit checking.
But your else prints a message guaranteeing that the whole number is real despite just checking a single letter.
And then the break; isn't contain in the if or the else (not your brackets and my indentation that makes it more clear). No matter what happens, you'll break; after a single iteration.
What you need should look something more like this:
boolean numberFlag = true;
for ( int i=0; i<=num.length(); i++ ) {
int j = num.charAt(i);
if ((j >= 48 && j <= 57) || j==44 || j==47 ) {
numberFlag = false;
break;
}
}
if(numberFlag) {
// logic when a valid number is checked
} else {
// logic when an invalid number is checked
}
We can't say whether num is a valid number of not until we've checked every single character in the string.
And please be sure to check #ZouZou's answer, as this is what you should really be doing.
You could think about this in terms of Characters and implement the following:
if (Character.isDigit(num.charAt(i))) {
//do something
}
Sorry if the title made no sense but I did not know how to word it.
The problem:
I'm making a multiple choice quiz game that gets either a, b, c or d from the user. This is no problem if they do as they are told, however if they don't type anything and just hit enter I get a StringIndexOutOfBoundsException. I understand why this is happening, but I'm new to Java and can't think of a way to fix it.
What I have so far:
System.out.println("Enter the Answer.");
response = input.nextLine().charAt(0);
if(response == 'a')
{
System.out.println("Correct");
}
else if(response == 'b' || response == 'c' || response == 'd')
{
System.out.println("Wrong");
}
else
{
System.out.println("Invalid");
}
Of course the program will never make it past the second line of code if the user types nothing, because you can't take the charAt(0) value of an empty String. What I'm looking for is something that will check if the response is null, and if so ask go back and ask the question to the user again.
Thanks in advance for any answers.
You can use a do-while loop. Just replace
response = input.nextLine().charAt(0);
with
String line;
do {
line = input.nextLine();
} while (line.length() < 1);
response = line.charAt(0);
This will continue to call input.nextLine() as many times as the user enters a blank line, but as soon as they enter a non-blank line it will continue and set response equal to the first character of that non-blank line. If you want to re-prompt the user for the answer, then you could add the prompt to the inside of the loop. If you want to check that the user entered a letter a–d you could also add that logic to the loop condition.
Either handle the exception(StringIndexOutOfBoundsException) or break this statement
response = input.nextLine().charAt(0);
as
String line = input.nextLine();
if(line.length()>0){
response = line.charAt(0);
}
Exception Handling:
try{
response = input.nextLine().charAt(0);
}catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}
Simple:
Get the input initially as a String, and put it into a temporary String variable.
Then check the String's length.
then if > 0 extract the first char and use it.
In addition #HovercraftFullOfEels' (perfectly valid) answer, I'd like to point out that you can "catch" these exceptions. For example:
try {
response = input.nextLine().charAt(0);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("You didn't enter a valid input!");
// or do anything else to hander invalid input
}
i.e. if a StringIndexOutOfBoundsException is encountered when executing the try-block, the code in the catch-block will be executed. You can read more about catching and handling exceptions here.
StringIndexOutofBoundException will occur in the following situation also.
Searching a string which is not available
Match with the string which is not available
for ex:
List ans=new ArrayList();
temp="and";
String arr[]={"android","jellybean","kitkat","ax"};
for(int index=0;index < arr.length;index++ )
if(temp.length()<=arr[index].length())
if(temp.equlsIgnoreCase((String)arr[``index].subSequence(0,temp.length())));
ans.add(arr[index]);
the following code is required to avoid indexoutofboundexception
if(temp.length()<=arr[index].length())
because here we are cheking the length of src string is equal or greater than temp .
if the src string length is less than it will through "arrayindexoutof boundexception"
There are a bunch of threads throughout the internet on this but I can't make heads or tails of any of them.
As an assignment for an intro to Java course we have been tasked with making a handful of different programs, we were then given them back and told to make them idiot proof.
So for example, we have to use a program to determine what day of the week a random day of any random year will be, (i.e Jan 1 2013 being a Tuesday)
I prompt for three things, Day, Year and Month, I want to make it so that if Day is contains a letter it sends back Invalid and prompts again.
Right now I have it set so that if day is an integer less than one or greater than 31 it asks again, so I don't have a problem with the range, just the NFE.
I have heard that I should use a
Try
{
//...
}
catch{NumberFormatExcept nFE}
but I have no idea how to use that to re-prompt for what I an looking for
Here is a snippet of my code so far
System.out.print("Enter the day of the month (1-31): ");
int d = UserInput.nextInt();
do
{
if(d < 1 || d > 31)
{
System.out.print("That day is invalid, please enter a day between 1 and 31");
d = UserInput.nextInt();
}
}while(d < 1 || d > 31);
I tried making d a string and using Integer.parseInt(); but that would just parse a into 1, I want to so something like if d.hasNextInt(); continue, but if it hasNextString() reprompt.
AKA
String d;
d = UserInput.nextLine();
int dVar = Integer.parseInt(d);
I can't just throw an exception because the objective is to not crash but just prompt again.
Consider creating a method for reading in a valid integer. Pass this method the valid integer range. The method would attempt to read the value once and validate. If the method fails, return null, if it passes return the Integer. Call this method in a do-while loop until you get a non-null Integer.
First off, you really shouldn't use exceptions for input validations. Exceptions are for exceptional conditions; things you don't expect to happen. Josh Bloch outlines this specifically in his excellent book Effective Java
As for your code, I would suggest using the hasNextInt() method combined with getting the input as an int and checking for the range you require as you've actually stated in your question.
int d = 0;
while (d < 1 || d > 31)
{
System.out.print("Enter the day of the month (1-31): ");
if (userInput.hasNextInt())
{
int d = userInput.nextInt();
}
else
{
String s = userInput.next();
}
if(d < 1 || d > 31)
{
System.out.print("That day is invalid - ");
}
}
It looks like you are using Scanner to get input. (By the way, in Java, it is conventional for variables to start with lower-case letters).
If that's the case, if you attempt to scan an int when there isn't one in the input, an InputMismatchException will be thrown. You avoid this by testing whether this will happen before you try to read the int.
So, think about a loop structure like this:
int d = 0;
while (true) {
if (/* The input isn't an integer */) {
/* Tell the user. */
continue;
}
d = input.nextInt();
if (/* The input is out of range */) {
/* Tell the user. */
continue;
}
...
/* When you've completed all of your tests and everything is okay, break. */
break;
}
By the way, many months don't have 31 days.
Are you familiar with the behavior of a try-catch statement?
try
{
//do something that may throw an exception you can handle
}
catch(Exception ex)
{
//If we enter this block, an exception was thrown from the try block's code
//If you cannot fully handle the exception, you can rethrow it
throw ex;
}
finally
{
//This code ALWAYS executes, unless the program is aborted from outside its scope
}
You can use this inside some other loop, allowing you to define behavior based on whether an exception was thrown. This code is in C#; it is syntactically very close to Java but I'm a little light on Java's libraries so substitute proper class names/method calls as necessary:
int day = 0;
while(true) //we will manually break out of the loop once the user enters a valid value
{
try
{
//Ask user for input
string input = Console.ReadLine();
day = Int32.Parse(input); //this will throw an exception if input is not numeric
//You can throw your own exception within a try block too
if (day < 1 || day > 31) throw new Exception("Date not within proper bounds");
break; //if the parse worked and the value passed the validation, end the loop.
}
catch(Exception ex) //You can catch something more specific
{
//The parse failed; tell the user that they screwed up, and how
Console.WriteLine("Invalid entry: " + ex.Message);
//skip the rest of the loop's code and start a new iteration of the loop
continue;
}
}
The behavior of this construct is that while the user keeps entering values that cannot be turned into a number between 1 and 31, exceptions will be thrown, caught, and used to perpetuate the loop. As soon as the user enters something you can work with, execution flow will move past this loop to whatever is next.
This is driving me insane! Here's the code:
public static void main(String[] strings) {
int input;
String source;
TextIO.putln("Please enter the shift value (between -25..-1 and 1..25)");
input=TextIO.getInt();
while ((input < 1 || input > 25) && (input <-25 || input >-1) && (input != 999 && input !=-999))
{
TextIO.putln(input + " is not a valid shift value.");
TextIO.putln("Please enter the shift value (between -25..-1 and 1..25)");
input=TextIO.getInt();
}
TextIO.putln("Please enter the source text (empty line to quit)");
//TextIO.putln(source);
source = TextIO.getln();
TextIO.putln("Source :" + source);?");
}
}
However, its telling me that 'source' is never read! It's not allowing me to get input! Can anyone see what the problem may be?
The compiler is correct; the variable source is never read. You're assigning a value to it (source = TextIO.getln();), but you're never reading that value back out.
To do so, you could do something like:
TextIO.putln(source);
You seem to be having trouble reading text from the console with the TextIO class. Here's a more standard approach, introduced in Java 5:
String source;
Scanner in = new Scanner(System.in);
source = in.nextLine();
What exactly do you wish to do with the variable source? As it stands, you're asking the user to enter a string, but you're not doing anything with that string.
You should probably ask one of your friends for help instead of posting our homework online. I feel as though this is subjective to cheating. If you are having trouble already, it is only going to get worse. You should be breezing through your freshman year.