This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 8 years ago.
I am new to java and having an issue calling a non static method
This is my main
public static void main(String[] args) {
Fish f1 = new Fish("Nemo");
Fish f2 = new Fish("Dory");
f2.setNumber(2);
Fish m = new Fish("Bruce");
m.setNumber(3);
Fish.printAllFish();
}
This is my fish class
import java.util.ArrayList;
import java.util.List;
public class Fish {
protected String name;
protected int number;
protected List<Fish> fishList = new ArrayList<Fish>();
public Fish(String in){
name = in;
number = 1;
fishList.add(this);
}
public void printFish(){
System.out.println("the fish called" + name + " is number " + number );
}
public void setNumber(int Number){
this.number = number;
}
public int getNumber(){
return number;
}
public String getName(){
return name;
}
public int getFishNumOf(){
return fishList.size();
}
public void printAllFish(){
int size = this.getFishNumOf();
System.out.println("There are " + size + " fish:");
for (int i = 0; i < size; i++){
String a = getName();
int b = getNumber();
System.out.println("The Fish " + a + " is number " + b );
}
}
}
I get the nonstatic error when trying to call printAllFish, I know I am probably making some rookie mistakes but I only just started to learn programming and things like classes, gets and sets still confuse me, any help would be very much appreciated!
You need to make printAllFish, getFishNumOf and fishList static and remove the this keyword before getFishNumOf. Then in the for loop you have to specify which fish you're getting the name and number of for each iteration of the loop. For instance:
for(Fish f : fishList)
String a = f.getName();
int b = f.getNumber();
System.out.println("The Fish " + a + " is number " + b );
}
printAllFish is non-static method and you are trying to call it in a static way i.e. using the class name and not the instance.
You should call it using one of the instance i.e. f1 or f2:
f1.printAllFish();
you have to call your initialized object method. not Fish.printAllFish() but f1.printAllFish(), f2.printAllFish() or m.printAllFish()
I suggest using a different class named FishContainer where it has a List object of Fish objects and when initializing a Fish object, you add it to FishContainer's list property and then call the printAllFish() from the container class.
Try sth like this:
FishContainer container = new FishContainer();
Fish f1 = new Fish("Nemo");
Fish f2 = new Fish("Dory");
f2.setNumber(2);
Fish m = new Fish("Bruce");
m.setNumber(3);
container.addFish(f1);
container.addFish(f2);
container.addFish(m);
container.printAllFish();
Related
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 1 year ago.
I want to use objects that I've declared in one class in a subclass but it gives me non-static variable cannot be referenced from static context I'm a beginner with this so what can I change to make this work
class PairofDice {
int d61;
int d62;
PairofDice d1 = new PairofDice();
PairofDice d2 = new PairofDice();
class BoxCars {
public static void main(String[] args) {
roll();
Random rand = new Random();
int BC = 0;
for (int i = 0; i < 1000; i++) {
d1.d61 = rand.nextInt(6 + 1 - 1) + 1;
d2.d62 = rand.nextInt(6 + 1 - 1) + 1;
if (d1.d61 + d2.d62 == 12) {
BC++;
}
}
}
}
}
(ignore the roll method it's a part of something else)
Your question implies a nested class, and not what one would consider a subclass. Here is a suggested structure for your code. Before creating an instance of the inner class you need to have one of the containing class which in this case is BoxCars. You can rename the classes to whatever fits your requirement.
public class BoxCars {
public static void main(String[] args) {
BoxCars bc = new BoxCars();
PairOfDice dice = bc.new PairOfDice();
int numberOfRolls = dice.roll();
System.out.printf("I rolled %d box cars%n", numberOfRolls);
}
class PairOfDice {
int d1;
int d2;
public int roll() {
int BC = 0;
// No need to create instances of dice here. Just use d1 and d2
// code here to count the dice that are box cars.
// you have already written this.
return BC;
}
}
}
This question already has answers here:
The connection between 'System.out.println()' and 'toString()' in Java
(3 answers)
Closed 2 years ago.
consider the two classes below, why when I call the print method in the second class i get "blueblueblue is blue repeated" instead of "blueblueblue" despite the fact that tostring() was never called
public class Simple{
private String word;
private String phrase;
public Simple(int number, String w) {
word = w;
phrase = mystery(number, w);
}
private String mystery(int num, String s) {
String answer = "";
for (int k=0; k<num; k++) {
answer = answer + s;
}
return answer;
}
public String toString() {
return phrase + " is " + word + " repeated";
}
}
public class TestSimple{
public void print() {
Simple item = new Simple(3, "blue");
System.out.println(item);
}
}
yeah,the system out finally will invoke the
object's toString method. you can get the source code.
This question already has answers here:
Error in System.out.println
(5 answers)
Closed 4 years ago.
My Task:
Create a class called Icosahedron which will be used to represent a regular icosahedron, that is a convex polyhedron with 20 equilateral triangles as faces. The class should have the following features:
A private instance variable, edge, of type double, that holds the
edge
length.
A private static variable, count, of type int, that holds the
number of Icosahedron objects that have been created.
A constructor that takes one double argument which specifies the edge length.
An
instance method surface() which returns the surface area of the
icosahedron. This can be calculated using the formula 5*√3 edge².
An
instance method volume() which returns the volume of the icosahedron.
This can be calculated using the formula 5*(3+√5)/12*edge³.
An
instance method toString() which returns a string with the edge
length, surface area and volume as in the example below:
Icosahedron[edge= 3.000, surface= 77.942, volume= 58.906]
The numbers in this string should be in floating point format with a field
that is (at least) 7 characters wide and showing 3 decimal places.
Please use the static method String.format with a suitable formatting
string to achieve this. A static method getCount() which returns the
value of the static variable count.
Finally, add the following main method to your Icosahedron class so that it can be run and tested:
public static void main(String[] args) {
System.out.println("Number of Icosahedron objects created: " + getCount());
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++)
icos[i] = new Icosahedron(i+1);
for (int i = 0; i < icos.length; i++)
System.out.println(icos[i]);
System.out.println("Number of Icosahedron objects created: " + getCount());
}
Okay. so heres what i have started on:
import java.util.Scanner;
public class Icosahedron {
private double edge = 0;
private int count = 0;
Scanner input = new Scanner(System.in);
double useredge = input.nextDouble();
System.out.println("Enter Edge Length: ");
}
i receive an error on the last line. i cant use println() what am i doing wrong? or maybe im understanding the question wrong? any guidance would be appreciated.
thanks.
Your Icosahedron class should look like the following:
public class Icosahedron {
private double edge;
private int count;
public Icosahedron(int count) {
this.count = count;
}
public double getEdge() {
return edge;
}
public void setEdge(double edge) {
this.edge = edge;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Icosahedron{edge=" + edge + ", count=" + count + '}';
}
}
And your class containing the main method (I called it MoreProblem):
import java.util.Scanner;
public class MoreProblem {
public static void main(String[] args) {
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++) {
icos[i] = new Icosahedron(i+1);
Scanner input = new Scanner(System.in);
System.out.println("Enter Edge Length: ");
double userEdge = input.nextDouble();
icos[i].setEdge(userEdge);
}
for (Icosahedron icosahedron : icos) {
System.out.println(icosahedron);
}
System.out.println("Number of Icosahedron objects created: " + icos.length);
}
}
I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()
The array with the names of strings of the instrument is a required field in the Instrument class, but in order to simplify the program, I will accept solutions in which tuning of an instrument is not done separately on each string. However, if you want to work with each string, a good example is found in the Week 8 Additional Notes, in which another class of instruments represented by Tuba is considered.
Please use Listings 8.3 and 8.4 as models to organize your code for Project 3 in two separate classes, one for defining the instrument, and the other one to test instruments.
Make the methods in the Instrument class to return String, unlike the example in the requirements, where such methods write directly to standard output. This is necessary because it is required that output of the test class be written to a file specified by the user on the command line.
In the test class you must have an array with 10 elements of Instrument type, populate the array with instances of the Instrument class (by using the new operator on the class constructor), and the use a while or for loop to perform tests (i.e. call Intrument class methods) on each array element.
As specified in the requirements, the test class must be started with an argument in the command line:
java Mynamep3tst myfilename.txt
where myfilename.txt is the file where all output must go. This file name should be used in the program as follows (see Listing 14.13):
java.io.File file = new java.io.File(args[0]);
java.io.PrintWriter output = new java.io.PrintWriter(file);
and when you have a message to be sent to the file,
output.println(message);
*My question is every time I try to create a new object of the instrument class within my for loop with the use of the array instrumentContent it causes an error. I cannot understand if I am not allowed to create new objects in this fashion. If I am not allowed to do it this way what is the proper way to do it so that each of my arrays are used?*
class StringInstrument {//begin class
//declare variables
boolean isTuned;
boolean isPlaying;
boolean band;
public String nameOfInstrument;
int numberOfStrings;
String nameofStringsInInstrument[] = {"E", "A", "D", "G", "B"}; //an array of string names
public StringInstrument() {//begin contructor
numberOfStrings = 5;
isTuned = false;
isPlaying = false;
band = false;
}//end constructor
public int NumberOfStrings(int stringNumber){//begin method
System.out.println("The number of strings for the " + nameOfInstrument + " is " + stringNumber );
return this.numberOfStrings = stringNumber;
}//end method
public String InstrumentNameGet() {//begin method
return nameOfInstrument;
}//end method
public void SetInstrumentName (String instrumentName) {//begin getter method
nameOfInstrument = instrumentName;
}//end method
public String InstrumentNameDisplay() {//begin method
System.out.println("Your instrument is the " + nameOfInstrument);
return nameOfInstrument;
}//end method
public boolean PlayInstrument(){//begin method
System.out.println("You are playing your " + nameOfInstrument);
return isPlaying = true;
}//end method
public boolean TuneInstrument(){//begin method
System.out.println("Tune " + nameOfInstrument);
return isTuned = true;
}//end method
public boolean stopTuneInstrument() {//begin method
System.out.println("The" + nameOfInstrument + " is out of tune.");
return isTuned = false;
}//end method
public boolean StopPlayInstrument() {//begin method
System.out.println("The " + nameOfInstrument + " has stopped playing");
return isTuned = false;
}//end method
public boolean PlayInstrumentBand() {//begin method
System.out.println("The " + nameOfInstrument + " is playing in a band");
return band = true;
}//end method
public boolean StopPlayInstrumentBand() {//begin method
System.out.println("The " + nameOfInstrument + " has stoped playing with the band");
System.out.println("\n");
return band = false;
}//end method
}//end class
public class RandyGilmanP3 {//begin class
public static void main(String[] args) throws Exception{//begin main
java.io.File file = new java.io.File("RandyGilmanP3.txt");
//create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
//Declaring, creating, and intialize arrays
String[] instrumentList = new String [10];
String[] instrumentContent = new String [10];
int[] stringNumber = new int [10];
//input string names into array
instrumentList[0] = "Guitar";
instrumentList[1] = "Violin";
instrumentList[2] = "Bass Guitar";
instrumentList[3] = "Cello";
instrumentList[4] = "Banjo";
instrumentList[5] = "Sitar";
instrumentList[6] = "Rabab";
instrumentList[7] = "Viola";
instrumentList[8] = "Harp";
instrumentList[9] = "Ukulele";
//input string amounts into array
stringNumber[0] = 5;
stringNumber[1] = 4;
stringNumber[2] = 5;
stringNumber[3] = 4;
stringNumber[4] = 5;
stringNumber[5] = 18;
stringNumber[6] = 3;
stringNumber[7] = 4;
stringNumber[8] = 47;
stringNumber[9] = 4;
for (int i = 0; i < instrumentContent.length; i++){//begin for loop
StringInstrument instrumentList[i] = new StringInstrument();
output.println(instrumentList[i].InstrumentNameDisplay());
output.println(instrumentList[i].NumberOfStrings(stringNumber[i]));
output.println(instrumentList[i].TuneInstrument());
output.println(instrumentList[i].PlayInstrument());
output.println(instrumentList[i].PlayInstrumentBand());
output.println(instrumentList[i].StopPlayInstrument());
}//end for loop
}//end main
}//end class
You've declared instrumentList[] as an array of Strings. Your for loop attempts calling the following method on these Strings:
InstrumentNameDisplay()
NumberOfStrings(String)
TuneInstrument()
`PlayInstrument()
PlayInstrumentBand()
StopPlayInstrument()
None of these are methods of the String class.
It looks like what you might be trying to do is build an array of Instruments...