我的代码编译正确。当我运行我的程序时,输出要求我输入包的重量。如果我输入一个负数,程序会要求我再次输入重量,但不会停止让我输入另一个数字。
我认为问题出在"而#34;声明,但我不确定。
任何帮助都将不胜感激。
import java.util.Scanner;
public class dcrawford_Shipping
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
int weight, distance, distancex;
double rate, price;
rate = 0.00;
System.out.print("Please enter package weight: ");
weight = input.nextInt();
while (weight <= 0 || weight >= 61)
{
System.out.print("Please enter package weight: ");
}
if (weight <= 10 && weight >= 1 )
{
rate = 5.01;
}
else if ( weight <= 20 && weight >= 11 )
{
rate = 7.02;
}
else if ( weight <= 30 && weight >= 21 )
{
rate = 9.03;
}
else if ( weight <= 40 && weight >= 31 )
{
rate = 11.04;
}
else if ( weight <= 60 && weight >= 41)
{
rate = 15.00;
}
System.out.print("Please enter distance: ");
distance = input.nextInt();
while ( distance <= 0 )
{
System.out.print("Please enter distance: ");
}
distancex = ( distance / 100 ) + 1;
price = ( distancex * rate );
System.out.printf("Your total shipping cost for %d miles is $%.2f\n", distance, price);
}
}
答案 0 :(得分:4)
您需要让用户在while循环内再次输入重量。
while (weight <= 0 || weight >= 61) {
System.out.print("Please enter package weight: ");
weight = input.nextInt();
}
你也可以使用do-while循环:
do {
System.out.print("Please enter package weight: ");
weight = input.nextInt();
} while (weight <= 0 || weight >= 61);
如果你使用do-while循环,你可以在第一次询问和while循环时删除。这是一种稍微紧凑的方式。