Static reference to the non-static method (In main method) [duplicate] - java

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
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".

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.

Related

How do I call these methods? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I'm new to Java, and I'm trying to call the private methods I've set up earlier, but with no success. It's a simple program that generates random numbers and display messages. Anyone wants to lend a hand?
Sorry if the code is bad, I've only been learning this for less than month.
import java.util.Random;
import java.util.Scanner;
public class project2 {
private static int rollDie() {
int num_random2 = (int) (Math.random() * 6) + 1;
System.out.println("Die 2: " + num_random2);
return num_random2;
}
private static int rollDie2() {
int num_random = (int) (Math.random() * 6) + 1;
System.out.println("Die 1: " + num_random);
return num_random;
}
private static void printDice(int num_random, int num_random2) {
total = num_random + num_random2;
System.out.println("Total: " + total);
}
int total = num_random + num_random2;
private static void printSpecialMessage(int total) {
String message1 = "Snake Eyes";
String message2 = "Box cars";
if (total = 12) {
System.out.println(message2);
} else if (total = 2) {
System.out.println(message1);
} else {
break;
}
}
public static void main(String[] args) {
System.out.println("Welcome to my app!");
System.out.println();
System.out.println("Dice Roller");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do {
rollDie();
rollDie2();
printDice();
printSpecialMessage();
System.out.print("Roll Again? (y/n): ");
choice = sc.next();
System.out.println();
}
while (choice.equalsIgnoreCase("y"));
}
}
I keep getting these errors:
The method printDice(int, int) in the type project2 is not applicable for the arguments ()
The method printSpecialMessage(int) in the type project2 is not applicable for the arguments ()
at project2.main(project2.java:51)
At this point I'm about to just give up. Hopefully someone can help me out!
Few errors in your code I found.
if (total = 12) should be replaced with if (total == 12).
Make sure you always use two equals in if condition. One = is for assignment and two = for condition check.
printDice() -> The signature is not matching. Pass two values to this function.
total should be declared as static.
printSpecialMessage -> The signature is not matching. Pass one values to this function.
I suggest you start with writing simple code and then gradually go ahead with writing complex codes.
Your code does not compile. The following code does. Compare it with your code.
import java.util.Scanner;
public class Project2 {
private static int rollDie() {
int num_random2 = (int) (Math.random() * 6) + 1;
System.out.println("Die 2: " + num_random2);
return num_random2;
}
private static int rollDie2() {
int num_random = (int) (Math.random() * 6) + 1;
System.out.println("Die 1: " + num_random);
return num_random;
}
private static void printDice(int num_random, int num_random2) {
int total = num_random + num_random2;
total = num_random + num_random2;
System.out.println("Total: " + total);
}
private static void printSpecialMessage(int total) {
String message1 = "Snake Eyes";
String message2 = "Box cars";
if (total == 12) {
System.out.println(message2);
}
else if (total == 2) {
System.out.println(message1);
}
}
public static void main(String[] args) {
System.out.println("Welcome to my app!");
System.out.println();
System.out.println("Dice Roller");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do {
int one = rollDie();
int two = rollDie2();
printDice(one, two);
printSpecialMessage(one + two);
System.out.print("Roll Again? (y/n): ");
choice = sc.next();
System.out.println();
} while (choice.equalsIgnoreCase("y"));
}
}
The things I changed (in no particular order).
Method printSpecialMessage requires an argument. You call that method from method main without an argument. Hence the following [compiler] error.
The method printSpecialMessage(int) in the type Project2 is not applicable for the arguments ()
Similarly for method printDice. That method requires two arguments but you call it with no arguments, which gives the following [compiler] error.
The method printDice(int, int) in the type Project2 is not applicable for the arguments ()
You need to save the value returned from method rollDie in a variable. You also need to save the value returned from method rollDie2 in another variable. Then you call method printDice with those two variables as arguments. In the code above I named the variables one and two.
break is not used in if statements. See method printSpecialMessage.
When comparing integers, use == (double equals sign). Again see method printSpecialMessage.
The following line of code is not inside the body of a method. It belongs in method printDice.
int total = num_random + num_random2;
Here is a sample run of the above code.
Welcome to my app!
Dice Roller
Die 2: 5
Die 1: 3
Total: 8
Roll Again? (y/n): y
Die 2: 6
Die 1: 3
Total: 9
Roll Again? (y/n): n

