Getting error while using .nextInt() - java

I am getting this error: "cannot make a static reference to the nonstatic field" everytime I try to execute a line of code with .nextInt() in it.
Here are the lines of code that could affect (that I can think of):
private Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();

This is most likely because you're trying to access input in a static method, which I'm assuming it to be the main() method. Something like this
private Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt(); // This is not allowed as input is not static
You need to either make your input as static or may be move it inside the static(main) method.
Solution1: Make the input as static.
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt();
Solution2: Move the input inside the main(note that you can't use input in any other methods, if its moved inside the main(), as it'll be local to it).
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();

private Scanner input = new Scanner(System.in); // make this static
If you accessing this inside static method. you have to make input static.
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt();
// without static you will get that error.
}

This is because of the way you are defining input
private Scanner input = new Scanner(System.in); // notice private
int priceLocation = input.nextInt();
Private variables are defined in the class, outside methods like
class myclass{
private Scanner input = new Scanner(System.in);
void methodname(){
int priceLocation = input.nextInt();
}
}
Or if you want to define input inside the method
class myclass{
void methodname(){
Scanner input = new Scanner(System.in); // you can make this a final variable if you want
int priceLocation = input.nextInt();
}
}

Related

Scanner as parameter and convert to int? (JAVA)

I have a trouble about usage of the scanner.
The getUserInput takes as an input the scanner instance and initialise the array of specified size which comes from the scanner. For example: if user puts 3 then the method will create an array of the size 3.
However, it keeps saying that scnr can't converted to int....
Any advice?
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.println("How many orders were placed Saturday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Sunday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Monday?");
int [] userInput = getUserInput(scnr)
return;
}
}
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr];
return userInput;
}
You have to call a method on Scanner. And because you want an int do it like this:
int[] userInput = new int[scnr.nextInt()];
Here you'll find the API documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
nextInt() method of Java Scanner class is used to scan the next token of the input as an int
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
Firstly there are 2 mistakes you have done here.
int [] userInput there are 2 duplicates of this userInput variable.
You are passing an instance of Scanner as a parameter in your getUserInput function.
getUserInput FIX
So in order to create we need to follow a syntax i.e
datatype [] vairable_name = new datatype[size];
Here size can be byte short int but what you did is
datatype [] vairable_name = new datatype[Scanner];
Which is just not the Syntax. You can fix it by taking input as int from the user.
A scanner as a method to do that .nextInt() which converts the input of the user to int if it's in numbers.
Solution is
int[] userInput = new int[scnr.nextInt()];
// This is like the syntax
datatype [] vairable_name = new datatype[Scanner];
Duplicate Variable
You should revise scopes in java, and then you will know why it's an error.
You cannot have the same variable name in the same scope or in the child scope
public static void main(String args[]){
int a = 0;
int a = 1; // <- error cuz a is already difined and is duplicate in the same scope.
}
Similarly
public static void main(String args[]){
int a = 0;
if(true){
int a = 1; // <- error cuz a is already difined and is duplicate in child scope.
}
}
The solution is to change the variable name.
//scnr is now globally available in the class so need to pass it as a parameter
Scanner scnr = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("How many orders were placed Saturday?");
int [] saturdayUserInput = getUserInput();
System.out.println("How many orders were placed Sunday?");
int [] sundayUserInput = getUserInput();
System.out.println("How many orders were placed Monday?");
int [] mondayUserInput = getUserInput()
return;
}
}
public static int[] getUserInput()
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
scnr is not an int. It's an isntance of the Scanner class. If you want to read an int from it, you'll need to call:
scnr.nextInt();
It's also better not to pass this as a parameter, but to create the Scanner on class level, so you can use it in all the methods.

What there is no resource leak when Scanner variable declared in class data field?

When I do write this:
import java.util.*;
public class Test {
// static Scanner input = new Scanner(System.in);
static double y;
public static void main(String[] args) {
double x = someMethod(5);
}
private static double someMethod(int nr) {
Scanner input = new Scanner(System.in);
try {
y = input.nextDouble();
} catch (InputMismatchException e) {System.out.println("Type in a double");}
return y + nr;
}
}
I get "resource leak" error message.
But when I do write this:
import java.util.*;
public class Test {
static Scanner input = new Scanner(System.in);
static double y;
public static void main(String[] args) {
double x = someMethod(5);
}
private static double someMethod(int nr) {
try {
y = input.nextDouble();
} catch (InputMismatchException e) {System.out.println("Type in a double");}
return y + nr;
}
}
It just does work. Why is there no resource leak when I define input Scanner on the class data field?
What is the difference between declaring a variable on the data field vs in a method?
When you have Scanner input = new Scanner(System.in); in the method, you're creating a new Scanner instance every time the method is called, and you only use it once. This creates garbage because now you will have a new Scanner which isn't being used anymore every time you use the method.
If you instantiate the Scanner in the class instead, you create it once and re-use it, preventing your program from having garbage.

