请帮我优化代码 class setbox { static int number11; static int number12; static int number13; static int number14; Scanner h = new Scanner(System.in); static int setbox1() { //设置总量 Scanner h = new Scanner(System.in); int number11 = h.nextInt(); if (number11 < 3) { System.out.println("输入错误"); System.out.println("输入的数量应该>=3"); } return number11; } static int setbox2() { //设置一等奖的个数 Scanner h = new Scanner(System.in); int number12 = h.nextInt(); if (number12 <= number11) { System.out.println("输入错误"); System.out.println("数量多于总量"); } return number12; } static int setbox3() { Scanner h = new Scanner(System.in); int number13 = h.nextInt(); if (number13 <= number11 - number12) { System.out.println("输入错误"); System.out.println("数量多于总量"); } return number13; } static int setbox4() { Scanner h = new Scanner(System.in); int number14 = h.nextInt(); if (number14 <= number11 - number12 - number13) { System.out.println("输入错误"); System.out.println("数量多于总量"); } return number14; } } }
时间: 2023-03-31 19:02:34 浏览: 66
我可以帮你优化代码。这段代码中有一些重复的部分,可以将 Scanner 对象和输入语句提取出来,避免重复输入。同时,可以将输入错误的提示信息提取出来,避免重复输出。以下是优化后的代码:
import java.util.Scanner;
class setbox {
static int number11;
static int number12;
static int number13;
static int number14;
static Scanner h = new Scanner(System.in);
static String inputError = "输入错误,数量多于总量";
static int setbox1() { //设置总量
int number11 = h.nextInt();
if (number11 < 3) {
System.out.println("输入错误,输入的数量应该>=3");
}
return number11;
}
static int setbox2() { //设置一等奖的个数
int number12 = h.nextInt();
if (number12 <= number11) {
System.out.println(inputError);
}
return number12;
}
static int setbox3() {
int number13 = h.nextInt();
if (number13 <= number11 - number12) {
System.out.println(inputError);
}
return number13;
}
static int setbox4() {
int number14 = h.nextInt();
if (number14 <= number11 - number12 - number13) {
System.out.println(inputError);
}
return number14;
}
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)