How to structure a validation loop with multiple characters - java

I'm struggling with learning validation loops in Java. I know how I need it to work but I can't seem to get it written.
If you select a character other than A, B, or C you receive an error
while (selection != A && !=B && !=C )
I also tried:
while (Selection != 'A' )
{
if (Selection != 'B')
else if (Selection != 'C')
else System.out.println ("Invalid Entry. Please make another selestion");}
Thank you for any help.

What can help in more complex systems is a case statement:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter A, B or C: ");
String input = scanner.nextLine();
switch(input) {
case "A":
// do something for A
break;
case "B":
// do something for B
break;
case "C":
// do something for C
break;
}
}
Here I used an infinite loop. So for the user to get out of it, one of the options should break it. Therefore I'd add a quit option:
Scanner scanner = new Scanner(System.in);
endless: while (true) {
System.out.print("Enter A, B, C or quit: ");
String input = scanner.nextLine();
switch(input) {
case "A":
// do something for A
break;
case "B":
// do something for B
break;
case "C":
// do something for C
break;
case "quit":
break endless; // break the while loop, not just the switch
}
}
On the other side, if you just want to ensure you have one of the values A, B or C input and then continue with exactly that value, use
Scanner scanner = new Scanner(System.in);
String input = null;
endless: while (true) {
System.out.print("Enter A, B or C: ");
input = scanner.nextLine();
switch(input) {
case "A":
case "B":
case "C":
break endless;
}
}
System.out.println("Thank you for choosing " + input);

Using the new switch with arrow, without break and with comma separated case values:
Scanner scanner = new Scanner(System.in);
char answer = ' ';
while (answer == ' ') {
System.out.println("Enter A, B, C or quit: ");
String input = scanner.nextLine();
switch (input) {
case "A", "B", "C" ->
answer = input.charAt(0);
quit ->
answer = 'q';
default ->
System.out.printf("Not A, B or C: '%s'.", input);
}
}
if (answer == 'q') {
System.exit();
}

Related

An option in my do-while to print out all 3 conditions

String xdd="";
Scanner Lenijs = new Scanner(System.in);
do {
System.out.println("Starting number a: ");
int a = Lenijs.nextInt();
System.out.println("Ending number b: ");
int b = Lenijs.nextInt();
System.out.println("Choose 1.for a-b, 2. for all even and 3. for odd numbers.");
int c = Lenijs.nextInt();
if (c == 1) {
do{
System.out.println(a);
a++;
}while(a<=b);
}
if(c == 2) {
if(a%2==0) {
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
else {
a++;
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
}
if(c == 3) {
if(a%2==0) {
a++;
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
else {
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
}
System.out.println("Do you wish to continue? (Yes/No)");
xdd=Lenijs.next();
}while(xdd.equals("Yes"));
}
}
How could I add a 4th option where the user can print out all 3, as of now you can individually select from 1-3 where u get for 1.just from a-b all numbers, 2.is a-b with only pairs and 3.is a-b only odd, but I wanted a 4th option where u could get them all together and is easy to read/overview. Is that possible to make or it won't look good/can't with my code?
It is generally a good practice to limit a method to doing just one thing. So the method that decides which action to perform should not be performing the action - it passes responsibility to the appropriate method(s). In this case, move each activity into a separate method and use a switch to invoke each as appropriate. The following illustrates the concept.
switch(c) {
case 1:
do1();
break;
case 2:
do2();
break;
case 3:
do3();
break;
case 4:
do1();
do2();
do3();
break;
default:
reportUnknownEntry(c);
}

How to take multiple data types in single line on java?

I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.

"How can I request an if-else input after a switch statement?"

After a switch statement I would like to request a 'Y' or 'N' statement and print out a statement for the respective response. How can I declare the input char, then provide a scanner input for that value?
I've tried using input as a char and an integer. I've also tried using the boolean method as well.
import java.util.*;
public class Dowhile {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
System.out.println("0,1,-1: ");
x = in.nextInt();
switch(x)
{
case 1:
System.out.println("Positive");
break;
case -1:
System.out.println("Negative");
break;
case 0:
System.out.println("Zero");
break;
default:
System.out.println("You're a bad person!");
break;
}
char input = (('Y'||'N'));
System.out.println("Enter 'Y' or 'N'");
in.nextInt();
if(input = 'Y')
System.out.println("OK");
else
System.out.println("wow");
}}
I expect the output to be the println response for the respective input.
I would try something like this:
System.out.println("Enter 'Y' or 'N'");
char input = in.next("Y|N").charAt(0);
if('Y' == input)
System.out.println("OK");
else
System.out.println("wow");
The in.next("Y|N") part requests either a 'Y' or a 'N' (the String "Y|N" is interpreted as a regular expression) and returns the result as a String. The charAt(0) function returns the first (and only) character from this String.
Note that this approach throws an exception if you enter neither 'Y' nor 'N'.
If you want to avoid the exception you can use the following code snippet:
System.out.println("Enter 'Y' or 'N'");
char input = in.next(".").charAt(0);
if('Y' == input)
System.out.println("OK");
else if ('N' == input)
System.out.println("wow");
else
System.out.println("You haven't entered a valid character");
But beware, because your first call to in.nextInt() will still fail if someone enters something that isn't an integer.
Assuming you don't need to expand your program to do anything other than print to the console, the following would be the approach I'd take:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("0,1,-1: ");
int x = in.nextInt();
System.out.println(
x == 1 ? "Positive" :
x == -1 ? "Negative" :
x == 0 ? "Zero" :
"You're a bad person!"
);
System.out.println("Enter 'Y' or 'N'");
System.out.println(in.next().equalsIgnoreCase("Y") ? "OK" : "wow");
in.close();
}
Ternary operators are used for checking the conditions and printing to the console without switch or if statements.

