Reputation: 327
I am trying to write a program which will keep asking a user for an integer until they input a value which isn't an integer, at which point the program stops.
Here is what I have so far:
import java.util.Scanner;
import java.util.ArrayList;
public class InputStats {
private static Scanner a;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList InputArray = new ArrayList();
Boolean Running = true;
System.out.println("Please type an integer. To stop enter a non integer value");
while (Running) {
a = Scanner.nextLine();
if (!a.hasNextInt()) {
Running = false;
}
else {
InputArray.add(input.nextLine());
}
System.out.println(InputArray);
}
}
}
However, with this code I am recieving the errors:
error: non-static method nextLine() cannot be referenced from a static context (for the line a = Scanner.nextLine();)
and
error: incompatible types (for the line a = Scanner.nextLine();)
What could be the issue?
Upvotes: 3
Views: 230
Reputation: 1
I accomplished this by creating a function to see if a String is numeric or not.
import java.util.ArrayList;
import java.util.Scanner;
public class InputStats {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> inputArray = new ArrayList<Integer>();
System.out.println("Please type an integer. To stop enter a non integer value");
boolean canContinue = true;
String a;
while(canContinue) {
a = input.next();
if(isNumeric(a) == true) {
int b= Integer.parseInt(a);
inputArray.add(b);
}
else {
canContinue = false;
}
}
System.out.println(inputArray);
input.close();
}
public static boolean isNumeric(String str) {
try {
int d = Integer.parseInt(str);
}
catch(NumberFormatException nfe) {
return false;
}
return true;
}
}
Upvotes: 0
Reputation: 5755
String str = input.nextLine();
You don't need Scanner a at all. Just replace all the references to it with references to input
.
Upvotes: 7