'How do I take the users input and have the program loop that many times for a for loop? [closed]
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();
Solution 1:[1]
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 increment 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();
}
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
| Solution 2 | Erkinoff Mohamed Ayyub |
