Boolean line error - java

So basically, I had to write a little java programm that assigns student scores.
It works fine, I can enter H (Higher) grades fine, but when I choose S(standart) it throws me back to the editor and I just don't udnerstand whats wrong.
boolean isHigher = getInput().charAt(0) == 'H' || getInput().charAt(0) == 'h';

The only reason I can think of is that your getInput() removes the input, and doesn't actually ask it again.
In that case the following scenario occurs: the input isn't equal to "H" so you go to the or, you have no input left so you return an empty String of which you ask the char at position 0 => StringIndexOutOfBoundException.
You should use:
Character enteredCharacter = getInput().charAt(0);
boolean isHigher = enteredCharacter == 'H' || enteredCharacter == 'h';

Related

Java loop confusion requiring assistance

So i need help, i am trying to input a Y/N program but it is not accepting a big 'Y' or 'N'. Also another thing that i am trying to do is after pressing 'Y'/'y' i am trying to get the program to loop back to the code written above. Example a program that displays '123' and do i need to continue? Y/N, if entered yes it goes back up to restart the program from scratch. Please help me.
System.out.println("continue? Yes or no ");
char check = s.next().charAt(0);
while (check != 'y' && response != 'n')// corrected this part, however need help with restarting the loop back to the first line of code in a loop {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
} if ((check == 'n') || (check == 'N')) {
// I tried (check == 'n' || check == 'N')
System.out.println("Program terminated goodbye.");
System.exit(0);
} else if (check == 'y') {
//need help with restarting the loop back to the first line of code in a loop
}
I think this is what you are looking for.
char check;
Scanner scanner = new Scanner(System.in);
do
{
//your piece of code in here e.g.
System.out.println("Printed 123");
System.out.println("Do you wish to continue?[Y/y] or [N/n]");
choice = scanner.next().charAt(0);
}while (check =='Y' || check == 'y');
System.out.println("Program terminated goodbye.");
A do-while loop runs at least once before the condition is checked and so when a user enters either Y or y, then the condition will be true, meaning that they wish for the loop to run again. If the user enters any other value, then the condition will become false since choice is neither Y nor y and the loop will terminate.
Use String.equals() to compare the value of strings, == compares the strings in memory.
If you want to check without case-sensitive, you should convert the char to a String, then do s1.equalsIgnoreCase(s2);
So
while(true) {
System.out.println("Continue? [Y/N]");
char check_char = s.next().charAt(0);
String check = Character.toString(check_char);
while(check.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
}
if (check.equalsIgnoreCase("n")) {
System.out.println("Program terminated goodbye.");
System.exit(0);
}
}
For returning to the first line, I used a while loop that loops forever.
To the end if it is n then exits, otherwise it returns back to the first line of the loop.

Handling exceptions in Java: How to reject int?

