英文:
How do I create a for loop where i = 0
问题
以下是翻译好的代码部分:
System.out.print("输入旅行次数:");
carSample.numberOfTrips = input.nextInt();
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("没有旅行");
}
int previous = 0;
int minimumTrip = Integer.MAX_VALUE;
int maximumTrip = Integer.MIN_VALUE;
System.out.print("里程表读数 0:");
carSample.odometerReading = input.nextInt();
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("里程表读数 " + (i + 1) + ":");
int odometerReading = input.nextInt();
int currentTrip = odometerReading - previous;
if (currentTrip > maximumTrip) {
maximumTrip = currentTrip;
}
if (currentTrip < minimumTrip) {
minimumTrip = currentTrip;
}
previous = odometerReading;
}
英文:
I'm a beginner at java and I'm facing a very basic problem that I just can't seem to figure out. Any insight or feedback will be greatly appreciated.
My program takes user input of the number of trips a car has undergone, and each odometer reading between each trip then calculates the longest, shortest and average distance traveled between each trip.
So far, it works OK besides when there is a test case where the user inputs 0 number of trips, which should output 0 for all calculations (shortest, longest average) but i get the max integer value for each output (2 billion).
I've tried to create a loop that accepts if the number of trips does = 0, then a message is outputted "there is no trips" however I keep receiving this error:
> TestCar.java:20: error: incompatible types: int cannot be converted to Boolean
> for (int i = 0; i = carSample.numberOfTrips; i++) {
Any help would be greatly appreciated, thank you for your time.
Here is my code:
System.out.print("Input trips: ");
carSample.numberOfTrips = input.nextInt();
for (int i = 0; i = carSample.numberOfTrips; i++) {
System.out.print("There are no trips");
}
int previous = 0;
int minimumTrip = Integer.MAX_VALUE;
int maximumTrip = Integer.MIN_VALUE;
System.out.print("Odometer reading 0: " );
carSample.odometerReading = input.nextInt();
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
int odometerReading = input.nextInt();
int currentTrip = odometerReading - previous;
if (currentTrip > maximumTrip){
maximumTrip = currentTrip;
}
if (currentTrip < minimumTrip){
minimumTrip = currentTrip;
}
previous = odometerReading;
答案1
得分: 1
这只是根据用户输入进行分支的简单问题。没有理由执行零次 for
循环。以下是其背后的逻辑(您可以自己编写实际代码):
如果 numTrips == 0
打印错误消息
否则
对于每次 numTrips
在这里编写所有逻辑
结束对于
结束否则
英文:
It's a simple matter of branching based on user input. There's no reason to run a for
loop zero times. Here's the logic behind it (you can write the actual code yourself):
if numTrips == 0
print error message
else
for numTrips
blah blah all your logic goes here
end for
end else
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论