Home > Back-end >  How to continue an if else statement (?) with another if else statement
How to continue an if else statement (?) with another if else statement

Time:11-30

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");
    }
  }
}

CodePudding user response:

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");
}

CodePudding user response:

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");
}

CodePudding user response:

You have to use it in first if:

if (yourage >= votersage) {
  System.out.println("Have you registered to vote?");
  String yes_no = input.next();
  if(yes_no.equals("yes")){
    ...
  }
}
else {
  System.out.println("You are too young to vote");
}

CodePudding user response:

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");
}

CodePudding user response:

Implement via switch command and use cases. Its the best approach.

  • Related