gpt4 book ai didi

java - 数组和打印语句/java

转载 作者:行者123 更新时间:2023-12-01 19:49:33 25 4
gpt4 key购买 nike

我需要制作一个程序,要求用户输入车主今天使用了多少辆卡车,卡车是“大”还是“小”,并基本上打印卡车的容量。如果用户在使用 else 语句后没有输入小或大,我会遇到问题。教授希望我们要求用户重试。另外,我对如何打印结果感到困惑,特别是当用户输入超过 2 辆卡车时。

这是我的代码:

import java.util.Arrays;
import java.util.Scanner;

public class TomTrucking {


/*
* Complete here if you are using class variables
*/

public static void main(String[]args){

Scanner input = new Scanner(System.in);

System.out.println("How many trucks are operating today (Number of trucks must be 2 or greater)? :");
int t1 = input.nextInt();


if(t1 < 2) {
System.out.println("You entered a value less than 2 for number of trucks.");
System.out.println("Terminating program. ");
System.exit(0);
}else {
double crates = 0;
double crates1 = 0;

String truck;
int i=0;

double array[] = new double[t1];
double array1[] = new double[t1];
for( i = 0; i < array.length; i++ ) {

System.out.println("What is the size of truck " + (i+1) + "(large trucks max crates = 100, small trucks max crates = 10)? ");
truck = input.next();

while(!true) {
if(truck.equals("large")) {
System.out.println("What is the actual number of crates that truck " + (i+1) + " is hauling today (Truck 1 max crates is 100)? ");
crates = input.nextDouble();

boolean ok = true;
array[i] = (crates/100);


}else if(truck.equals("small")){
System.out.println("What is the actual number of crates that truck " + (i+1) + " is hauling today (Truck 2 max crates is 10)? ");
crates1 = input.nextDouble();

boolean ok = true;
array1[i] = (crates1/10)*100;


}else {
System.out.println("Enter either large or small: ");

boolean ok = false;


}
}




System.out.println("**Entry for all trucks completed**");




System.out.println("Truck " + (i-1) + " max: 100 actual: " + crates + " capacity at: " + (array[i-2]) + "%");
System.out.println("Truck " + (i) + " max: 10 actual: " + crates1 + " capacity at: " + (array1[i-2]) + "%");

}
}
}
}

最佳答案

首先,while循环的条件是

while(!true) {

这意味着循环内的代码永远不会被处理。你可能是说

while(!ok) {

这意味着您必须在循环之外声明ok

第二,不要使用System.exit()。这被认为是不好的做法。使用 boolean 标志来控制流程。

第三,我建议您使用适当的缩进重新格式化代码并使用有意义的变量名称(例如 arrayarray1)。这将帮助您发现错误并帮助我们理解代码。另外,将代码分解为逻辑单元并将它们放入单独的方法中。例如,一种方法处理用户输入,另一种方法验证用户输入,另一种方法用于计算,最后一种方法显示结果。

关于java - 数组和打印语句/java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916832/

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