Reputation: 654
I am trying to write a small program dealing the earthquakes and magnitudes.
When the program is run, it asks the user to input a number for how many earthquakes the user wants to submit magnitudes for. Depending on the response, the program then prompts the user to enter a magnitude for each earthquake. I have written the following code below but am having trouble with the for loop
.
Obviously in the for loop, putting i <= numberOfEarthquakes
disallows the program from compiling correctly. What is a simple way to give i
a condition that correlates to the inputted number from the user. Much thanks.
(this is a smaller part of a larger program that I am hoping to write)
import java.util.*;
public class Earthquakes {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many magnitudes will you enter? ");
String numberOfEarthquakes = console.next();
for (int i = 1; i <= numberOfEarthquakes; i++) {
System.out.print("Enter magnitude for earthquake " + i);
String magnitudeOfEarthquake = console.next();
}
}
}
Upvotes: 0
Views: 97
Reputation: 1984
Convert your numberOfEarthquakes
from String to Integer. Use Integer.parseInt(numberOfEarthquakes)
to convert String to Intger.
Upvotes: 0
Reputation: 5837
Make this String numberOfEarthquakes = console.next();
to int numberOfEarthquakes = console.nextInt();
You can not compare String
with int
.
Upvotes: 5