I'm having a problem handling exceptions. Honestly, I really don't understand how it works since I self study.
I'm working with a program where there would be a main menu with the following choices.
Odd/Even - asks an integer input from user and identify if it is an odd or even. Program would continuously ask for an integer input if the user keeps on giving character inputs. (I was able to do this but I keep on getting errors when I use br.readLine() in getting input. Pls see codes below. So I used the normal parsing. Since I didn't use Buffered Reader, I try to delete it but the Odd/Even program wouldn't handle the exception without it.)
Vowel/Consonant - asks the user for a character input and identify if it is a vowel or a consonant. Program should reject integer inputs. The program I made with the codes below doesn't reject integer inputs. I tried searching for answers but I can't find one.
Please ignore for now.
My problem/s involve/s the following questions.
1. Why doesn't the program Odd/Even handle the NumberFormat exception whenever I try to delete the BufferedReader line even though it wasn't used in the whole program?
How can I reject integer inputs for the Vowel/Consonant program?
Here is a video when I tried to run the program.
http://tinypic.com/r/24ou9kz/9
When I exit the program, the console shows this.
Exception in thread "main" java.lang.NumberFormatException: null at
java.lang.Integer.parseInt(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source)
import javax.swing.JOptionPane;
import java.io.*;
import java.util.InputMismatchException;
public class DoWhileIf {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
int choice, num = 0;
char again = 0;
boolean err = true;
do {
input = JOptionPane.showInputDialog("Menu\n[1] Odd/Even\n[2] Vowel/Consonant\n[3] CQM\n[4] Fuel Efficiency\n[5] Scholarship\n[6] Exit program.\n\nEnter Choice.");
choice = Integer.parseInt(input);
if (choice == 1) {
do {
do {
try {
input = JOptionPane.showInputDialog("Input an integer : ");
num = Integer.parseInt(input);
err = false;
} catch (NumberFormatException o) {
JOptionPane.showMessageDialog(null,"Error!");
err = true;
}
} while (err);
if (num % 2 == 0) {
JOptionPane.showMessageDialog(null,"Even.");
}
else {
JOptionPane.showMessageDialog(null,"Odd.");
}
do {
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
again = input.charAt(0);
} while (again != 'Y' && again != 'y' && again !='N' && again !='n');
} while (again == 'Y' || again == 'y');
}
if (choice == 2) {
char letter = 0;
do {
do {
try {
input = JOptionPane.showInputDialog("Character : ");
letter = input.charAt(0);
err = false;
} catch (InputMismatchException a) {
JOptionPane.showMessageDialog(null,"Error!");
err = true;
}
} while (err);
if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U') {
JOptionPane.showMessageDialog(null,"Vowel");
}
else {
JOptionPane.showMessageDialog(null,"Consonant");
}
do {
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
again = input.charAt(0);
} while (again != 'Y' && again != 'y' && again !='N' && again !='n');
} while (again == 'Y' || again == 'y');
}
} while (choice <= 0 || choice > 6 || again == 'N' || again == 'n');
}
Why doesn't the program Odd/Even handle the NumberFormat exception whenever I try to delete the BufferedReader line even though it wasn't
used in the whole program?
I am not able to duplicate this problem. I removed the BufferedReader and option #1 works the same as it did before. I entered integer values, special characters, letters, spaces and it works fine.
How can I reject integer inputs for the Vowel/Consonant program?
You could modify your else condition from this:
else {
JOptionPane.showMessageDialog(null,"Consonant");
}
to this:
else if(Character.isLetter(letter)){
JOptionPane.showMessageDialog(null,"Consonant");
}
else{
JOptionPane.showMessageDialog(null,"Error! You must enter a valid letter.");
}
When I exit the program, the console shows this.
Exception in thread "main" java.lang.NumberFormatException: null at ...
Regarding the NumberFormatException you're seeing, I'm guessing you're pressing the Cancel button on the dialog. When you press cancel the variable input receives the value null. When you try to parse null as an integer it fails and throws the exception:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at exception.DoWhileIf.main(DoWhileIf.java:18)
Line 18 is this line: choice = Integer.parseInt(input);
Notice how the exception told us - java.lang.NumberFormatException: null which tells us that the parameter being passed to the parseInt method is null.
Lastly some additional thoughts for you to consider:
Whenever you get input from the user you must account for all the possibilities somehow. For example when you have code like this:
letter = input.charAt(0);
you're not accounting for the possibility that the input could be null or empty in which case this logic will throw an exception.
A concrete example is when the user clicks Cancel on the dialog that asks whether they want to try again:
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
When the user clicks Cancel on this dialog the same thing happens that I described above regarding the NumberFormatException - input becomes null. If you try to use input like this:
again = input.charAt(0);
it will fail with the exception:
Exception in thread "main" java.lang.NullPointerException
because you can't invoke a method on a null.
Another example is when the user enters nothing at the main menu but simply presses OK. The result is this exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
This happens because input was set to an empty string and parseInt does not know how to convert empty string into an integer value.
Another item I want to bring up is that you're using this same piece of code over and over again. Whenever you have code you want to reuse you should not copy and paste it but instead create a method, object, or other construct so that you can refer to it.
do {
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
again = input.charAt(0);
} while (again != 'Y' && again != 'y' && again !='N' && again !='n');
Breaking up your logic into smaller more manageable pieces will help you to debug, test, and maintain your code more easily.
Another point I want to touch on regarding this same block of logic is that you're using the same kind of dialog to ask for many different kinds of input. Since you're using a GUI dialog, you could use a dialog that is better suited to your task such as one that asks the user to press either a Yes button or No button.
You can learn more about different kinds of dialogs by reading the How to Make Dialogs Tutorial
Here is an example of how you could create a more friendly dialog:
/**
* Asks the user if they want to try something again and
* returns a boolean representing the user's response.
* #return true if the user answers Yes, false otherwise.
*/
private static boolean promptToRepeatSelectedOption(){
int n = JOptionPane.showOptionDialog(null,
"Try again?",
"Repeat Selection",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
null,
null);
return n == JOptionPane.YES_OPTION;
}
The above method, when invoked, will create and display a dialog with two buttons - Yes and No - and the user will have to select one of them or close the dialog. The logic simply looks for if the user said Yes (by clicking the Yes button) and returns true when that is the case. If the user closes the dialog or chooses the No option the method returns false simply because either of those two scenarios will cause the n == JOptionPane.YES_OPTION comparison to result in a value of false.
You can replace your entire loop with a call to this method like this:
First, define a variable to hold the user's response.
boolean repeat = false;
Then invoke the method and set the variable to its result:
repeat = promptToRepeatSelectedOption();
Now replace the outer loop condition
while (again == 'Y' || again == 'y');
with this: while (repeat);
and finally replace part of the outermost loop condition
again == 'N' || again == 'n'
with this: !repeat
One final thought is that you're using very general error messages when the user enters something incorrect or invalid:
JOptionPane.showMessageDialog(null, "Error!");
It's always better to explain to the user a little bit about what they did wrong so that they know how to avoid the error next time. You should probably consider adding more detail to your error messages.
Hope this helps!