Returned int always zero + how to use object from Main method in sub-method

I am trying to write a simple Java program for school that does the following:
Gym Membership: "Write code that will input the customer’s age and number of months, and print the monthly rate and total amount to be charged. Prompt the user for the appropriate input, and display a meaningful output message. Make sure that the months are greater than 0 and the age is greater than 0."
My problems are:
custMonths int is always getting returned as 0 and I don't know why.
I can't seem to find a way to loop back to the start of my selectAge method if the user gives bad input (negative number or zero).
Here is my Java code:
import java.util.*;
public class GymMembership {
public static void main (String[] args) {
//create test customer (customer0) via the constructor
GymMembership customer0 = new GymMembership(70, 12);
customer0.selectAge(customer0.custAge);
customer0.printCustomer();
customer0.getMonthlyRate(customer0.ageNamed);
//prompt user for two integer inputs to create customer1
Scanner scnr = new Scanner(System.in);
System.out.println("Enter customer age, then number of months for contract: ");
GymMembership customer1 = new GymMembership(scnr.nextInt(), scnr.nextInt());
customer1.selectAge(customer1.custAge);
customer1.printCustomer();
}
//the constructor
GymMembership(int custAge, int custMonths) {
this.custAge = custAge;
this.custMonths = custMonths;
}
//instance variables
private int custAge;
private int custMonths;
int monthlyRate;
int childRate = 15;
int adultRate = 25;
int seniorRate = 20;
String ageNamed;
public String selectAge(int custAge) {
Scanner x = new Scanner(System.in);
int age = custAge;
ageNamed = "badInput";
do {
if (age >= 1 && age <= 18) {
ageNamed = "child";
}
else if (age >= 19 && age <= 64) {
ageNamed = "adult";
}
else if (age > 64 && age <= 120) {
ageNamed = "senior";
}
else {
ageNamed = "badInput";
System.out.println("Age must be a positive number between 1 and 120.");
break;
}
} while(ageNamed.equals("badInput"));
return ageNamed;
}
public int getMonthlyRate(String ageNamed) {
if (ageNamed.equalsIgnoreCase("child")) {
monthlyRate = 15;
} else if (ageNamed.equalsIgnoreCase("adult")) {
monthlyRate = 25;
} else {
monthlyRate = 20;
}
return monthlyRate;
}
public void printCustomer() {
if (ageNamed.equals("badInput") != true) {
System.out.println("The customer is a/an " + ageNamed + " and is " + custAge + " years old.");
System.out.println("The customer is signed up for a " + custMonths + " month contract.");
System.out.println("The monthly rate is " + monthlyRate);
}
else {
selectAge(customer1.custAge); //this is broken since I cannot access customer1 object from this "printCustomer" method.
}
}
}
I realize I am very likely making some bad beginners mistakes here as well, but am not quite sure what they are.
You seem to be over-complicating things. Some issues here including
You've got user I/O within the GymMembership class where it doesn't belong. Get it out and into its own UI class or simply the main method.
This includes not using Scanner within GymMembership as you're creating more than one Scanner based on System.in, a dangerous thing to do. Leave that in main.
Get the input in main, and then use it to create your GymMembership object. Repeat as needed.
I/O validation for age and months should also be in main. Again GymMembership should concern itself with just simply holding the state and behaviors of the object.
Or I suppose you could give GymMembership a static boolean method that checks for valid age and months, and use that in the main method to tell if data entered is valid.
The selectAge method is completely unnecessary as you're setting the age in the GymMembership's constructor. Again most of that code should be in the I/O section (main).
This, selectAge(customer1.custAge); isn't valid or necessary. You're within the GymMembership class, the current object's age field is visible to you directly, use it.
Your getMonthlyRate(...) method is dangerous in that it requires that a separate unnecessary field be calculated and passed in as a String, and this String is completely unnecessary, and likely this is causing you problems. The class already knows the information needed to calculate the rate via the age and months fields -- get rid of the String parameter and use the class's own fields.
e.g., the GymMembership class could be as simple as something like:
public class GymMemb2 {
private int age;
private int months;
public GymMemb2(int age, int months) {
this.age = age;
this.months = months;
}
public int getAge() {
return age;
}
public int getMonths() {
return months;
}
public double getMonthlyRate() {
// calculations using age and months for monthly rate
// return result
}
public String print() {
String text = "age: " + age + ", months: " + months;
// also add monthly rate info
return text;
}
}
Then in the main method, create the new Scanner(System.in) again, do this only once, and use it to get input. Within the main you'd use a while loop to keep looping until valid input has been entered, and then create your gym membership object(s). I think that the GymMembership class shouldn't have any println's within it but rather return Strings that may be printed by main if it desires.
Also at the end of main, close the Scanner by calling .close() on it. This should only be done with the program is completely done getting user input, since once closed it may not be reopened.

