1

I've looked all over for an answer that I understand about this question. I'm writing a program where a user inputs a number, and then the program prints out the number and if it is odd or even as well as if it's a multiple of 7.

I'm getting this error for these lines of code:

"Cannot make a static reference to the non-static method Method Name"

    getNum ();
    evenOdd ();
    multiple ();
    System.out.println(number1 + " : " + evenOdd + " : " + multipleOr);

This is what my code is:

import java.util.Scanner;

public class Multiples {

int number1;
String evenOdd;
String multipleOr;

public static void main(String[] args) {
    printMsg();
    System.out.println("Enter a number: ");
    getNum ();
    evenOdd ();
    multiple ();
    System.out.println(number1 + " : " + evenOdd + " : " + multipleOr);

}

public static void printMsg() {
    System.out.println("Welcome to the Multiplicity program.");
    System.out.println("Enter a number and I will tell you if it is a multiple of 7 and if it is odd or even.");
    return;
}

public int getNum() {
    Scanner input = new Scanner (System.in);
    number1 = input.nextInt();
    return number1;
}

public String evenOdd(){
    if (number1 / 2 == 0);
        evenOdd = "EVEN";
    if (number1 / 2 != 0);
        evenOdd = "ODD";
    return evenOdd;
}

public String multiple(){
    if (number1 / 7 == 0);
        multipleOr = "MULTIPLE";
    if (number1 / 7 != 0);
        multipleOr = "NOT";
    return multipleOr;
}
}

Really unsure of how to fix this issue. I tried putting "static" into all of the methods but then the variables were all messed up inside of them.

Note: It's supposed to print as "Number : Even : Multiple".

user2800912
  • 123
  • 1
  • 1
  • 7
  • 1
    If you declare a method as `static`, all the external `variable`s it uses should also be `static`. – Compass Nov 24 '14 at 19:43
  • 2
    One other approach you can think of, create instance of the class and invoke methods/operations on that instance. – kosa Nov 24 '14 at 19:44
  • `static` methods are shared among all objects, is this what you want? – Maroun Nov 24 '14 at 19:46

1 Answers1

0

Make your variables and methods static and that will fix your problem. Just make sure you understand the difference between static and non-static. Static variables and methods are shared by all objects (instances) of a particular class while non-static variables and methods are specific to each instance of a particular class. For what you are doing making your variables and methods all static is the correct thing to do. Or you could create your global variables in the main method as non-static variables and pass them to each method that needs them.

brso05
  • 13,142
  • 2
  • 21
  • 40