How do I take the user's input for how many legs are on the trip and have it loop that amount of times?
int counter = 0;
int gas = 0;
int legs = 1;
double miles = 0;
int mph= 0;
System.out.print("How many gallons of gas in you tank(Integer 1-20):");
gas = input.nextInt();
gas =gas;
System.out.print("How many legs on your trip?: ");
legs=input.nextInt();
for (int x = 0; x< legs ; legs );
{
System.out.printf("Enter leg %d distance(Miles): ",counter);
miles=input.nextDouble();
System.out.printf("Enter leg %d Speed(MPH): ",counter);
mph=input.nextInt();
CodePudding user response:
Include Scanner sc= new Scanner(System.in);
in your code to read input from the console. And use sc.nextInt()
to read inputs.
And remove ;
after for-loop
which is terminating the loop. And your trying to increament legs
in for-loop
instead of x
change it to for (int x = 0; x<legs ; x )
.
Here is the modified code which worked for me
int counter = 0;
int gas = 0;
int legs = 1;
double miles = 0;
int mph= 0;
Scanner sc= new Scanner(System.in);
System.out.print("How many gallons of gas in you tank(Integer 1-20):");
gas = sc.nextInt();
gas =gas;
System.out.print("How many legs on your trip?: ");
legs=sc.nextInt();
for (int x = 0; x<legs ; x )
{
System.out.printf("Enter leg %d distance(Miles): ",x);
miles=sc.nextDouble();
System.out.printf("Enter leg %d Speed(MPH): ",x);
mph=sc.nextInt();
}
CodePudding user response:
you must write : for(int x=0; x<legs;x ) not: for(int x=0; x<legs;legs ) this loop will be infinitive unless legs is negative number