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
Related
I am trying to learn "if else" statements and I am having trouble with the middle 'if else' part of the script.
package practice;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("enter a number between 1 and 10 ");
if (!in.hasNextDouble()) {
String word = in.next();
System.err.println(word + " is not a number");
} else if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
System.err.println(wrongnumber + " is not between 1 and 10");
} else {
System.out.println("It works!");
}
return;
}
}
There are no errors but in the 'else if' block I can't get it to print the err "..... not between 1 and 10", whether or not I put a number between 1 and 10 or higher. It also wont print the "it works!" line anymore when I add the 'else if' block.
any suggestions would be much appreciated.
You are caling in.nextDouble() several times in your if else block, so you get something else every time.
if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
System.err.println(wrongnumber + " is not between 1 and 10");
}
convert it to something like
double next = in.nextDouble();
if (!(next > 0) || !(next <= 10)) {
Double wrongnumber = next;
System.err.println(wrongnumber + " is not between 1 and 10");
}
To be logically correct you might switch to Integer instead of Double values.
You call in.hasNextDouble() several times. Each time it scans new number from input so it may cause your issue. You should also consider how you write conditions. I am aware you may just try what's happening there but this kind of condition is hard to read. You can use
(number <= 1) || (number > 10) (remove negations by inverting operators) for example.
else if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
I'm not sure but here you operate on 3 different numbers. Before condition, write it to a variable.
Don't compare int with double
#RevCarl, According what i understand by your code and the description provided, what you want to do is to check whether the input is a number and whether its between 1 to 10. Also you have not clearly said the type of the input you are expecting. I assume it as integer, and the code below will do the task.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a No between 1 to 10");
String next = input.next();
Integer i = Integer.parseInt(next);
if (null == i) {
System.out.println("Input is not a number");
} else {
if (i > 0 && i < 10) {
System.out.println("It works");
} else {
System.out.println("Not Between 1 to 10");
}
}
}
}
Otherwise u can replace the statement String next = input.next(); with Integer i = input.nextInt(); which takes the integer numbers input from the console.
I'm trying to make this Sentinel program more robust by continuing it even when incorrect user inputs are received. I've gotten it to work if the user input is a different int, but if it is a string, or anything else really, the program crashes.
My current code attempt is this:
} else if (userInt != 1 && userInt != 2 && userInt != 3 && userInt != 4 && userInt != 5 && userInt !=6
|| userInt instanceof String) {
The first part of this code works fine at checking if the user input is a different in. The instanceof statement gives the error of "incompatible operand types int and String"
Should I even be using an instanceof statement? Is there a better way to check for this?
This is the whole method:
public static void printMenu() {
Scanner userInput2 = new Scanner(System.in);
String menu = new String(" Please choose from the following menu: \n 1. Rock paper Scissors\n 2. "
+ "Tip Calculator\n 3. "
+ "Number Adding\n 4. Guessing Game\n 5. Random\n 6. Exit");
System.out.println(menu);
int userInt = userInput2.nextInt();
if (userInt == 1) {
System.out.println(" You asked to play Rock Paper Scissors");
System.out.println(" Launching Rock Paper Scissors... \n");
RockPaperScissors gameRun1 = new RockPaperScissors();
gameRun1.main(null);
} else if (userInt == 2) {
System.out.println(" You asked to run the Tip Calculator");
System.out.println(" Launching the Tip Calculator... \n");
TipCalculator gameRun2 = new TipCalculator();
gameRun2.main(null);
} else if (userInt == 3) {
System.out.println(" You asked to run the Number Adding game");
System.out.println(" Launching the Number Adding game... \n");
NumberAddingGame gameRun3 = new NumberAddingGame();
gameRun3.main(null);
} else if (userInt == 4) {
System.out.println(" You asked to play GuessingGame");
System.out.println(" Launching GuessingGame... \n");
GuessingGame gameRun4 = new GuessingGame();
gameRun4.main(null);
} else if (userInt == 5) {
System.out.println(" You asked for a random game");
option5();
} else if (userInt == 6) {
System.out.println( "Thank you for using Conner's Sentinel");
// figure out how to terminate the program from here
} else if (userInt != 1 && userInt != 2 && userInt != 3 && userInt != 4 && userInt != 5 && userInt !=6
|| userInt instanceof String {
System.out.println("Not a valid input, type 1-6");
printMenu();
}
printMenu();
}
There is no way to check if the next input was an int like you are doing (userInput2.nextInt() can only return an int), instead you have to check before you assign the result. Something like,
if (userInput2.hasNextInt()) {
int userInt = userInput2.nextInt();
if (userInt == 1) {
System.out.println(" You asked to play Rock Paper Scissors");
System.out.println(" Launching Rock Paper Scissors... \n");
RockPaperScissors gameRun1 = new RockPaperScissors();
gameRun1.main(null);
} else if (userInt == 2) {
System.out.println(" You asked to run the Tip Calculator");
System.out.println(" Launching the Tip Calculator... \n");
TipCalculator gameRun2 = new TipCalculator();
gameRun2.main(null);
} else if (userInt == 3) {
System.out.println(" You asked to run the Number Adding game");
System.out.println(" Launching the Number Adding game... \n");
NumberAddingGame gameRun3 = new NumberAddingGame();
gameRun3.main(null);
} else if (userInt == 4) {
System.out.println(" You asked to play GuessingGame");
System.out.println(" Launching GuessingGame... \n");
GuessingGame gameRun4 = new GuessingGame();
gameRun4.main(null);
} else if (userInt == 5) {
System.out.println(" You asked for a random game");
option5();
} else if (userInt == 6) {
System.out.println("Thank you for using Conner's Sentinel");
// figure out how to terminate the program from here
} else {
System.out.println("Not a valid input, type 1-6");
printMenu();
}
} else {
userInput2.nextLine(); // <-- consume the non-number
System.out.println("Not a valid number, type 1-6");
printMenu();
}
Instead of "expecting" an int...
int userInt = userInput2.nextInt();
You should "expect" a String...
int actualInput = userInput2.nextLine();
From this you could then use Integer.parseInt(String) in an attempt to parse the String to an int, this will give you your first chance to validate the value.
The problem with this is Integer.parseInt(String) can throw a NumberFormatException, and you really should avoid making logic decisions based on exceptions.
Another approach might be to use a regular expression instead, something like...
if (actualInput.matches("^\\d*")) {
// This is a number, safe to parse to int
} else {
// This is not a number and is not safe to be parsed
}
Once you're satisfied that the actualInput is a number, you could use another Scanner to get the next int...
Scanner safeScanner = new Scanner(actualInput);
int userInt = safeScanner.nextInt();
as an example
userInt instanceof String will always be false, since userInt is an int. If it is an int, you don't need to check for instanceof string.
What you meant is to proof check the string from user input with StringUtils.isNumeric and reduce your other expressions to:
if 1<= userInt && userInt <=6
Should I even be using an instanceof statement? Is there a better way
to check for this?
Even if some other string, non numeric, could be converted to int and result into a value between 1 and 6, this way it would be rejected. Keep the numeric check, yes, just the correct one, StringUtils.isNumeric .
If you opt to have userInt as String, instead, then turn the other expression into if 1<= Integer.parseInt(userInt) && Integer.parseInt(userInt) <=6
First of all, after you write something like this:
int userInt = userInput2.nextInt();
your userInt is declared as an int, and can be nothing but a int. So writing something like this makes no sense:
userInt instanceof String
Because here, you already know that userInt is an int, because you declared it so.
The problem (where the exception, or crash as you called it, occurred) is elsewhere. It will happen at the call to nextInt().
Read the documentation for Scanner.nextInt(), under the exceptions, it states:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
So that is exactly what happens.
You have several choices, two of which:
catch the exception, and handle it the way you want it to be handled
Use of Scanner.hasNextInt().
I already see a growing number of alternative approaches.
Also most people would translate that chain of if/else if statements into a switch/case/default construct.
Then an other problem in your printMenu() method, it is endlessly recursive. Even though it is just user input, and it might have a limited timespan, with limited user entries before it exits, in theory you could reach a situation where you get a StackOverflowException. This implementation begs to be converted from recursive to iterative to avoid overallocation of objects (memory leak) and having a stack that grows forever.
I am currently learning java script and attempting new things, for example I wish to see if I can set a boolean expression to end if it detects a starting number through an ending number.
Or in other terms what I'll want is 3 through 8.
I will make it clear I am using netbeans IDE.
Within my last else if statement, I want it to end the asking process. I am hoping it is a simple fix, but I can not think of anything that will accomplish this unless I create a lot more else if statements.
Scanner input = new Scanner(System.in);
int[][] table;
boolean stopasking = true;
while (stopasking = true){
System.out.println("Let's make a magic Square! How big should it be? ");
int size = input.nextInt();
if (size < 0)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size >= 9)
{
System.out.println("That's huge! Please enter a number less than 9.");
System.out.println("");
}
else if (size <= 2)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size == 3)
{
stopasking = false;
}
}
You have used the assignmnent operator =
you should use == instead
also the condition size<=2 holds when size<0 so you can use one if for both
while(stopasking){
if (size <= 2) {
System.out.println("That would violate the laws of mathematics!\n");
} else if (size >= 9){
System.out.println("That's huge! Please enter a number less than 9.\n");
} else if (size == 3){
stopasking = false;
}
}
you can use the boolean expression in this way, as condition to exit from a loop. Some would say it is a more elegant solution than break.
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.
trying to terminate program using negative numbers and if else statement . does anyone see whats wrong with this thanks.
import java.util.Scanner;
public class Assignment {
public static void main(String args[]){
int n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
int backUp = n;
if(n>0)
n=n/10;
i++;
else if(backUp = -1)
System.out.print("program terminated......");
System.exit(0);
System.out.println("Number of Digits in " +backUp +" is " +i);
}
}
First of all, = is for assigning values. Use == for comparing.
Also, you need to use {} after if and else statements if you want to run more than one line.
else if(backUp = -1)
Should be
else if(backUp == -1)
= assignment operator , == is for comparing
And finally with missed {}
if (n > 0) {
n = n / 10;
i++;
} else if (backUp == -1) {
System.out.print("program terminated......");
System.exit(0);
}else{
// do something else. I have no idea.
}
You are missing { } for your if-statements. In if statements without the { }, only the line following the if-statement will be affected by the outcome of the if-test.
So:
if (condition)
doSomething();
doSomethingElse();
will execute doSomething() if condition == true and doSomethingElse() no matter if condition == true.
if (condition) {
doSomething();
doSomethingElse();
}
will execute both doSomething() and doSomethingElse(), if and only if condition == true.
You are using an assignment operator to evaluate a condition.
else if(backUp = -1)
should be
else if(backup == -1)
remove else use if(backup==-1).
First of all your indenting.
Secondly, if you want to execute multiple statements given a certain condition you'll need to put it in a code block like if(x) { /* do multiple things */ }.
Thirdly, your else if(backUp = -1) is invalid because you need a boolean expression inside a if, backUp = -1 is an assignment and thus does not evaluate to a boolean (you probably want backUp == -1).
And you probably want to loop the n = n/10; i++; part because now it will never count more than 1 digit.