Java - how to use variables in static methods [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
I can't figure out how to use variables when methods are static (which "main" has to be?). Here is an example:
import java.util.Scanner;
public class Yatzy {
Scanner input = new Scanner(System.in);
protected static int reply;
public static void main(String[] args){
startGame();
}
public static void startGame(){
System.out.println("How many players? 1 - 3.");
reply = input.nextInt(); // Option 1: class variable
int userinput = input.nextInt(); // Option 2: instance variable
}
}
No matter which way I try, I keep getting this error:
Error: non-static variable input cannot be referenced from a static context
How can I use user inputs (or more generally, variables) within static methods?
The error message is clear, and this is a fundamental as well as a very basic concept in java. You are trying to refer to a variable within the static area, so you should create that variable in the static area.
static Scanner input = new Scanner(System.in);
will do the trick.
Using Static variables and methods
import java.util.Scanner;
public class Yatzy {
static Scanner input = new Scanner(System.in);
static int reply;
public static void main(String[] args){
startGame();
}
public static void startGame(){
System.out.println("How many players? 1 - 3.");
reply = input.nextInt();
int userinput = input.nextInt();
}
}
In the above example, all methods and variables are in the static area.
Using Instance variables and methods
import java.util.Scanner;
public class Yatzy {
Scanner input = new Scanner(System.in);
int reply;
public static void main(String[] args){
new Yatzy().startGame();
}
public void startGame(){
System.out.println("How many players? 1 - 3.");
reply = input.nextInt();
int userinput = input.nextInt();
}
}
Create a new object of your class in the main method and call startGame().

error: non-static variable scan cannot be referenced from a static context in Java

import java.util.Scanner;
public class CHP4Ex
{
Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
Why am I getting this error? I'm basically writing a while loop that prints all positive numbers that are divisible by 10 and less than n. For example, if n is 100, enter 10 ... 90.
Put the Scanner class object inside the main function. Basically the problem is that your code violates the static feature. You cannot use non-static members inside a static function, main being static in your case. So it should be :
import java.util.Scanner;
public class CHP4Ex
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
You can't refer to non static variable in static context, so change
Scanner scan = new Scanner(System.in);
to
private static Scanner scan = new Scanner(System.in); It should work

Beginner Java static scope error

(For a beginner Java class)
The assignment specifies that i only make one Scanner instance, and I need it in more than one method, so i declared it outside of main. I declare an array and try to equate it with a method call, initialCash(), like I would in Python. The problem is if I make the initialCash method static, I can't use Scanner. If initialCash() isn't static, Eclipse is kind enough to tell me that it "cannot make a static reference to the non-static method." (in the money = initialCash(); line)
How do I get around this?
package proj1;
import java.util.Scanner;
public class Project1
{
Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
int[] money = new int[4];
money = initialCash();
}
public int[] initialCash()
{
int[] initialMoney = new int[4];
while(true)
{
System.out.print("Ones: ");
initialMoney[0] = scanner.nextInt();
System.out.print("Fives: ");
initialMoney[1] = scanner.nextInt();
System.out.print("Tens: ");
initialMoney[2] = scanner.nextInt();
System.out.print("Twenties: ");
initialMoney[3] = scanner.nextInt();
if((initialMoney[0]>=0)&&(initialMoney[1]>=0)&&(initialMoney[2]>=0)&&(initialMoney[3]>0))
{
return initialMoney;
}
else
{
System.out.println("One or more invalid denominations. Try again.");
}
}
}
}
Create an instance of your class and invoke initialCash on that instance from main.
money = new Project1().initialCash();
What PermGenError said would definitely work, or you could make both the initalCash() method and the scanner reference variable static.
In your code, the line
Scanner scanner = new Scanner(System.in);
creates a new Scanner object each time you create an object of type Project1. Whereas if you had written it as
static Scanner scanner = new Scanner(System.in);
It would create a single Scanner instance for use by all classes that refer to this object. In your question you mentioned there has to be exactly one Scanner object, if so this is the way to go.
If you use
money = new Project1().initialCash();
you are creating a new Project1 object as well as a new Scanner object, if you were to reuse the Scanner object by calling another function you cannot as it is tied to that specific instance of Project1, so I'd recommend you make it static, the same with the initialCash function, it is tied to that object instance.
Make the Scanner and the initialMoney method static. This should fix your problem.
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
int[] money = new int[4];
money = initialCash();
}
public static int[] initialCash()
{
int[] initialMoney = new int[4];
while(true)
{
System.out.print("Ones: ");
initialMoney[0] = scanner.nextInt();
System.out.print("Fives: ");
initialMoney[1] = scanner.nextInt();
System.out.print("Tens: ");
initialMoney[2] = scanner.nextInt();
System.out.print("Twenties: ");
initialMoney[3] = scanner.nextInt();
if((initialMoney[0]>=0)&&(initialMoney[1]>=0)&&(initialMoney[2]>=0)&&(initialMoney[3]>0))
{
return initialMoney;
}
else
{
System.out.println("One or more invalid denominations. Try again.");
}
}
}

Categories