Key input restrictions - java

How do you restrict the letter being inputted;
for example I have the code
System.out.println("Enter a letter(A,B,C or D):");
letter = input.next().charAt(0);
How would I set up an if statement to say if letter does not equal "A" "B" "C" or "D", it will say please input correct letter?
thanks

I would recommend you to use a while loop, so it loops until you get a valid input:
Scanner input = new Scanner(System.in);
System.out.println("Enter a letter(A,B,C or D):");
char letter = input.next().charAt(0);
while (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D') {
System.out.println("Enter a valid letter(A,B,C or D):");
letter = input.next().charAt(0);
}
System.out.println(letter);
Output:
Enter a letter(A,B,C or D):
E
Enter a valid letter(A,B,C or D):
A
Valid: A
But if you just want an if conditional, use the same condition of the while above:
if (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D') {
...
}

Related

Java, How to close do-while loop using multiple character boolean expressions?

This is quite a beginner question but I'm wondering why my do...while loop is not closing.
The program is supposed to loop while the user input is not 'C', 'c', 'F', or 'f'.
It seems to close when just one boolean expression in the while section is valid but not if multiple are valid.
public class CelsToFaren
{
public static void main(String[] args)
{
// scanner setup
Scanner sc = new Scanner(System.in);
// Variable declarations
int celsius;
int answerC;
int farenheit;
int answerF;
char userLetter;
do
{
// initial menu options
System.out.println("Which temperature would you like to convert from? ");
System.out.println(" >(C)elsius ");
System.out.println(" >(F)arenheit ");
// user input of C, c, F, or f to select option
userLetter = sc.next().charAt(0);
// if user input C or c
if ((userLetter == 'C' || userLetter == 'c'))
{
System.out.print("Please enter the temperature: ");
celsius = sc.nextInt();
answerC = ((celsius*9/5)+32);
System.out.println("The answer is: " + answerC + " Farenheit ");
}
else
{
// if user input F or f
if ((userLetter == 'F' || userLetter == 'f'))
{
System.out.print("Please enter the temperature: ");
farenheit = sc.nextInt();
answerF = ((farenheit-32)*5/9);
System.out.println("The answer is: " + answerF + " Celsius ");
}
else
{
// if user input not F, f, C, or c
if ((userLetter != 'F' || userLetter != 'f' || userLetter != 'C' || userLetter != 'c'));
{
System.out.println("Please enter a valid option");
}
}
}
} while ((userLetter != 'c') || (userLetter != 'C') || (userLetter != 'f') || (userLetter != 'F'));
}
}
You need to change the exit logic.
In your case 1 | 0 | 0 = true so the loop continues.
You need to change it to:
while ((userLetter != 'c') && (userLetter != 'C') && (userLetter != 'f') && (userLetter != 'F'));
Your condition is wrong. Lets assume you want to break loop in if statement. It would look like
if(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F')
Now let's apply negation to get a condition under which you do not need to exit the loop
if(!(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F'))
this condition is simillar to
if(userLetter != 'c' && userLetter != 'C' && userLetter != 'f' && userLetter != 'F')

input character inside a while loop with validation

System.out.print("Enter the operator (+ - X /): ");
operator = input.next();
char c=operator.charAt(0);
while (c != '+' && c != '-' && c != '*' && c != '/'){
System.out.println("Operator doesn't match. Try again.");
System.out.print("Enter the operator (+ - X /): ");
input.next().charAt(0);
}
Here, I want an input character value from keyboard which will be only symbols just (+ - * /) inside a while loop. if the sign is not match the while loop will be running.
Here, the while loop is working but the character is not checked. So, while loop continuously works with-
System.out.println("Operator doesn't match. Try again.");
System.out.print("Enter the operator (+ - X /): ");
In the last line of your while loop, you are retrieving an user input, but not storing it anywhere. You should do like that:
c = input.next().charAt(0);
If you want to do something fancy, you could also try using the do-while loop, like below:
char c;
do {
System.out.println("Enter a operator (+ - * /):");
c = input.next().charAt(0);
} while(c != '+' && c != '-' && c != '*' && c != '/');

Counting the vowels in each name, and displaying separately

How I would get this code to count the vowels in each word rather than adding all the vowels up and displaying these. The code I have written:
import javax.swing.JOptionPane;
import java.util.Arrays;
String[] names = new String[12];
int i;
int j;
j=0;
int vowelCount;
vowelCount=0;
char ch;
names[0] = JOptionPane.showInputDialog("Please enter a name");
names[1] = JOptionPane.showInputDialog("Please enter a name");
names[2] = JOptionPane.showInputDialog("Please enter a name");
names[3] = JOptionPane.showInputDialog("Please enter a name");
names[4] = JOptionPane.showInputDialog("Please enter a name");
names[5] = JOptionPane.showInputDialog("Please enter a name");
names[6] = JOptionPane.showInputDialog("Please enter a name");
names[7] = JOptionPane.showInputDialog("Please enter a name");
names[8] = JOptionPane.showInputDialog("Please enter a name");
names[9] = JOptionPane.showInputDialog("Please enter a name");
names[10] = JOptionPane.showInputDialog("Please enter a name");
names[11] = JOptionPane.showInputDialog("Please enter a name");
Arrays.sort(names);
System.out.println("Name" + " " + "Characters" + " " + "Vowels");
for (i=0; i<12; i++)
{
for(j=0; j<names[i].length(); j++)
{
ch=names[i].charAt(j);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowelCount ++;
}
System.out.println(names[i] + " " +names[i].length() + " " + vowelCount);
}
I need the code to accept a user inputted name (which it does), sort the names alphabetically (which it does), count the characters in each name (which it does), and then display the vowels in each name.
Keep a collection of some sort, most likely an ArrayList. As you count the number of vowels, add them to the list.
//declare collection here
for(j=0; j<names[i].length(); j++)
{
ch=names[i].charAt(j);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowelCount ++;
//add ch character to collection
}
System.out.println(names[i] + " " +names[i].length() + " " + vowelCount);
//print vowels in collection
Example use of ArrayList
Just for extra information if you are interested, there are a number of collections you can use depending on whether you need a value/key pair, if you can allow duplicate entries, and if you want a certain order. Additionally, they perform differently depending on how you are using them.
Comparison Chart between different Collection

Java - Get user input and transferring to main function with Switch case

I have a static function which gets and returns a char input.
It will then check the input using a while loop.
After my main method gets the input, the result will display accordingly to the user input.
Below is my method:
public class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char choice = getInput(sc);
String result;
switch (choice)
{
case ('a'): result = "u choose A";
break;
}
}
private static char getInput(Scanner keyboard)
{
Scanner sc = new Scanner(System.in);
System.out.println("a, b, c, d, e, q: ");
char choice = sc.nextLine().trim().toLowerCase().charAt(0);
while (choice != 'a' || choice != 'b' || choice != 'c' || choice != 'd' || choice != 'e' || choice != 'q')
{
System.out.println("You have entered an invalid entry.");
System.out.println("a, b, c, d, e, q: ");
choice = sc.nextLine().trim().toLowerCase().charAt(0);
}
return choice;
}
}
However, I am getting the result of invalid input even though I entered the character 'a'.
May I know which part have I gone wrong?
This condition:
while (choice != 'a' || choice != 'b' || choice != 'c' || choice != 'd' || choice != 'e' || choice != 'q')
will always return true if your choice is not a or is not b or is not c, etc. Change those || operators to && operators and you should be good to go.

Java - charAt(), equalsIgnoreCase, if statement testing?

What I want is no matter what the user inputs, if the first letter of their input is either a 'y' or 'n' regardless of case, it will print "game start".
I've tried equalsIgnoreCase() with the "letter" variable but it gives the error: char cannot be dereferenced. Any recommendations will be really appreciated on this! Thanks!
Scanner input = new Scanner(System.in);
System.out.println("Do you want to continue?");
String wesker = input.nextLine();
char letter = wesker.charAt(0);
if(letter == 'y' || letter == 'p'){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
Try use Character#toLowercase():
if (Character.toLowerCase(letter) == 'y' || Character.toLowerCase(letter) == 'n') {
or
if (Character.toUpperCase(letter) == 'Y' || Character.toUpperCase(letter) == 'N') {
or simply
if( letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N' )
Just check against both cases:
if( letter == 'y' || letter == 'Y' || letter == 'p' || letter == 'P' )
equalsIgnoreCase can be used only by Strings. For your case, if you want to use that method, you can do this:
Scanner input = new Scanner(System.in);
String wesker = input.nextLine();
String letter = wesker.substring(0,1);
if(letter.equalsIgnoreCase("y") || letter.equalsIgnoreCase("n")){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
You could pre-build a set of acceptable characters.
Set<Character> yes = new HashSet<>(Arrays.asList('y','Y','p','P'));
public void test() {
char letter = 'c';
if ( yes.contains(letter)) {
}
}

Categories

Resources