[英]How to continue an if else statement (?) with another if else statement
A little confused on where to put another if-else statement after one.有点困惑在哪里放置另一个 if-else 语句。 like do I put it under the if statement ("have you registered to vote yet?" ) or do i put it under the else statement?喜欢我把它放在 if 语句下(“你注册投票了吗?”)还是放在 else 语句下?
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");
}
}
}
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.对于 elif 语句,您将 elif 放在 else 之前,但请确保为 elif 语句添加一个子句,以便像使用原始 if 语句一样运行。
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");
}
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");
}
You have to use it in first if
:如果出现以下情况,您必须首先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");
}
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");
}
Implement via switch command and use cases.通过 switch 命令和用例实现。 Its the best approach.它是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.