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().
Related
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 2 years ago.
import java.util.Scanner;
public class Info {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n1,n2;
System.out.print("Enter n1: ");
n1 = input.nextInt();
System.out.print("Enter n2: ");
n2 = input.nextInt();
System.out.println(sumTotal(n1,n2));
}
public static int sumTotal(int n1sum, int n2sum) { // *why static includes here*
return n1sum+n2sum;
}
}
I don't understand why do I need to put static in here?
Some other codes with return statement doesn't need static, like this one. So why?
public class FirstProgram {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in); // for scanning
int age;
System.out.println("Enter your age");
age = userInput.nextInt();
var a = new FirstProgram();
a.userAge(age);
}
public int userAge(int age1)
{
if ( age1 < 18 )
{
System.out.println("You are a YOUNG!");
}
else if (age1 > 18 && age1 <=25)
{
System.out.println("Young adult! ");
}
else
{
System.out.println("Wise!");
}
return age1;
}
}
I don't understand why do I need to put static in here.
Java does not allow calling non-static method from a static method directly.
Some other codes with return statement doesn't need static, like this
one. so whyy?
This is how (i.e. using the instance of the class) Java allows you to call a non-static method from a static method.
Learn more about static keyword here.
This question already has answers here:
Java Multiple Scanners
(3 answers)
Closed 3 years ago.
I am trying to read input in main function as well as different functions, for that, I am creating two different Scanner and it is giving me an error but if I take input only in main function and pass the value in the different function it does not gives error then, what I am missing here?. I am a beginner in java.
import java.util.Scanner;
public class abc{
public static void fun(){
Scanner read = new Scanner(System.in);
int a,b,c;
a=read.nextInt();
b=read.nextInt();
c=read.nextInt();
// some code
}
public static void main(String[] args){
Scanner read=new Scanner(System.in);
int t=read.nextInt();
while(t>0){
fun();
t--;
}
}
}
Why do you just don't do like this:-
import java.util.Scanner;
public class abc{
public static void fun(int a, int b, int c){
Scanner read = new Scanner(System.in);
// some code
}
public static void main(String[] args){
Scanner read=new Scanner(System.in);
int t=read.nextInt();
Object o = new Object();
int a, b, c;
while(t>0){
a=read.nextInt();
b=read.nextInt();
c=read.nextInt();
ob.fun(a, b, c);
t--;
}
}
}
This will probably give you no error. If you don't want to do this, you can simply declare the Scanner object in the class and not in a method and try to use it.
I do not think it correct to create two Scanner for the same System.in. Why don't use the single one:
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int t = scan.nextInt();
while (t > 0) {
fun(scan);
t--;
}
}
}
public static void fun(Scanner scan) {
int a, b, c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
// some code
}
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
I know that there are many questions like this one but it didn't really help me out any. I have to Write a program that will help an elementary school student learn multiplication. Use a SecureRandom object to produce two positive one-digit integers. The program should then prompt the user with a question, such as "How much is 6 times 7?" I have done the hard part but I can not get my variables that is in my class to work for the other methods. i will "get non-static variable randomNumbers cannot be referenced from a static context" error! can someone help me please!!
import java.util.Random;
import java.util.Scanner;
public class computerAssistedInstruction {
Random randomNumbers = new Random();
int answer;// the right answer
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int input;// the user answer
newQuestion();
input = scnr.nextInt();
if (input != answer) {
System.out.println("No. Please try again.");
}// end of if
else {
System.out.print("Very Good!");
newQuestion();
}// end of else
}// end of main
public static void newQuestion() {
int number1 = randomNumbers.nextInt(10);
int number2 = randomNumbers.nextInt(10);
answer = number1 * number2;
System.out.printf("How much is %d times %d?", number1, number2);
}// end of newQuestion
}// end of class
Problem
The error is
non-static variable randomNumbers cannot be referenced from a static context
which means that since you declared randomNumbers like this
public class computerAssistedInstruction {
Random randomNumbers = new Random();
int answer;
}
you cannot use it (or answer) in your static method
public static void newQuestion() {
...
}
Solution
Either make randomNumbers and answer static variables, or make newQuestion an instance method (i.e. not static) like so:
public class computerAssistedInstruction {
Random randomNumbers = new Random();
int answer;
...
public void newQuestion() {
...
}
}
Now, you need to edit your main method a little since you cannot call the non-static method without an instance of the class anymore. So, instead of
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int input;
newQuestion();
input = scnr.nextInt();
if (input != answer) {
System.out.println("No. Please try again.");
}
else {
System.out.print("Very Good!");
newQuestion();
}
}
you would now need this:
public static void main(String[] args) {
computerAssistedInstruction instance = new computerAssistedInstruction(); // Create an instance of the class here.
Scanner scnr = new Scanner(System.in);
int input;
instance.newQuestion(); // Call newQuestion() on the instance.
^^^^^^^^^^^^^^^^^^^^^^^
input = scnr.nextInt();
if (input != answer) {
System.out.println("No. Please try again.");
}
else {
System.out.print("Very Good!");
instance.newQuestion();
^^^^^^^^^^^^^^^^^^^^^^^
}
}
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();
}
}
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