gpt4 book ai didi

java - 如何压缩这些大的 if 语句

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:05:01 26 4
gpt4 key购买 nike

我已经研究这段代码一段时间了,终于完成了它,但是有什么方法可以压缩大量的 if 语句吗?

我已经尝试了我的编码知识范围内的一切,但似乎没有任何效果。

import java.util.Scanner;

public class AidanMRN{

public static void main(String[] args){

//Creating Variable "Number"
int number;

Scanner keyboard = new Scanner(System.in);

//Storing Number
System.out.println("Pick a number, 1 - 10");
number = keyboard.nextInt();

//If statements and Outputs
if (number > 10)
//Error message
System.out.print("Error, " + number + " is higher than 10.\nPlease try again");
if (number == 1)
System.out.println("Roman Numeral: I");

if (number == 2)
System.out.println("Roman Numeral: II");

if (number == 3)
System.out.println("Roman Numeral: III");

if (number == 4)
System.out.println("Roman Numeral: IV");

if (number == 5)
System.out.println("Roman Numeral: V");

if (number == 6)
System.out.println("Roman Numeral: VI");

if (number == 7)
System.out.println("Roman Numeral: VII");

if (number == 8)
System.out.println("Roman Numeral: VIII");

if (number == 9)
System.out.println("Roman Numeral: IX");

if (number == 10)
System.out.println("Roman Numeral: X");
}
}

最佳答案

你可以用这段代码有更短的 if 语句。

public static void main(String[] args) {
String[] romanNumbers= {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"};

int number;
Scanner keyboard = new Scanner(System.in);
//Storing Number
System.out.println("Pick a number, 1 - 10");
number = keyboard.nextInt();
//If statements and Outputs
if (number > 10 || number < 1)
//Error message
System.out.print("Error, " + number + " is higher than 10.\nPlease try again");
else
System.out.println("Roman Numeral: " + romanNumbers[number -1]);
}
}

关于java - 如何压缩这些大的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58504349/

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