How to continue an if else statement (?) with another if else statement - java

A little confused on where to put another if-else statement after one. like do I put it under the if statement ("have you registered to vote yet?" ) or do i put it under the else statement?
I wanted it to answer if yes then it would print out "you can vote" and if no then it would print out "You must register before you can vote"
here's the code
import java.util.Scanner;
public class voting {
public static void main(String[] args) {
int yourage, votersage;
votersage = 18;
Scanner input = new Scanner(System.in);
System.out.println("How old are you? ");
yourage = input.nextInt();
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else {
System.out.println("You are too young to vote");
}
}
}

I think this works to how you want it. You may need to change around the input'Registered as I am a bit rusty with inputs but I think this should work?
if (yourage >= votersage) {
Scanner input = new Scanner(System.in)
System.out.println("Have you registered to vote?");
Registered = input.next();
if Registered = ("Yes") {
System.out.println("You can vote");
}
else if Registered = ("No"){
System.out.println("You need to register to vote");
}
else:
System.out.println("INVALID INPUT")
}
else {
System.out.println("You are too young to vote");
}

For elif statements you put the elif before the else, but make sure to add a clause for the elif statement to run just like you did with the original if statement.
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else if (yourage <= votersage){
System.out.println("You must register before you can vote.");
}
else {
System.out.println("You are too young to vote");
}

Nested if statement work in these scenarios...
if (yourage >= votersage)
{
System.out.println("Have you registered to vote?");
bool registered = input.next();
if(registered)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please get yourself register on voting portal!");
}
}
else {
System.out.println("You are too young to vote");
}

Related

Issue with refactoring of a switch statement

Here is the method that performs the switch(Note The switch statement works correctly and according to the requirements)
public void performChecks() {
priceInput = priceReader.nextDouble();
loop: while(true){
nameInput = nameReader.nextLine();
switch(nameInput){
case "A1": Cola colaItem = new Cola();
if(colaItem.checkPrice(priceInput)){
System.out.println("You ordered " + colaItem.getName()+ ", here is it");
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
}
break loop;
case "B2": Chips chipsItem = new Chips();
if(chipsItem.checkPrice(priceInput)){
System.out.println("You ordered " + chipsItem.getName()+ ", here is it");
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
}
break loop;
case "C3": Crackers crackerItem = new Crackers();
if(crackerItem.checkPrice(priceInput)){
System.out.println("You ordered " + crackerItem.getName()+ ", here is it");
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
}
break loop;
default:
System.out.println("Sorry, we don't have item with such a code");
}
}
}
Now I started doing some refactoring and put the method in the super class of the items(Cola, Chips and Crackers) and it looks like this:
public void performChecks(){
inputPrice = priceReader.nextDouble();
inputCode = codeReader.nextLine();
initializeItems();
for(int i = 0; i < items.length; i++){
if(items[i].checkCode(inputCode)){
if(items[i].checkPrice(inputPrice)){
System.out.println("You ordered " + items[i].getName() + " here it is");
break;
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
break;
}
} else if(!items[i].checkCode(inputCode)){
continue;
} else {
System.out.println("Sorry, we don't have item with such a code");
inputCode = codeReader.nextLine();
}
}
}
The issue is the following: When I enter correct/incorrect price and incorrect item code, I should be getting the "Sorry, we don't have an item with such a code" message and the option to enter the item code again. I've ran out of ideas on how to implement this option inside the
else if(!items[i].checkCode(inputCode)){
continue;
Since I'm pretty sure, it just gets stuck there and returns nothing(for incorrect item code).
What you are trying to achieve can be solved with a simple "found" boolean. Like this:
boolean found = false;
for(Item item : items) {
if(item.checkCode(inputCode)){
found = true;
[...] // Here you found the item and you can check the price and other stuff
}
}
if(!found) {
[...] // Here you can handle the case of the incorrect code
}
I'm not absolutely sure, but I guess you can do sth like this:
inputCode = codeReader.nextLine();
do{
if(items[i].checkCode(inputCode)){
if(items[i].checkPrice(inputPrice)){
System.out.println("You ordered " + items[i].getName() + " here it is");
break;
} else {
System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
break;
}
} else {
inputCode = codeReader.nextLine();
}
} while(!items[i].checkCode(inputCode));

JAVA While loop - last else if statement not working

package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("What is the password?");
Scanner new2 = new Scanner(System.in);
int input = 0;
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
}
}
}
basically, once I hit the 5 loops, it just says "incorrect password" and breaks. not the "maximum attempts" message.
Allow me to annotate:
This if statement will always be evaluated:
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
This if statement will only be evaluated if the password is "bluesky123". In this case, it will always evaluate to true.
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
There is no case when this if statement will ever be evaluated. Once if-else finds a statement that is true, it will skip all others in that section.
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
In your case, you should consider a nested if (i.e. an if inside another if).
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else {
System.out.println("You got it right!");
break;
}
if((input == 5) && (!password.equals("bluesky123"))) {
System.out.println("maximum number of attempts reached");
break;
}
}
Your logic has some flaws. You have to pay attention to how JAVA processes if / else if
https://www.tutorialspoint.com/java/if_else_statement_in_java.htm
I tested your code it is working! The only thing that you need to do is to move the follow line to inside the while loop
System.out.println("What is the password?");
Doing this it will print "Incorrect password" and then it will print again
"What is the password?"
Because in the way that it is working now seems that the software is not waiting the password to be retyped when in fact it is.

Where should I put a Scanner.close();?

