Is it possible to use a boolean expression in this manner? - java

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.

Related

Checking if a user input that should be an int is a string

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.

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

Java do while loop with multiple conditions not executing properly

I have to write a Magic 8 ball program that will account for user input errors and I have to use a loop to do that.
boolean okay;
do {
System.out.printf("What is your question?\n");
questionStr = keyboard.nextLine();
int length = questionStr.length();
if (questionStr.length() == 0) {
System.out.println("Not allowed.");
okay = false;
} else if (!(questionStr.charAt(length - 1) == '?')) {
System.out.println("Add question mark.");
okay = false;
} else if (questionStr.length() > 60) {
okay = false;
}
okay = true;
} while (!okay);
When I run the code and make it an empty string, it does print out not allowed however it still runs the rest of the code and does not loop back and ask "What is your question?" The same happens with the question mark; it prints out "Add question mark" but does not loop back like it is supposed to. If I make a question longer than 60 characters, the code still executes and does not loop back and continue asking the user "What is your question?" until the code is less than 60 characters. I am trying to figure out what I am doing wrong here.
Move okay = true; before your if statements that negate it,
okay = true;
if (questionStr.length() == 0) {
System.out.println("Not allowed.");
okay = false;
} else if (!(questionStr.charAt(length - 1) == '?')) {
System.out.println("Add question mark.");
okay = false;
} else if (questionStr.length() > 60) {
okay = false;
}
As posted, you unconditionally set okay to true before your condition while (!okay); and thus the loop always ends.

Replace a while ( 1 == 1) loop in Java

I have been unable to find something related to this so far. I've heard that surrounding the majority of your program in a while loop like this makes the program inefficient, is there any better way to get the same effect?
while (1 == 1) {
//User Input
System.out.println("Do you wish to roll? (Y/N)");
if (kb.hasNext()) {
userContinue = kb.next();
}
if (userContinue.equalsIgnoreCase("n")) {
System.exit(0);
}
//Calculations
score = 0;
while (userContinue.equalsIgnoreCase("Y")) {
rollResult = user.rollTwoDie();
score = rollResult + score;
if (score > 21) {
System.out.println("You loose for going over 21.");
System.out.println("Your final score was: " + score);
score = 0;
System.out.println("Play again? (Y/N)");
if (kb.hasNext()) {
userContinue = kb.next();
}
if (userContinue.equalsIgnoreCase("n")) {
System.exit(0);
}
}
else if (score <= 21) {
System.out.println("Your score is: " + score);
System.out.println("Roll again? (Y/N)");
if (kb.hasNext()) {
userContinue = kb.next();
}
}
}
if (userContinue.equalsIgnoreCase("N")) {
while (computerScore <= score && computerScore < max) {
computerResult = computer.rollTwoDie();
computerScore = computerResult + computerScore;
}
userContinue = computer.checkComputerScore(computerScore, score);
}
}
I'm not Java guy, but in many languages 1==1 is usually optimized to true anyway.
So you can use while(true) or while(1==1) or even while (2==2).
It doesn't matter.
In your case it doesn't matter even more, because your while loop is not forcing CPU to work a lot. Your loop is waiting for user input for most of the time. Don't worry about this in this case.
While loops can be extremely inefficient in some cases. In these cases - it's better to use Events instead of loops.
Theoretical example of very incorrect inefficient while loop:
while(true)
{
if(textBox1.Text == "yes") x = 1;
if(textBox1.Text == "no") x = 2;
if (x == 1) doSomething();
if (x == 2) doSomethingElse();
}
It is very inefficient, because you "ask" interface about data in textbox again and again, and there is no reason to do this. There is no pause, CPU and memory are forced to do same thing again and again without pause. In this case - Event should be used.
Events exist in many programming languages. There are many sites, videos and tutorials explaining Events.
Take a look at this video about Events in Java:
Java Programming Tutorial - 52 - Event Handling on Youtube (by Bucky Roberts)
After watching this (and maybe few more Bucky or other tutorial videos) you should understand better why while loops are bad idea sometimes.
It's not necessarily inefficient. It will just run endlessly. If you want that then this isn't necessarily evil.
One thing you may consider is adding a stop boolean. That way you can ask the user if they want to quit, and set the variable to true/false.
boolean stop = false;
while(stop == false) {
//...
}
Also, stylistically I like doing infinite while loops like this:
while(true) {
//...
}
Instead of using "1==1"

Termination of program using if else statement?

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.

Categories