I'm very new to programming in general, and I'm having a bit of trouble with a program I'm writing in Java to help calculate my final grade in a class. This part of the program asks me what letter grade I would like to receive, and then determines if that input is valid. For example, if I typed into the keyboard that I wanted to receive a letter grade of "Z", because that is not a valid grade, I would like my program to output "Invalid Input" and exit. The code I have written below is not producing any syntax errors, but it outputs "Invalid Input" for every letter grade I choose, even A, B, and C (inputs that should be valid). Any help in understanding what's wrong is more than welcome.
Scanner input = new Scanner(System.in);
char desiredGrade
System.out.print("What letter grade do you want to achieve for the course? ");
desiredGrade = input.next().charAt(0);
if (desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'){
System.out.println("Invalid Input");
System.exit(0);
}
In addition to this, it would be helpful to not have to worry about case sensitivity with the inputs. I know I can use .ignoreCase() or .equalsIgnoreCase() with strings, but I'm not quite sure how to implement that with char.
see this Answer
For Upper- and Lowercase you can wrap your char in Character and then call toLowerCase and check the input and the expected value on Lowercase.
In your example
desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'
If you want to use the || operator you have to do it like that
if(!(desiredGrade == 'A' || desiredGrade == 'B' || desiredGrade == 'C')){
}
That way you check if the Input is A, B, or C and if not then exit
Lets say desiredGrade = 'A'
if (desiredGrade != 'A' || desiredGrade != 'B' || desiredGrade != 'C'){
The first condition will be false, but the second and third will be true. So
if (false || true || true)
Will result always in true.
The way to do it is using operator AND &&
if (desiredGrade != 'A' && desiredGrade != 'B' && desiredGrade != 'C'){
This way, if the user decides to input 'A' the operation will be
if (false && true && true){
Resulting in false. And if the user inputs 'Z', the operation will be
if (true && true && true){
That will result true and execute the Invalid input output.
EDIT
As it has been mentioned. The user may input 'a' (lowercase) for which condition desiredGrade = 'A' will be false since 'a' != 'A' (is not equal).
So it will be wise to convert desiredGrade to uppercase before the if statement.
Try out
(desiredGrade != 'A' && desiredGrade != 'B' && desiredGrade != 'C')
Basically, you want to check if desiredGrade is different than A and different than B and different than C, print out invalid input.
Try this:
if (! Arrays.asList ('A', 'B', 'C').contains (Character.toUpperCase (desiredGrade))) {
// your error handling
}
Related
I should ask "choose" and the user should type a b or c if he types somehting else, it should repeat the question. I don't even understand how I do that and then I have another problem: Later I should print out the chosen sort of coffee but because the "eingabe" is in a while or if body it can't be recognized when I want to use it later. How do I solve this problem? Or should I use another loop anyway? And is character even the right type to use here?
Thx in advance.
while(eingabe != 'a' || eingabe != 'b' || eingabe ||'c') {
Out.println("Bitte auswaehlen: ");
char eingabe = in.readChar();
}
Out.print("Gewaehlt ");
if (eingabe == 'a') Out.print("CAPPUCCINO");
if (eingabe == 'b') Out.print("MOKKA");
if (eingabe == 'c') Out.print("VERLAENGERTER");
Out.print(" !");
}
As mentioned before you should declare it outside the loop. And you mistyped in the loop when check c:
char eingabe = '';
while(eingabe != 'a' && eingabe != 'b' && eingabe != 'c') {
Out.println("Bitte auswaehlen: ");
eingabe = in.readChar();
}
Out.print("Gewaehlt ");
if (eingabe == 'a') Out.print("CAPPUCCINO");
if (eingabe == 'b') Out.print("MOKKA");
if (eingabe == 'c') Out.print("VERLAENGERTER");
Out.print(" !");
Your eingabe variable should be defined outside of the loop, so the rest of your code can access it. Just be careful not to initialise it with a value checked for in the condition, or even better use a do-while instead.
I switched your code to use regular System.in and System.out, as I do not know what those in and Out are. Last but not least, your output condition was wrong, you should ask again if the value is is different from all expected values, not if differend from any (which is always true):
char eingabe;
do {
System.out.println("Bitte auswaehlen: ");
eingabe = (char) System.in.read();
} while (eingabe != 'a' && eingabe != 'b' && eingabe != 'c');
System.out.print("Gewaehlt ");
if (eingabe == 'a')
System.out.print("CAPPUCCINO");
if (eingabe == 'b')
System.out.print("MOKKA");
if (eingabe == 'c')
System.out.print("VERLAENGERTER");
System.out.print(" !");
I think there is a problem in your expression eingabe != 'a' || eingabe != 'b' || eingabe ||'c'. Maybe you meant eingabe != 'a' || eingabe != 'b' || eingabe != 'c'. I think in order to continue loop when user types something else, you need to use && instead of ||. A do while loop is ideal for your use case:
char eingabe;
Scanner in = new Scanner(System.in);
do {
System.out.println("Bitte auswaehlen: ");
eingabe = in.next().toCharArray()[0];
} while (eingabe != 'a' && eingabe != 'b' && eingabe != 'c');
Write a program that asks the user to type a vowel from the keyboard. If the character entered is a vowel, display “OK”; if it is not a vowel, display an error message. Be sure to allow both uppercase and lowercase vowels. The program continues until the user types ‘!’.
I have written the program but I need it to loop. I wrote a code where it only accepts one input and I don't know what I am supposed to use for the input for char.
Scanner input = new Scanner(System.in);
System.out.println("Enter an alphabet between a to z; Enter ! to stop");
int myChar;
myChar = input.nextInt();
while (myChar <= 'z') {
if (myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u' ) {
System.out.println(myChar + " OK");
} else {
System.out.println(myChar + " is not vowel");
}
}
You're almost there :)
A small error that you've made is that you've limited your scanner to only reading integers.
You've also declared myChar to an int. Since it is a character, you can declare it like:
char myChar = input.next().charAt(0);
A scanner has many functions, and some are specific to certain variable types
.nextInt() will only read integers.
nextDouble().will read doubles
.nextLine() will read till the end of the current line
Thus, as I mentioned above, you can simply use .next().charAt(0)
First, you need to put the declaration before you give it a value, so it should be
int myChar;
myChar = input.nextInt();
Second, you are reading a char, so it should not be int myChar...
char myChar;
myChar = input.next().charAt(0);// Since there no nextChar() in scanner
Third, your while loops is NEVER going to stop, since the value of myChar is not changed in the while loop,
Fourth, you did not allow both uppercase and lowercase vowels, you only allowed lowercase vowels
Fifth, add the statement "! to stop", I mean, I'm sure you don't want "! is not a vowel" to be printed, right?
So this is what it should look like:
Scanner input= new Scanner(System.in);
System.out.println("enter alphabet between a & z, ! to stop");
char myChar;
myChar = input.next().charAt(0);
while(('a' <= myChar && myChar <= 'z') || ('A' <= myChar && myChar <= 'Z')) {
if(myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u' || myChar == 'A' || myChar == 'E' || myChar == 'I' || myChar == 'O' || myChar == 'U'){
System.out.println(myChar + " OK");
}else if(myChar == '!'){
break;
}else{
System.out.println(myChar + " is not vowel");
}
System.out.println("Enter again:");
myChar = input.next().charAt(0);
}
You code is almost correct but you are missing few very important parts.
Declaration int myChar; should be written before initialization myChar = input.nextInt();
You are willing to read a char so you should declare myChar variable with data type char and not int.
Your while-loop condition does not satisfy the need. Because you are just using one end of the range of alphabet but missing the other end and hence it will not generate desired boolean result.
Approach to reach solution for your problem:
Read a string from user using scanner.next() method.
Convert the string to lower case to handle upper and lower case vowels.
Take the first character from the read string input by using the method string.charAt(0) to convert String into char and save it to myChar.
Start a while-loop that will keep iterating until myChar == '!'.
Inside the loop, first check if myChar is a vowel. If true, print "OK".
If myChar is not a vowel, check if myChar fall in range of an alphabet or not. If true, print "Not a vowel".
If myChar does not fall in the range of English alphabets then print "You entered an incorrect alphabet" and prompt for new value.
Finally, if myChar is !, then the condition for while-loop becomes false and the program stops.
Here is the full code:
Scanner input = new Scanner(System.in);
System.out.println("Enter an alphabet between 'a' to 'z'; Enter '!' to terminate");
/*
* input.next() reads a string from Scanner's input stream until it finds a space or endOfLine.
* string.toLowerCase() converts any English alphabet in a string to lower case and return the new string. For example, "Hello World 21F" becomes "hello world 21f".
* string.charAt(0) returns the character of a string at index 0; 1st position.
*/
char myChar = input.next().toLowerCase().charAt(0);
while (myChar != '!') {
if (myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u') {
System.out.println(myChar + " OK");
} else if (myChar >= 'a' && myChar <= 'z') {
System.out.println(myChar + " is not vowel");
} else {
System.err.printf("You entered an incorrect alphabet '%c'. ", myChar);
}
System.out.println("Enter an alphabet between 'a' to 'z'; Enter '!' to terminate");
myChar = input.next().toLowerCase().charAt(0);
}
I use this code to restrict the input only for numbers, but if the first key I press is a letter, the code let me enter that letter, only one time, then when I erase it I cannot input anymore letters, what is wrong with the code? I want to imput only numbers.
amount.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!(Character.isDigit(c)
|| (c == KeyEvent.VK_BACK_SPACE)
|| (c == KeyEvent.VK_DELETE))
|| (amount.getText().length() >= 2)) {
e.consume();
}
}
});
Because of De Morgan's laws:
"not (A or B)" is the same as "(not A) and (not B)".
Your condition is equivalent to:
if ((Character.isDigit(c)
&& c == KeyEvent.VK_BACK_SPACE
&& c == KeyEvent.VK_DELETE))
|| cantBannosTxt.getText().length() >= 2)
When you enter a two letters, the first part of the OR fails but the second one evaluates to true. Since false || true is true, it will consume what you entered.
I'll leave it for you to construct a new validation - Pay attention to the logical && and || when combined with !.
I'm doing this little program, but unfortunately I ran into this issue..
if (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3') {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
}
My program does not recognize if I put in any of the integers in my String.
However, if I delete my || and the last part, the if statement recognizes the first integer.
What am I missing here?
if (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3')
Is always true.
Every character is != '4' or != '3'
I guess you want && instead.
Details:
The statement A || B is true if A is true or B is true (or both are true).
In your example, lets say that the first character is '4'.
A = ccnString.charAt(0) != '4' is false (4 != 4 is false)
B = ccnString.charAt(0) != '3' is true (3 != 4 is true)
So A || B is true because B is true.
This is an addition to the many other answers that correctly state that you must use and (&&) instead of or (||).
You have been fooled by De Morgan's laws. They define how boolean expressions are negated.
In your example, the original expression that defines a valid user input is as follows:
validInput = userPressed3 or userPressed4
But as we are interested in invalid user input, this expression has to be negated:
not(validInput) = not(userPressed3 or userPressed4)
According to De Morgan, not(A or B) is equal to not(A) and not(B). So we can also write:
not(validInput) = not(userPressed3) and not(userPressed4)
In other words: It's De Morgan's fault! ;)
You probably want
if (ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3') {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
}
This would give your error message only for Strings that don't start with 4 AND don't start with 3.
Your original condition gives an error for any String that either doesn't start with 4 OR doesn't start with 3, and since all Strings satisfy that condition, you'll always get your error message.
If you require additional conditions after the initial test, you can do :
if (ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3') {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
} else if (ccnString.charAt(0) == '3' && ccnString.charAt(1) == '7') {
// here you know that ccnString starts with 37
} else if (...) {
...
}
... add as many else ifs as you need ...
else {
// default behavior if all previous conditions are false
}
It should be && not ||
ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3'
Else (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3' always true
if ((ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3')
|| (ccnString.charAt(0) == '3' && ccnString.charAt(1) == '7')) {
System.out.println("The String entered does not fit any of the Credit card standards");
System.exit(0);
}
I want to exit the while loop when the user enters 'N' or 'n'. But it does not work. It works well with one condition but not two.
import java.util.Scanner;
class Realtor {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
char myChar = 'i';
while(myChar != 'n' || myChar != 'N'){
System.out.println("Do you want see houses today?");
String input = sc.next();
myChar = input.charAt(0);
System.out.println("You entered "+myChar);
}
}
}
You need to change || to && so that both conditions must be true to enter the loop.
while(myChar != 'n' && myChar != 'N')
Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.
Use myChar != 'n' && myChar != 'N' instead
If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.