how to end a method in java through another method?

Here's my code:
public boolean isConsonant(char x){
if (!Character.isLetter(x)){
System.out.print ("What you have entered cannot be a consonant or vowel.");
return false;
}
return (x != 'a' && x != 'e' && x != 'i' && x != 'o' && x != 'u');
}
The problem I'm having is the first if statement. I call the isConsonant method multiple times in the code after this and depending on the return calue (true or false) the code does some action.
The problem is that I don't want the method to continue at all if the char isn't a letter. I want the program to end. What I tried to do is write another method that looked like this:
public voidisNotLetter(char x)
if (!Character.isLetter(x){
System.out.println("What you have entered cannot be a consonant or vowel.");
}
This is where I'm stuck. I don't know what I can put in that method that will stop the program from running and just print that statement to the user. I thought about throwing an IllegalArgumentException, but that's not technically true since the argument is valid but just isn't what I want.
If you want to "stop the program from running and just print that statement to the user", this might help :
if (!Character.isLetter(x)){
System.out.print ("What you have entered cannot be a consonant or vowel.");
System.exit(0); //This would terminate the execution if the condition is met
}
More details here. Hope it helps.
You can try nesting if statements.
if(isLetter(input)){
if(isConsonant(input)
//input is consonant
else
//input is not consonant
}else{
//input is not letter
}

How do you check to see if the 1st letter in a string is equal to something?

In my if statement, I'm trying to check if the first letter of a string is either Y or y, and then proceed as such. Below is what I have, but I don't believe it to be correct.
System.out.print("Do you wish to do another calculation (Yes/No): ")
option = scan.next();
if (option.substring(0,1) == "N" && option.substring(0,1) == "n" )
{
System.out.println("Have a good day");
System.exit(0);
}
bmi.setOption(option);
I instantiated option as String option = " "; earlier on in my program. I know how to check if strings equal a certain character, however am having trouble checking to see if only the FIRST character of the string is equal to something.
Thank you!
if (Character.toLowerCase(option.charAt(0)) == 'n')
The first char can't be both "N" and "n", looks like you want it to be "N" or "n"
if (option.substring(0,1).equals("N") || option.substring(0,1).equals("n") )
We had == before which is more like a memory comparison we want to compare value so we use equals

NumberFormatException thrown by Integer.parseInt

Hey Im taking coding lessons at school but the teacher does not explain that well so we have to look for info online which I did, but I was not able to find the error in my code, can you help me please?
char end='s';
do{
System.out.println("Tipo de boleto");
char boleto = (char) System.in.read();
switch (boleto){
case 'a':
System.out.println("El boleto cuesta $120.00");
System.out.println("Otro boleto (s/n)?");
end = (char) Integer.parseInt(entrada.readLine());
continue;
case 'n':
System.out.println("El boleto cuesta $75.00");
System.out.println("Otro boleto (s/n)?");
end = (char) Integer.parseInt(entrada.readLine());
continue;
case 'i':
System.out.println("El boleto cuesta $60.00");
System.out.println("Otro boleto (s/n)?");
end = (char) Integer.parseInt(entrada.readLine());;
continue;
default:
System.out.println("Error" );
break;
}
}
while (end == 'n');
Exception
run: Tipo de boleto a El boleto cuesta $120.00 Otro boleto (s/n)?
Exception in thread "main" java.lang.NumberFormatException: For input string: "" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:592) at
java.lang.Integer.parseInt(Integer.java:615) at
asjidbhahsjksbd.Asjidbhahsjksbd.main(Asjidbhahsjksbd.java:16) Java Result: 1
BUILD SUCCESSFUL (total time: 7 seconds)
See, you are trying to parse "" as an Integer whichwill throw NumberFormatException. You have to check for null and isEmpty() in this order and then try to parse the string as an integer.
You are getting exception in this line , i think you are getting "" blank String from readLine() method
end = (char) Integer.parseInt(entrada.readLine());
So Do like this
String input=entrada.readLine();
if(input!=null && !input.equals(""))
{
end = (char) Integer.parseInt(input);
}
I suggest you to use google guava libraries which is having a utility function
Strings.isNullOrEmpty(inputString)//Checks String for both null and empty
Update
As #ajb suggested :
If you want to convert s and n into character than don't use your code snippet
instead of Parsing an Integer
Use
char c=input.charAt(0);
you should replace continue statement with a break. putting continue will skip the current iteration and the while condition will not be evaluated.
This does not do what you think it will:
end = (char) Integer.parseInt(entrada.readLine());
This line reads a string. It then assumes the string is a number, and determines the number. If the user actually enters "s" or "n", it throws an exception, because "s" and "n" are not numbers. The number is then treated as the ASCII value of a character. The result is that the loop will test whether the user types in the string "110", since 110 is the ASCII value of the character n.
There are several ways to fix this; here's one:
end = entrada.readLine().charAt(0);
This returns the first character of whatever line the user types in. This is a sloppy solution because it doesn't work if the user hits ENTER on an empty line (it will throw an exception). Better:
String answer = entrada.readLine();
if (answer.isEmpty()) {
end = 'n'; // treat an empty string like 'n'
} else {
end = answer.charAt(0);
}
Also, I think the while might be wrong. while (end == 'n') means the program will loop back if the user enters n, which I think is the opposite of what you want.
P.S. There are other errors that I didn't catch, that others have pointed out; using continue is wrong--use break to leave the switch statement. And reading one character with System.in.read() is a problem, because the user will type in a character, but the character won't get into the program until the user types ENTER, and then readLine() will get the rest of this first line, instead of asking for another line. But I usually don't use System.in.read() so I'm not completely sure what this does without trying it.

Categories

Resources