How to choose and write a loop for this specific task?

I am pretty new to Java. Sorry if this is a lame question. I have this chunk of code. It is not the whole thing obviously.
char option = scan.next().charAt(0);
for (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
}
int lengthOne = stringOne.length(); //Getting the lengths for each string
int lengthTwo = stringTwo.length();
if (option == 'a'|| option == 'A') { //If the user inputs a
if (lengthOne == lengthTwo) { //If both lengths are equal
System.out.println("The strings are the same length");
}
Looking for some advice on which loop i should use for this code. The options will be A-F and then Q to quit.
The while loop can seem messy for what you are trying to accomplish. I would use a Switch statement inside a 'do while' loop.
If the user input doesn't match a 'case' then it will go to the default.
When a user enters 'q' to quit then boolean validSelection turns to true and you will exit the 'do while' loop.
public static void main( String[] args )
{
Scanner scan = new Scanner( System.in );
boolean validSelection = false;
do
{
System.out.println( "Please pick an option from the menu above" );
char option = scan.next().charAt( 0 );
switch( option )
{
case 'a':
break;
case 'b':
break;
case 'c':
break;
case 'd':
break;
case 'e':
break;
case 'f':
break;
case 'q':
validSelection = true;
break;
default:
System.out.println( "Choice invalid." );
break;
}
}
while( validSelection == false );
}
}
Add a scan inside the loop.
char option = scan.next().charAt(0);
while (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
Try this
Scanner scan = new Scanner(System.in);
char option = scan.next().charAt(0);
while (option != 'a' && option !='b' && option != 'c'&& option !='d'&& option !='e'&& option !='f'&& option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
You will need the ANDs instead of the ORs or it wont work

Conflicts between 'for' and 'switch'?

I want to try a little programming that can read user input continuously unless input is 0.
But the problem is whatever I enter (except 0), it always shows "Please choose one" (in default part). If I enter 4, it will show me this phrase twice!
I do not understand why. Is there a conflict between for and switch or something?
Here is code:
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0') {
switch(ch) {
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
}
The problem is char ch = (char)System.in.read();. Java does not support character based input very well, I recommend using a Scanner which fixes your output, however the user now has to press return after each input.
import java.io.IOException;
import java.util.Scanner;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
while (!s.equals("0"))
{
switch(s)
{
case "1":
System.out.println("The If");
break;
case "2":
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
s = in.nextLine();
}
}
}
If you don't want to press return, you can also read the character twice, although I can only speculate why this works is that there is a control character sent over the stream. Edit: I thought it could also be another byte of a UTF-16 character which is not used when typing in ASCII characters but System.in.read() returns integers not bytes.
import java.io.IOException;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0')
{
switch(ch)
{
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
ch = (char)System.in.read();
}
}
}
System.in.read() reads a byte from the InputStream and returns it. When you type 1 or any single digit number and press enter, it reads two characters.
Try tying multiple digit number to see how System.in.read() behaves.
You should use scanner for the console input:
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Categories