Мне нужно создать программу, которая просит пользователя ввести, сколько грузовиков использует владелец сегодня, независимо от того, является ли грузовик «большим» или «маленьким», и в основном печатать вместимость грузовиков. У меня возникают проблемы с тем, что пользователь не вводит small или large после использования оператора else. Профессор хочет, чтобы мы попросили пользователя повторить попытку. Кроме того, я не понимаю, как распечатать результаты, особенно если пользователь вводит более двух грузовиков.
Вот мой код:
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(). Это считается плохой практикой. используйте логические флаги для управления потоком.
в-третьих, я предлагаю вам переформатировать ваш код с правильным отступом и использовать значимые имена переменных (например, для array и array1). Это поможет вам обнаружить ошибки и поможет нам разобраться в коде. Кроме того, разбейте код на логические блоки и поместите их в отдельные методы. Например, один метод имеет дело с вводом данных пользователем, другой проверяет его, третий - для вычислений, а последний - для отображения результата.
Я обнаружил еще несколько проблем, вы можете попробовать
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 totalTrucks = input.nextInt();
if (totalTrucks < 2) {
System.out.println("You entered a value less than 2 for number of trucks.");
System.out.println("Terminating program. ");
System.exit(0);
} else {
HashMap<Integer, Double> smallTrucks = new HashMap();
HashMap<Integer, Double> largeTrucks = new HashMap();
for (int i = 0; i < totalTrucks; i++) {
System.out.println("What is the size of truck " + (i + 1) + "(large trucks max crates = 100, small trucks max crates = 10)? ");
String truckSize = input.next();
boolean repeatLoop = true;
while (repeatLoop) {
if (truckSize.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)? ");
Double crates = input.nextDouble();
largeTrucks.put(i, crates);
repeatLoop = false;
} else if (truckSize.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)? ");
boolean sizeWrong=true;
while (sizeWrong) {
Double crates = input.nextDouble();
if (crates > 10) {
System.out.println("Small Truck max crates is 10,Please enter size again ");
repeatLoop = true;
continue;
}
sizeWrong=false;
smallTrucks.put(i, crates);
}
repeatLoop = false;
} else {
System.out.println("Enter either large or small: ");
}
}
}
System.out.println("**Entry for all trucks completed**");
for (int i = 0; i < totalTrucks; i++) {
Double maxTruckSize = smallTrucks.get(i);
if (maxTruckSize != null) {
System.out.println("Truck " + (i + 1) + " max: 100 actual: " + maxTruckSize + " capacity at: " + maxTruckSize / 100 + "%");
}else
System.out.println("Truck " + (i + 1) + " max: 10 actual: " + smallTrucks.get(i)+ " capacity at: " + maxTruckSize / 10 + "%");
}
}
}
Сначала исправьте несколько ошибок, а затем переместите truck = input.next () внутрь while.
Я исправил ваш код и добавил вывод работающей программы. Но если вы придерживаетесь массива, вы печатаете 0, если массив не заполнен входными данными. Так что я не трогаю туда. Я предлагаю вам использовать ArrayList вместо массива. Таким образом, вы можете перебирать только существующие элементы.
Нормальный расход:
How many trucks are operating today (Number of trucks must be 2 or greater)? :
2
What is the size of truck 1(large trucks max crates = 100, small trucks max crates = 10)?
large
What is the actual number of crates that truck 1 is hauling today (Truck 1 max crates is 100)?
50
What is the size of truck 2(large trucks max crates = 100, small trucks max crates = 10)?
small
What is the actual number of crates that truck 2 is hauling today (Truck 2 max crates is 10)?
20
**Entry for all trucks completed**
Truck 1 max: 100 actual: 50.0 capacity at: 0.5%
Truck 2 max: 10 actual: 20.0 capacity at: 0.0%
Если пользователь вводит значение, отличное от «большего» или «маленького», он повторяет попытку:
How many trucks are operating today (Number of trucks must be 2 or greater)? :
2
What is the size of truck 1(large trucks max crates = 100, small trucks max crates = 10)?
xxx
Enter either large or small:
What is the size of truck 1(large trucks max crates = 100, small trucks max crates = 10)?
large
What is the actual number of crates that truck 1 is hauling today (Truck 1 max crates is 100)?
50
What is the size of truck 2(large trucks max crates = 100, small trucks max crates = 10)?
small
What is the actual number of crates that truck 2 is hauling today (Truck 2 max crates is 10)?
20
**Entry for all trucks completed**
Truck 1 max: 100 actual: 50.0 capacity at: 0.5%
Truck 2 max: 10 actual: 20.0 capacity at: 0.0%
Решение :
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++ ) {
boolean ok = false;
while(!ok) {
System.out.println("What is the size of truck " + (i+1) + "(large trucks max crates = 100, small trucks max crates = 10)? ");
truck = input.next();
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();
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();
ok = true;
array1[i] = (crates1/10)*100;
}
else {
System.out.println("Enter either large or small: ");
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(!true) никогда не будет выполняться. И вам нужно объявить boolean ok вне цикла while. В этом коде все еще есть логическая ошибка. Но поскольку это ваше задание в классе, попробуйте решить остальное самостоятельно.
boolean ok = false;
while (!ok) {
truck = input.next();
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();
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();
ok = true;
array1[i] = (crates1 / 10) * 100;
} else {
System.out.println("Enter either large or small: ");
}
}