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

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.

Related

Need Help to Understand Some Basic Java concepts about While loop conditional statements and type conversion

I was just trying to code a simple calculator and it works fine...
What I want to do now is include a 'do while' or 'while' loop to repeat a statement till a user enters one of the four basic operator signs. I have achieved it using other methods (if and switch) but I want to simplify it.
Also I faced a lot of problems learning how to parse a character in scanner and JPane methods. I could achieve using various resources on the internet but a simple method that would help me understand the logic more clearly and not just achieve will be highly appreciated...
public class MyCalculator{
public static void main (String [] args){
// Let us code a simple calculator
char OP;
System.out.println("This is a simple calculator that will do basic calculations such as :\nAddition, Multiplication, Substraction and Division.");
// Create a scanner object to Read user Input.
Scanner input = new Scanner(System.in);
System.out.println("Enter Any positive number followed by pressing ENTER.");
int firstNum = input.nextInt();
// Need to Loop the below statement till one of the four (+,-,*,/) operator is entered.
System.out.println("Enter your choice of OPERATOR sign followed by pressing ENTER.");
OP = input.next().charAt(0);
System.out.println("Enter your Second number followed by an ENTER stroke.");
int secNum = input.nextInt();
// Various possible Resolution
int RSum = firstNum+secNum;
int RSubs= firstNum-secNum;
int RPro = firstNum*secNum;
double DPro = firstNum/secNum;
// Conditional statements for Processing
Switch (OP){
case '+': System.out.println("The Resulting sum is "+ RSum);
break;
case '-': System.out.println("The Resulting sum is "+ RSubs);
break;
case '*': System.out.println("The Resulting Product is "+ RPro);
break;
case '/': System.out.println("The Resulting Divisional product is "+ DPro);
break;
default : System.out.println("Try Again");
}
}
}
You can use something like this:
while(scanner.hasNext()) {
//some code
int number = scanner.NextInt();
}
But I would implement a calculator as follow:
int num1 = scanner.NextInt();
String op = scanner.Next();
int num2 = scanner.NextInt();
You can loop through a String as follow and do your checks:
for (char ch : exampleString.toCharArray()){
System.out.println(ch);
}
You can also loop through a String as follow:
for (int i=0; i<examplestring.length(); i++) {
char c = examplestring.charAt(i);
}
You can loop until you get a + or a - as follow:
char operator;
do {
char operator = scanner.next().get(0);
}while(operator != '+' || operator != '-')
You can loop and print error messages as follow:
char operator;
do {
char operator = scanner.next().get(0);
if(!isValidOperator(operator)) {
System.out.println("invalid operator");
}
}while(!isValidOperator(operator))
public boolean isValidOperator(char operator) {
if(operator == '+') {
return true;
} else if (operator == '-') {
return true;
}
return false;
}

Loop certain IF statements in java

import java.util.Scanner;
public class main {
public static void main(String[] args) {
int number = 0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of sides");
number = input.nextInt();
if (number == 1) {
System.out.println("Circle");
}
if (number == 3) {
System.out.println("Triangle");
}
if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
}
}
Hello, I am trying to use the if statement. Can anyone advise me how to loop if statements? Because I get this as a result for example:
circle
Incorrect Input.
Also, How could I repeat the scanner so it allowed me to type another input?
Currently, the else clause is only associated to the last if block i.e. if (number == 4) {...} This means if any of the other if blocks are executed, it will still print "Incorrect Input". The solution is to use else if instead of separate if's.
if (number == 1) {
System.out.println("Circle");
}else if (number == 3) {
System.out.println("Triangle");
}else if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
You can use switch case (see : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html).
And you can check the type of number or string with instanceof.
For your second part question, I guess you're looking for something like a do....while loop, you can set up some condition like if the input result is not a number, then it will stuck in the loop until the user type in a number then only go in the the if, else-if statement

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

Java loop- keeps on asking for user input

I looked at some other similar posts but was not able to figure out the solution, hence looking for your valuable input, thanks in advance.
What I want: You will be asked to enter a sign (+ , -, /) and the output will display "You entered minus" (if your input was -)
Class that takes the input
import java.util.Scanner;
public class TakeSign {
Scanner userInput = new Scanner(System.in); /*Create an object of scanner class*/
public char mySign() {
System.out.print("Enter a sign: ");
char input2 = userInput.next().charAt(0);
return input2;
}
}
Main Class
public class Main {
public static void main (String[]args) {
TakeSign ts = new TakeSign();
if (ts.mySign() == '+') {
System.out.println("You entered plus");
}
else if (ts.mySign() == '-') {
System.out.println("You entered minus");
}
else if (ts.mySign() == '/') {
System.out.println("You entered division");
}
}
}
Problem
If my 1st input is / (division) I get asked 3 times. I was expecting to be asked just 1 time.
Enter a sign: /
Enter a sign: /
Enter a sign: /
You entered division
I think the problem is in the loop which I probably did not write correctly. Can you please point me to right direction?
You need to assign ts.mySign() to a variable and use that variable in your if statements
public static void main(String[] args) {
TakeSign ts = new TakeSign();
char sign = ts.mySign();
if (sign == '+') {
System.out.println("You entered plus");
} else if (sign == '-') {
System.out.println("You entered minus");
} else if (sign == '/') {
System.out.println("You entered division");
}
}
The mySign method asks the user for input. So if you call ts.mySign() three times, it will ask the user three times. But this is what you're doing in your chain of if and else statements.
You need to call ts.mySign() just once before the if statements, assign the result to a variable, then just check the value of that variable in each of the if statements.
You might use
switch( ts.mySign() ){
case '+':
System.out.println ("You entered plus");
break;
case '-':
System.out.println ("You entered mimus");
break;
case '*':
System.out.println ("You entered asterisk");
break;
case '/':
System.out.println ("You entered slash");
break;
default:
System.out.println ("Input error");
break;
}
You're calling ts.mySign() 3 times in your if-statement.
Call it once and store it in a variable and then compare against your signs.
i.e.
char sign = ts.mySign();
if (sign == '+')
...