Java Unable to return variables

The code is fine, but when I need to take the variables out of the functions and put them into the public static void, it says the variable cannot be found. Anybody know how to solve this issue?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
System.out.println("Greetings, " + String(s) + ". " +
String(j) +"!" + " You are about " + int(z) + " years old");
}
public static String fNameGenerator(String s){
Scanner scan1 = new Scanner(System.in);
System.out.println("Please enter your first name: ");
String first = scan1.next();
s = first.substring(0,1).toUpperCase();
return s;
}
public static String LastName(String j){
Scanner scan2 = new Scanner(System.in);
System.out.println("Please enter you last name: ");
String second = scan2.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
j = y.substring(0,1).toUpperCase();
return j;
}
public static int age(int z){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
z = (2015 - third);
return z;
}
}
You are not calling any of the methods, so how do you expect them to return something?
Two things to remember:
just because you wrote return s at the end of a method, it does not mean you can access s outside of this method. There's something called scopes in java, that means that a variable exists only on the scope it's define in- in your case - inside the methods. if you want it to exist outside - take the returned value and do something with it.
declaring the methods does nothing until you actually call them
so in order to access these variables, you need to do something like this:
public static void main(String[] args) {
String s = fNameGenerator();
String j = LastName();
int z = age();
System.out.println("Greetings, " + s + ". " + j +"!" +" You are about " + z + " years old");
}
one more thing you can see that I did there- you don't need to pass anything to your methods, as you are not doing anything with the given values before re-setting them. just make sure you declare the fields inside. for example your age method should look like:
public static int age(){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
int z = (2015 - third);
return z;
}
There is a compile error in your code
System.out.println("Greetings, " + String(s) + ". " + String(j) +"!" +" You are about " + int(z) + " years old");
If you're trying to call the methods then replace
String(s) --> fNameGenerator(s)
String(j) --> LastName(j)
int(z) --> age(z)
Have the s,j,z as the local variables or static members.
or remove the arguments passing to the method as you're getting input from scanner

How to invoke multiple method signatures within a main method?

