gpt4 book ai didi

java - if语句的使用

转载 作者:行者123 更新时间:2023-11-30 10:35:57 26 4
gpt4 key购买 nike

我是 Java 初学者,正在学习 if 语句没有 else,请社区检查我的代码以改进?

问题陈述:在这段代码中我们只使用 if 语句来练习。这里需要输入年龄才能进入有辣妹的酒吧,如果你的年龄在18岁以上就可以进入。 如果低于 18 岁,则不能进入。

import java.util.Scanner;

public class Main {
public static void main(String[] args){

Scanner input = new Scanner(System.in);

int age;

// Ask the age
System.out.println("Please write your age to enter to the bar:");
age = input.nextInt();

// Equal to
if(age == 18){
System.out.println("Your age " + age + " it's equal to 18, you can enter");
}

// Not equal to
if(age != 18){
System.out.println("Your age " + age + " it's not equal to 18");
}

// Greater than
if(age > 18){
System.out.println("Your age " + age + " " + "is greater than 18, you can enter");
}

// Less than
if(age < 18){
System.out.println("Your age " + age + " " + "is less than 18, you can't enter");
}

// Greater than or equal to
if(age >= 18){
System.out.println("Your age " + age + " is greater than or equal to 18, you can enter");
}
// Less than or equal to
if(age <= 18){
System.out.println("Your age " + age + " is less than or equal to 18, you can't enter");
}
}
}

最佳答案

从技术上讲,您只有 三种 情况:

  • age < 18
  • age == 18
  • age > 18

所以你可以把你的代码简化成

...
if (age < 18) {
System.out.println("Your age " + age + " it's not equal to 18");
System.out.println("Your age " + age + " is less than 18, you can't enter");
System.out.println("Your age " + age + " is less than or equal to 18, you can't enter");
}

// "else if" instead of "if" will make the code more readable
if (age == 18) {
System.out.println("Your age " + age + " it's equal to 18, you can enter");
System.out.println("Your age " + age + " is greater than or equal to 18, you can enter");
System.out.println("Your age " + age + " is less than or equal to 18, you can't enter");
}

// "else" instead of "if" will make the code more readable
if (age > 18) {
System.out.println("Your age " + age + " it's not equal to 18");
System.out.println("Your age " + age + " is greater than 18, you can enter");
System.out.println("Your age " + age + " is greater than or equal to 18, you can enter");
}

如果您想确保age >= 18 :

if (age >= 18) {
System.out.println("Your age " + age + " is greater than or equal to 18, you can enter");
}

// "else" is a better choice here
if (age < 18) {
System.out.println("Your age " + age + " is less than 18, you can't enter");
}

关于java - if语句的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40834020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com