using Or in if/else statement issue [duplicate] - java

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 5 months ago.
Beginner to java. Trying to make it so that my code only takes a certain letter grade input or otherwise exits the system. When I put in this code,
System.out.print("What letter grade do you want to achieve for the course? ");
char desiredGrade = keyboard.next().toUpperCase().charAt(0);
if (desiredGrade != 'A') {
System.out.println("Invalid input");
System.exit(0);
}
it works fine and reads that any other input other than 'A' is an invalid input. However, when I add an OR such as
System.out.print("What letter grade do you want to achieve for the course? ");
char desiredGrade = keyboard.next().toUpperCase().charAt(0);
if (desiredGrade != 'A' || desiredGrade != 'B') {
System.out.println("Invalid input");
System.exit(0);
}
it runs through the if statement even though the user inputs A or B. Is this a simple writing error that I am missing? Thanks!

Use:
desiredGrade != 'A' && desiredGrade != 'B'

Related

Java NumberFormatException when using Integer.parseInt

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
}

Char check using while loop in java (BufferedReader) [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
do
{
// asking user choices
choice = Integer.parseInt(br.readLine());
switch(choice)
{
// doing something
}
System.out.println("Do you want to continue?");
System.out.println("(Y/N)");
ans = (char) br.read();
}
while(ans == 'y' || ans == 'Y');
I am using eclipse;
I want to check whether the user want to re-enter the switch case by entering his answer by a char 'y' || 'Y'.
But whenever i enter the char 'Y' it enters the do loop but also executes the choice variable. And as the choice variable is int; it throws number format exception.
Do you want to continue?
(Y/N)
y
// prints all my switch options
Exception in thread "main":
java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at ArithemeticOperations.main(ArithemeticOperations.java:45)
See that "input string" part of the message? It tells you that the input to the parseInt function is empty. And it's empty because it's the newline after you entered your y. You need to read a whole line for the "continue" answer, and get the character from that full line.
#SomeProgrammerDude already explained the reason behind your problem. So, i am not repeating it. You can modify your code as given below.
String ans;
do{
// asking user choices
choice = Integer.parseInt(br.readLine());
switch(choice){
// doing something
}
System.out.println("Do you want to continue?");
System.out.println("(Y/N)");
ans = br.readline();
}while(ans.toLowerCase().equals("y"));

Making a Y/N Condition work

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())) {
}

why cant i get out of this while loop? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
our project basically involves reading files about the premier league and returning 1. outcomes of games played, 2. fixtures yet to be played and 3. the leaderboard(table). I'm displaying a menu in the command line and also taking in the user input from there. I'm using a while loop to match the userinput with what output to display but I wanted to say if they don't enter 1,2 or 3 that there's an error and to display the menu again and ask them to enter another input. However now if I do enter 1,2 or 3, it doesn't display my results I can't get out of the while loop. Can anyone help me? This is my code!
while(userInput == false)
{
Scanner input = new Scanner(System.in);
String pattern = "[1-3]{1}";
String userChoice;
System.out.println(menuOptions);
userChoice = input.nextLine();
if(userChoice == "1")
{
System.out.print(outcomesResults);
userInput = true;
}
if(userChoice == "2")
{
System.out.print(fixturesResults);
userInput = true;
}
if(userChoice == "3")
{
System.out.print(leaderboardResults);
userInput = true;
}
else if(!userChoice.matches(pattern))
{
System.out.println();
System.out.println("Error: unidentified selection. Please choose 1,2 or 3");
userInput = false;
}
}
If you want to compare the String value, you should use equals():
if (userChoice.equals("1")) {
// do something
}

Input String check [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am writing an ATM program and when the user inputs one of the string values the program should check it an do a method accordingly. The problem code is here:
System.out.println("PRESS");
System.out.println("(D)eposit");
System.out.println("(W)ithdraw");
System.out.println("(C)heck Account Balance");
System.out.println("(Q)uit");
System.out.println("Enter Choice: ");
String choice = scanner.nextLine();
scanner.nextLine();
if(choice == "D"){
currentCustomer.deposit();
}
else if(choice == "W"){
currentCustomer.withdraw();
}
else if(choice == "C"){
currentCustomer.checkBalance();
}
else if(choice == "Q"){
currentCustomer.quit();
}
else{
System.out.println("Invalid choice please reenter: ");
}
If a user enters in "D" the program skips to the else statement. I know when using .nextLine you have to use two because of the return character but I'm not sure if that is true with this case. Either way if I have the extra .nextLine statement or not it still skips ahead. Any help would be much appreciated!
In Java we compare strings with String#equals.
I'll not write the difference between equals and ==, google for more information. You'll get around 100 results.
You would be better off using if(choice.equals("D")) in your code. You can't compare strings with == because you are just checking the memory and not the actual contents.
Instead of using String in comparison part:
else if(choice == "C"){
currentCustomer.checkBalance();
}
you could use char comparison instead
else if(choice[0] == 'C'){
currentCustomer.checkBalance();
}
You shouldn't be using the == operator to compare strings, use the String equals method instead. The operator checks to see if both strings are stored at the same location in memory while the method checks if they have the same content.
If you're using Java 7, you might want to switch out that if-elseif-then block with a switch statement. Java 7 introduced the ability to use strings in switch statements.

Categories