i need to know where i should put a Scanner close in this code to stop resource leak.
public class guess_main {
public static void main(String[] args) {
Random numGenerated = new Random();
int numToGuess = numGenerated.nextInt(100);
int numTries =0;
int Guess;
boolean win = false;
Scanner inputNum = new Scanner(System.in);
while (win == false){
System.out.println("Please guess a number between 1 and 100");
Guess = inputNum.nextInt();
numTries++;
if (Guess == numToGuess){
win = true;
}
else if (Guess < numToGuess) {
System.out.println("Your guess is LOW!");
}
else if (Guess > numToGuess){
System.out.println("Your guess is HIGH!");
}
}//End of loop
System.out.println("You won in " + numTries + " goes. Well done!");
}
}
Add it at the end of the loop.
Things should be closed as soon as you are done using them.
If you do anything else with the scanner afterwords, you will need to move it. For example, if you rewrite it to offer the option for another game, you will need to place the closing statement after your confirm that they don't want to play.
You should put it after the end of your loop:
while (win == false) {
...Game logic...
}
inputNum.close();
What this does is close the input stream, so you don't have memory leaks.
In addition to that, please follow Java coding conventions. The only (non-indent related) breaches I saw was that Guess is capitalized, but it's an object, and guess_main should be GuessMain (Uppercase and using camelCase instead of underscores) but it's good to keep an eye out, just in case.
Addendum: As David Wallace pointed out, there is a method that might throw an exception. If you don't care, then the above solution will work, but if you do, this is better:
try (Scanner inputNum = new Scanner(System.in)) {
...Game logic...
} catch (InputMismatchException e) {
e.printStackTrace();
}

MasterMind-Resource Leak?

My code is running fine, but every line where I use a scanner it warns me that there is a "Resource leak; 'userGuess' is never closed" I don't understand what it means and could use some help solving it. Also if there is anything else in my code worth fixing I could use the help. Be warned I have a limited knowledge of Java programming. I also cannot get my TryCounter++ to work...
package masterMind2_1;
import java.util.Scanner;
public class MasterMind2_1 {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
// //Create Board
// System.out.println("-- -- -- --");
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
System.out.println("What is the first Number?");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
if (num==answerArray[0]) {
guessedCount++;
}
System.out.println("What is the Second Number?");
Scanner userGuess1 = new Scanner(System.in);
int num1 = userGuess1.nextInt();
if (num1==answerArray[1]) {
guessedCount++;
}
System.out.println("What is the Third Number?");
Scanner userGuess2 = new Scanner(System.in);
int num2 = userGuess2.nextInt();
if (num2==answerArray[2]) {
guessedCount++;
}
System.out.println("What is the Fourth Number?");
Scanner userGuess3 = new Scanner(System.in);
int num3 = userGuess3.nextInt();
if (num3==answerArray[3]) {
guessedCount++;
}
System.out.println("Your guess was "+ num+" "+num1+" "+num2+" "+num3);
if (num==answerArray[0]) {
System.out.println("First number was correct");
} else {
System.out.println("First number was incorrect");
}
if (num1==answerArray[1]) {
System.out.println("Second number was correct");
} else {
System.out.println("Second number was incorrect");
}
if (num2==answerArray[2]) {
System.out.println("Third number was correct");
} else {
System.out.println("Third number was incorrect");
}
if (num3==answerArray[3]) {
System.out.println("Fourth number was correct");
} else {
System.out.println("Fourth number was incorrect");
}
if (guessedCount==4) {
System.out.println("YAY you won!!");
guessedAll=true;
tryCounter=10;
} else {
System.out.println("Try again, except this time don't fail!");
guessedAll=false;
tryCounter++;
guessedCount=0;
}
}//What if I collected all of the values first
} //then told them if they were right or Wrong?
//Black and White Pegs?
//Fix TryCounter...Why isn't it working
}
Thank you for the Help!
The error message is telling you that you never call the close() method on your Scanner object. A worse problem is that you create multiple Scanners when you only need one.
As for tryCounter not working...
while(tryCounter<9 || !guessedAll)
This will keep looping if either part of the condition is true. My guess is that !guessedAll is evaluating to true beyond 9 guesses, so your loop keeps running. You'll need to change the || to an && to get it stop looping after 9 tries. (Also, print out the values of your variables or use a debugger so you can verify that they are changing when you expect them to.)

How to automatically output strings in loops

So I just have a quick little issue
int pickmeup = 0;
while (true)
{
pickmeup = scanner.nextInt();
if (pickmeup == 1)
{System.out.println ("you entered 1");}
if(pickmeup == 2)
{System.out.println ("you entered 2");}
{
break;
}
System.out.println ("Invalid code");
Now when I run this code it all works fine however in regards to the strings but it seems as though the loop doesn't work all that well when I enter '3', as it doesn't return the string 'Invalid code'.
If I were to get rid of the strings after both if statements, then it works perfectly fine. What exactly am I doing wrong? Are there other ways to automatically have strings output?
I believe you want to use a logical or || and an else like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1 || pickmeup == 2) {
System.out.printf("you entered %d%n", pickmeup);
} else {
System.out.println("Invalid code");
}
}
Alternatively, you could use an else if chain like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1) {
System.out.println("you entered 1");
} else if (pickmeup == 2) {
System.out.println("you entered 2");
} else {
System.out.println("Invalid code");
}
}
You could start with firstly correcting your code, you can do that in eclipse Source-Format or by pressing CTRL+SHIFT+F
For your example, I corrected as much as I understood, currently it breaks only if else is reached. Break can be modified.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pickmeup = 0;
while (true){
pickmeup = scanner.nextInt();
if (pickmeup == 1){
System.out.println("one");
}
else if (pickmeup == 2){
System.out.println("two");
}
else{
System.out.println("Invalid code");
break;
}
}

Categories