So I have three required codes I have already figured out. They are the codes for a quadratic formula, codes for an ISBN checker, and a code for Newtons Method. I'm supposed to make a menu with options 1, 2, and three each containing these codes respectively.
I guess this means I need different methods for this right? I was never really taught - I was told we had to always put in public class void main (String []args){ for everything, and I was just told there were variations to this?
For Quadratics formula, the information is : Return - void and parameters of three doubles, Newtons method: Return - double and parameters of 1 double, and ISBN checker: Return: Boolean and Parameters of 1 string. I don't really understand the parameters thing either. Help would be appreciated. I know this aesthetically looks horrible, but because my codes for now are relatively short I just edit the style when I' done. I know a lot of things are wrong in this too and I've spent time trying to figure them out.
import Java.util.Scanner;
public class HelperMethod{
public static void main(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
System.out.println ("You have three options. press one for the quadratic Formula, 2 for the newtons Method, and 3 for an ISBN checker.");
int input = userInputScanner.nextInt();
if (input = 1){
}else if (input = 2) {
private class NewtonsMethod {
public static void NewtonsMethod(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
double guess, fX, fPrimeX, newGuess;
System.out.println ("enter in a value give");
guess = userInputScanner.nextDouble();
System.out.println ("Your guess is " + guess);
while (true) {
fX = (6 * Math.pow (guess,4)) - (13 * Math.pow (guess,3)) - (18 * Math.pow (guess,2)) + (7 * guess) + 6;
fPrimeX = (24 * Math.pow (guess,3)) - (39 * Math.pow (guess,2)) - 36 * guess + 7;
newGuess = guess - (fX / fPrimeX);
System.out.println ("A possible root is " + newGuess);
if (Math.abs(newGuess - guess) < 0.00001) {
break;
} else {
guess = newGuess;
}
}
System.out.println ("The root is: " + newGuess);
}
}
}else{
private class BookNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char f;
int e, g, h;
int result = 0;
System.out.println ("Pleas enter a thirteen digit number");
String a = scanner.nextLine();
if (a.length() == 13){
for (int i = 0; i < 13; i ++) {
f = a.charAt(i);
e = Character.digit(f, 10);
if (i % 2 == 0) {
g = e * 1;
result = result + g;
} else {
g = e * 3;
result = result + g;
}
}
System.out.println ("The added sum of you numbers is " + result);
if (result % 10 == 0) {
System.out.println ("This combination IS a ISBN number");
} else {
System.out.println ("This is NOT an ISBN number");
}
} else {
System.out.println ("This combination is not thirteen digits long");
}
}
}
}
}
}
First of all, right now you're setting input to 1 in your first if statement. To compare input to 1 instead, use the == operator, i.e. if (input == 1) {.... Secondly, you don't really need to use classes, you can simply have methods NewtonsMethod(), BookNumber() etc. and run them when the input is correct.
public class HelperMethod{
public static void main(String[] args) {
int input;
//Handle user input
switch (input) {
case 1:
newtonsMethod();
break;
case 2:
bookNumber();
break;
case 3:
anotherMethod();
break;
}
}
public static void newtonsMethod() {
//Your code
}
public static void bookNumber() {
//Your code
}
public static void anotherMethod() {
//Your code
}
}
Methods should never be inside one another. That is what classes are for. A method is an element within a class. For example, in your case your class was named "HelperMethod". Your methods need to begin after the main method's code block is closed with a curly brace "}"
as an example
// This would be your main method.
public static void main(String args[]) {
// Your method is CALLED here.
someMethod();
{
// Then this is where your next method would start.
public static void someMethod() {
// Your code for the method of course goes here.
}
Of course you need your class setup and needed imports ABOVE the main method but you have that setup correctly already. With this setup, it makes it easy to call public methods that are in other classes. Your private methods are not really needed unless you intend to use more than one class, at which point you will need to import that class and then call the method like so
SomeClass.someMethod();

My variables are not initializing properly

In my code below double getAirSpeed double calcPatternwidth and double calcPatternLength are not being initialized properly, why?
/**
* holding patterns
* assignment 1
* question 2
**/
import java.util.Scanner;
public class StockiColeA1Q2 {
public static void main(String []args) {
Scanner keyboard = new Scanner(System.in);
double getAirSpeed ;
double calcPatternWidth;
double calcPatternLength;
System.out.println("That speed is " + getAirSpeed +
"\nHolding pattern width: " + calcPatternWidth +
"kms\nHolding pattern length: " + calcPatternLength + "kms");
}//main
public static double getAirSpeed() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the speed in Knots: ");
double knots = keyboard.nextDouble(); //knots given by user
return knots*1.852;
}//get air speed
public static double calcPatternWidth(double knots) {
return (knots/60*Math.PI)*2;
}//patern width
public static double calcPatternLength(double knots) {
return knots/60 + (knots/60*Math.PI)*2;
}//pattern width
}//class
You aren't properly initializing the variables in main. You show call the functions and assign them up front and then display them. I think what you were looking for was a main that looked liked this:
public static void main(String[] args) {
double getAirSpeed = getAirSpeed();
double calcPatternWidth = calcPatternWidth(getAirSpeed);
double calcPatternLength = calcPatternLength(getAirSpeed);
System.out.println("That speed is " + getAirSpeed + "\nHolding pattern width: " + calcPatternWidth
+ "kms\nHolding pattern length: " + calcPatternLength + "kms");
}// main
The code above uses the getAirSpeed as a parameter to calcPatternWidth and calcPatternLength. I am guessing that was what you intended to accomplish.
You really should close the Scanner object when finished so I'd amend getAirSpeed() to call keyboard.close() before returning.
public static double getAirSpeed() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the speed in Knots: ");
double knots = keyboard.nextDouble(); // knots given by user
keyboard.close();
return knots * 1.852;
}// get air speed
Here I am not able to see where you are initializing the given variables. As all three vairables are local to main method so compiler will not assign the default value to them. just creating getter of those variable will not assign the value. If you create the variable out side the main method in class the compiler will assign the defaut value but you have to make them static as main method is static and you cannot use non-static variable inside the static block.

Categories