Why do I need the static keyword here? [duplicate] - java

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.

Related

why i am getting java.util.NoSuchElementException error in Scanner [duplicate]

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
}

Why am I getting this error? non-static variable randomNumbers cannot be referenced from a static context [duplicate]

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();
^^^^^^^^^^^^^^^^^^^^^^^
}
}

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().

Java program to ask user for basic input and to return a value [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am writing a Java program to decide how much a user has to pay for a delivery charge for a school project. I have been advised the method that works out the cost has to be static. When i de-bug my code the value of the price is never changing and i don't know why, please see my code below.
main method
package questionOne;
import java.util.Scanner;
import questionOne.DeliveryMenu;
public class DeliveryMenuDemo {
public static void main(String[] args)
throws java.io.IOException {
String choice;
DeliveryMenu d = new DeliveryMenu();
System.out.println("Enter the type of Delivery service needed (Standard/Super/WowWee)?");
Scanner scanner = new Scanner(System.in);
choice = scanner.next();
d.setDeliveryCost(choice);
d.getPrice();
}
}
and class with other methods
package questionOne;
public class DeliveryMenu {
private static String delivery;
private static int price=0;
public static int setDeliveryCost(String choice) {
if(delivery == "Standard") {
price = price + 22;
} else if (delivery == "Super") {
price = price + 44;
} else if (delivery == "wow-wee") {
price = price + 60;
}
return price;
}
public String setDelivery(String s) {
return delivery=s;
}
public void getPrice() {
System.out.println(price);
}
}
price is never changing to the desired amount.
For comparing Strings you need to use String method equals.
(delivery.equals("Standard")) or (delivery.equalsIgnoreCase("Standard")) instead of (delivery == "Standard")

using static boolean method [duplicate]

This question already has an answer here:
Primitives/Objects Declaration, default initialization values
(1 answer)
Closed 7 years ago.
My code:
import java.util.Scanner;
public class MonthMapper{
static String month;
static int month_num;
public static boolean isMonthNumber (String str) {
month = str;
month_num = Integer.parseInt(month);
return (month_num >= 0 && month_num < 12);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Month: ");
month = sc.next();
System.out.println (isMonthNumber (Integer.toString(month_num)));
}
}
I have to write a static class method boolean isMonthNumber(String str) that takes a String as an input and returns boolean value. The method returns True if the input string represents an integer value between 1 and 12, otherwise the method returns should return False.
Currently for some reason my program always returns true even when i enter a value greater than 12.
You pass mounth_num variable to a method, but the month variable has the read value.
Replace with this:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Month: ");
System.out.println(isMonthNumber (sc.next()));
}

Categories