询问用户想要循环多少次的程序(java)



//在 eclipse 中创建一个完整的程序,它会询问用户你想循环多长时间。它将在 for 循环中询问双精度值的速率和整数值的时间。它将计算您在汇率和时间中输入的每个时间的距离。

如果我只想输入一次,我当前的输出给了我正确的答案,因为它只需要运行一次程序。每当我输入超过 1 时,它就会开始表现得很奇怪,这是我解释它的最好方法,因为我不知道它有什么问题。

这是一个随机输出

How many times would you like to calculate the distance.
12
Enter rate
2
Enter time
13
The distance is 26.0
Enter rate
12
Enter time
12
The distance is 144.0
How many times would you like to calculate the distance.
1
Enter rate
12
Enter time
1
The distance is 12.0

我的实际代码

import java.util.Scanner;
 public class NTC {
 public static void main(String[] args){
Scanner kb=new Scanner(System.in);
    int loop = 10;
    double rate=0;
    int time=0;
    int count;
    double distance = rate*time;
 for (count = 0; count <= loop; count++) {
 System.out.println("How many times would you like to calculate the distance.");
 loop = kb.nextInt(); 

for(rate=0; rate <loop;rate++)
{
System.out.println("Enter rate");
rate = kb.nextDouble();
for(time=0; time <loop;time++)
{
     System.out.println("Enter time");
    time = kb.nextInt();
 System.out.println("The distance is "+rate*time);
}

你只需要有一个for循环:

import java.util.Scanner;
public class NTC 
{
public static void main(String[] args)
{
Scanner kb=new Scanner(System.in);
int loop = 10;
double rate=0;
int time=0;
int count;
double distance = rate*time;
System.out.println("How many times would you like to calculate the distance.");
loop = kb.nextInt(); 
for (count = 0; count < loop; count++) 
{    
 System.out.println("Enter rate");
 rate = kb.nextDouble();
 System.out.println("Enter time");
 time = kb.nextInt();
 System.out.println("The distance is "+(rate*time));
}
}
}

最新更新