multiple variable for if else statement

I have written some code to check if the user has entered a number between 1 and 5, and now I would also like my code to allow the user to enter the letters A, S, D or M.
Is there a way to combine the code where I can have it identify whether the user has entered 1-5 or A, S, D, M?
How do I edit the code below so the user can enter either an Integer or a character? Do I have to write a snippet of code underneath the loop for it to identify that a user did not enter 1-5 but did enter A, S, D, or M, as in break out of the loop? Or is it a separate loop all together. I am so confused!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Selection {
Scanner readInput = new Scanner(System.in);
int selectionOne() {
int inputInt;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for subtraction, M for multiplication, or D for division: ");
try {
inputInt = readInput.nextInt(); //user will enter a response
if (inputInt >= 1 && inputInt <=5) {
System.out.print("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have not entered the correct number, please try again.");
}
continue;
}
catch (final InputMismatchException e) {
System.out.println("You have entered an invalid choice. Try again.");
readInput.nextLine(); // discard non-int input
continue; // loop will continue until correct answer is found
}
} while (true);
return inputInt;
}
}
I suggest instead of using an int input, just use a String input and convert it to an integer when you need to. You can use Integer.parseInt(String) to convert a String to an int.
So when you check if the input is valid, you need to check if the input is equal to "A", "S", "M" or "D", or any values from 1-5 when it is converted to an int.
So to check if it's one of the characters, you could do this:
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D"))
And then to test if it's an int of value 1 through 5, you could do this:
if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5)
Just parse the input to an int and then check the range as you already have done.
The return type of this method will be String now, instead of int. If you need it to be an int for whatever reason, you can just parse the value to an int and then return that instead. But I just returned it as a String.
The last thing I changed was the catch block. Now, instead of an InputMismatchException (because they can enter Strings now, I changed it to NumberFormatException, which would happen if a String that could not be converted to an int was attempted to be. For example, Integer.parseInt("hello") will throw a NumberFomatException because "hello" can not be represented as an integer. But, Integer.parseInt("1") would be fine and would return 1.
Note that you should test the String equivalence first so that you don't go into your block before you have a chance to test all conditions you need to.
The method would look like this:
String selectionOne() {
String input;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for subtraction, M for multiplication, or D for division: ");
try {
input = readInput.nextLine(); //user will enter a response
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D")) {
System.out.println("Thank you");
break; //user entered a character of A, S, M, or D
} else if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5) {
System.out.println("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have not entered the correct number, please try again.");
}
continue;
}
catch (final NumberFormatException e) {
System.out.println("You have entered an invalid choice. Try again.");
continue; // loop will continue until correct answer is found
}
} while (true);
return input;
}
As #MarsAtomic mentioned, first thing you should change your input to String instead of an int so you can easily handle both characters and digits.
Change:
int inputInt;
To:
String input;
Then change:
inputInt = readInput.nextInt();
To:
input = readInput.next();
To accommodate reading String instead of int.
Now you reach at 2 main cases (and 2 subcases):
1) input is a single character
a) input is a single digit from 1-5
b) input is a single character from the set ('A', 'S', 'D', 'M')
2) input is an error value
Also, since you are not calling Scanner.nextInt, you don't need to use the try/catch statement and can print your errors in else blocks.
Furthermore, you should have your method return a char or a String instead of an int so you can return both 1-5 or A,S,D,M. I will assume you want to return a char. If you want to return a String instead, you can return input instead of return val in the code bellow.
NOTE: The code bellow can be simplified and shortened, I just added variables and comments in an attempt to make each step clear to what is being read or converted. You can look at #mikeyaworski's answer for a more concise way of doing this.
Here is how your code could look like:
char selectionOne() {
String input;
do {
input = readInput.next();
// check if input is a single character
if(input.length() == 1) {
char val = input.charAt(0);
// check if input is a single digit from 1-5
if(Character.isDigit(val)) {
int digit = Integer.parseInt(input);
if (digit >= 1 && digit <=5) {
System.out.print("Thank you");
return val; // no need to break, can return the correct digit right here
} else {
System.out.println("Sorry, you have not entered the correct number, please try again.");
}
} else {
// check if input is in our valid set of characters
if(val == 'A' || val == 'S' || val == 'M' || val == 'D') {
System.out.print("Thank you");
return val; // return the correct character
} else {
System.out.println("Sorry, you have not entered the correct character, please try again.");
}
}
} else {
System.out.println("Sorry, you have not entered the correct input format, please try again.");
}
} while(true);
}
If your input can be both characters and letters, why not change to looking for a char or String? Then, you can look for "1" or "A" without any trouble.

Categories