This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I getting the wrong result every time I run this program and I feel like an extra pair of eyes would be helpful at 4 in the morning. Can someone please help find where my curly braces or parentheses are off because I cannot find it for the life of me.
System.out.println("Please enter your guess") ;
userGuess = kbd.next() ;
if( userGuess != "a" || userGuess != "b" || userGuess != "c" ||
userGuess != "d" || userGuess != "e" || userGuess != "f" || userGuess != "g" ||
userGuess != "h" || userGuess != "i" || userGuess != "j" || userGuess != "k" ||
userGuess != "l" || userGuess != "m" || userGuess != "n" || userGuess != "o" ||
userGuess != "p" || userGuess != "q" || userGuess != "r" || userGuess != "s" ||
userGuess != "t" || userGuess != "u" || userGuess != "v" || userGuess != "w" ||
userGuess != "x" || userGuess != "y" || userGuess != "z" || userGuess!= "A" ||
userGuess != "B" || userGuess != "C" || userGuess != "D" || userGuess != "E" ||
userGuess != "F" || userGuess != "G" ||userGuess != "H" || userGuess != "I" ||
userGuess != "J" || userGuess != "K" ||userGuess != "L" || userGuess != "M" ||
userGuess != "N" || userGuess != "O" || userGuess != "P" || userGuess != "Q" ||
userGuess != "R" || userGuess != "S" || userGuess != "T" || userGuess != "U" ||
userGuess != "V" || userGuess != "W" || userGuess != "X" || userGuess != "Y" ||
userGuess != "Z" ) {
System.out.println("Invalid character, please enter your guess") ;
}userGuess = kbd.next() ;
Strings should be compared with the .equals() method and not ==.
That being said, in your case you might want to take a look at regular expressions, which would allow you to do a clean validation of the input. So in short:
//This code is untested, but it should guide you to what you need to do
Pattern userInput = Pattern.compile("^[A-Za-z]$"); //A-Z will match all the characters ranging from A to Z. a-z will do the same but it will check the lower case range. Alternatively, you could use ^[a-z]/i$ to make your regular expression case insensitive.
Scanner kbd = new Scanner(System.in);
String input = kbd.next();
Matcher matcher = userInput.matcher(input);
if(!matcher.matches())
{
System.out.println("Invalid character, please enter your guess") ;
}
You need to change == to equals to compare values of String (and any other object).
Also you have problem with logic, because userGuess != "a" || userGuess != "b" is true for all characters since if something is a then it is not b so one of these conditions will be always true.
You may want to change || to && or use proper tools like regex, or methods from Character class like Character.isLetter.
Related
I am writing a code that represents an old-fashioned phone keypad. Everything is working fine except for when I try to take a blank space from the user which is supposed to print out the number 0. I've tried Unicode as well with '\u0020' but that didn't work either. In the output If I type a space and hit enter, I get another line so the scanner is not recognizing the blank space as a char that would be my guess. Someone, please help thanks!
import java.util.Scanner;
public class phoneKeypad{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a letter: ");
char userInput = input.next().charAt(0);
if (userInput == 'a' || userInput == 'b' || userInput == 'c' ||
userInput == 'A' || userInput == 'B' || userInput == 'C')
{
System.out.println(userInput + " is the number 2!");
}
else if (userInput == 'd' || userInput == 'e' || userInput == 'f' ||
userInput == 'D' || userInput == 'E' || userInput == 'F')
{
System.out.println(userInput + " is the number 3!");
}
else if (userInput == 'g' || userInput == 'h' || userInput == 'i' ||
userInput == 'G' || userInput == 'H' || userInput == 'I')
{
System.out.println(userInput + " is the number 4!");
}
else if (userInput == 'j' || userInput == 'k' || userInput == 'l' ||
userInput == 'J' || userInput == 'K' || userInput == 'L')
{
System.out.println(userInput + " is the number 5!");
}
else if (userInput == 'm' || userInput == 'n' || userInput == 'o' ||
userInput == 'M' || userInput == 'N' || userInput == 'O')
{
System.out.println(userInput + " is the number 6!");
}
else if (userInput == 'p' || userInput == 'q' || userInput == 'r' || userInput == 's' ||
userInput == 'P' || userInput == 'Q' || userInput == 'R' || userInput == 'S')
{
System.out.println(userInput + " is the number 7!");
}
else if (userInput == 't' || userInput == 'u' || userInput == 'v' ||
userInput == 'T' || userInput == 'U' || userInput == 'V')
{
System.out.println(userInput + " is the number 8!");
}
else if (userInput == 'w' || userInput == 'x' || userInput == 'y' || userInput == 'z' ||
userInput == 'W' || userInput == 'X' || userInput == 'Y' || userInput == 'Z')
{
System.out.println(userInput + " is the number 9!");
}
else if (userInput == '\u0020')
{
System.out.println("Blank space is the number 0!");
}
else
{
System.out.println(userInput + " could be either a 1 or the character does not exist");
}
input.close();
}
}
Use:
char userInput = input.nextLine().charAt(0);
instead of:
char userInput = input.next().charAt(0);
Use Scanner.nextLine() instead of next() :
char userInput = input.nextLine().charAt(0);
scanner.nextLine() will capture everything in the line, including whitespace.
scanner.next() will not capture whitespace as the delimiter is whitespace by default.
So, try using scanner.nextLine();
The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}
Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.
Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am just finishing my program, but I still have one problem left that I can't seem to find an answer too. I have been looking through already asked questions but I couldn't find something that specifically answers my question in this case. This is a program that lets the user input a string and then it counts how many vowels and consonants etc. And after this the user gets an option to repeat the program and input a new string if he/she press y, the program quits if he/she press n etc. The only thing that is not working is if the user presses y to repeat the program, it then prints out that there are 0 vowels and consonants etc. I know that it is something in the beginning of my code where I have int consonant_count=0 for example, I just can't figure out what to move and where to move it. Ps. this shouldn't be flagged as a duplicate since I didn't know that nextLine was the problem. Here is the code:
import java.util.Scanner;
public class loop2
{
public static void main (String[] args)
{
Scanner inputReader = new Scanner (System.in);
char result='y';
do {
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
// Kod f ̈or hantering av repetition
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.next();// H ̈amta anv ̈andarens svar.
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
result='y';
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
}
while (result == 'y'); // Observera semikolon!
}
}
You should use the nextLine() when reading input from the user, this grabs everything including the end of line character '\n' which is what gets left over after your next() call and then nextLine() grabs the '\n' which gives you the counts of 0, 0 for vowels and consonents
Scanner inputReader = new Scanner (System.in);
char result='y';
while(result == 'y')
{
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
//wrap your play again logic in another do/while where you
// ask for y or n until they enter either one
do {
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.nextLine();//read the entire next line <----
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
} while (result !='y' && result !='n');
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Here is my code, I know the if statement is really long and the code could probably be more efficient, but I just want to know the answer to this as it is driving me nuts.
while (whileloop == 1)
{
if (guess != 'a' || guess != 'A' || guess != 'b' || guess != 'B' || guess != 'c' || guess != 'C' || guess != 'd' || guess != 'D' || guess != 'e' || guess != 'E' || guess != 'f' || guess != 'F' || guess != 'g' || guess != 'G' || guess != 'h' || guess != 'H' || guess != 'i' || guess != 'I' || guess != 'j' || guess != 'J' || guess != 'k' || guess != 'K' || guess != 'l' || guess != 'L' || guess != 'm' || guess != 'M' || guess != 'n' || guess != 'N' || guess != 'o' || guess != 'O' ||guess != 'p' || guess != 'P' || guess != 'q' || guess != 'Q' || guess != 'r' || guess != 'R' || guess != 's' || guess != 'S' || guess != 't' || guess != 'T' || guess == ' ')
{
System.out.println ("\nNot a Point. Try again.");
guess = IBIO.inputChar ("If the missile is launched from Point B, which Point will the missile hit? ");
}
else
whileloop = 2;
}
Because you wanted a logical and && (not a logical or ||). When you use || if any condition is true (such as the letter A not being the letter B, the entire expression is true). You could use an || with two ands. Something like
if (!(guess >= 'a' && guess <= 'z') || !(guess >= 'A' && guess <= 'Z'))
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am trying to create a program in java which asks the user to enter a string, the number equivalent of the string is then given as the output. eg ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9). my code is below. The problem is once the user inputs their string to be converted I get no output(and no errors). I was wondering if someone could have a look and give me some advice. what i am trying to do is turn the string that the user has entered into an array and then use a for loop with nested if statements to go through the array and whatever letter there is in [i] give the equavilent number. but the system.out isnt working?
import java.util.Scanner;
public class keyPad {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a string:");
Scanner userInput = new Scanner(System.in);
String convertString = userInput.next();
int length = convertString.length();
String[] stringArray = new String[length];
for(int i=0; i<length; i++){
if(stringArray[i] == "a" || stringArray[i] == "b" || stringArray[i] == "c"){
System.out.println("1");
}
if(stringArray[i] == "d" || stringArray[i] == "e" || stringArray[i] == "f"){
System.out.print("2");
}
if(stringArray[i] == "g" || stringArray[i] == "h" || stringArray[i] == "i"){
System.out.print("3");
}
if(stringArray[i] == "j" || stringArray[i] == "k" || stringArray[i] == "l"){
System.out.print("4");
}
if(stringArray[i] == "m" || stringArray[i] == "n" || stringArray[i] == "o"){
System.out.print("5");
}
if(stringArray[i] == "p" || stringArray[i] == "q" || stringArray[i] == "r" || stringArray[i] == "s"){
System.out.print("6");
}
if(stringArray[i] == "t" || stringArray[i] == "u" || stringArray[i] == "v"){
System.out.print("7");
}
if(stringArray[i] == "w" || stringArray[i] == "x" || stringArray[i] == "y" || stringArray[i] == "z"){
System.out.print("8");
}
}
}
}
In your program you take the input from the user but you havent put it in the array you are comparing .The string array is empty.So you are not getting an output.
Instead of using == in your if statements, use string1.equals(string2);
Look at this stackOverflow answer for more: How do I compare strings in Java?
You also need to add the input string into the array which you are checking.