Using objects in a subclass java [duplicate] - java

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;
}
}
}

Related

I can not understand why my console is not showing any of my output [duplicate]

This question already has answers here:
Java: How To Call Non Static Method From Main Method?
(9 answers)
Closed 3 years ago.
my console doesn't seem to be showing any output on my projects, on some, it does at first. I am new to this so I don't understand it, this is an example of my code
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
}
public void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Replace your main method with the following code and it should work as you are expecting:
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
}
The reason why it didn't work for you is because you have missed to call the methods you have created in the class. I have added the following lines in the main method to complete that missing part:
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
None of your methods are static, so you'll need to create an instance of your TestAmazing class, and call methods via your instance.
That might look something like:
public static void main(String args[]) {
TestAmazing test = new TestAmazing();
test.roomtemp();
test.bonusball();
// etc...
}
Comment from QA:
this worked thank you! do I have to always do this and put it in the
same place? – Joe Emery
Not necessarily. It depends on the requirements of your program. If all of your methods are STATIC then you don't need an instance of your class. In that case, then you'd simply call all of your methods directly from main, like this:
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
roomtemp();
bonusball();
currentpopulationofchina();
gameloadingstatus()
}
public static void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public static void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public static void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public static void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Notice how every method has static in its declaration.

Java Assignment, add value to variable in different class

currently doing an assignemnt but i'm new to programming so was wondering how you add a value to a variable in a different class which already has an existing class
class OtherClass {
int a;
}
public class Main Class{
public static void main(String[] args) {
int b = 7;
OtherClass temp = new OtherClass();
OtherClass.a = 5
OtherClass.put(b) //this is where I'm not sure how to add b to a
}
Actual Code
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Enter amount of money you have: ");
Scanner input = new Scanner(System.in);
Wallet bettersWallet = new Wallet();
bettersWallet.moneyAvailable = input.nextDouble(); //then had a function which played out a bet and added/took away winnings from the bet
int winnings = 5;
bettersWallet.moneyAvailable +=winnings; //Will setMoneyAvailable function work in this scenario aswell?
}
class Wallet {
double moneyAvailable;
double openingCash;
public void setMoneyAvailable()
{
moneyAvailable += ChuckALuckDiceGame.winnings;
}
int b = 7;
OtherClass temp = new OtherClass();
temp.a = 5;
temp.a += b; //Same as temp.a = temp.a + b;
System.out.println(temp.a);
What we are doing here,
We are creating an object of class OtherClass, the name of the object is temp.
Then we are assigning the value 5 in the attribute a of object temp
Then we are adding the value of primitive variable b into the variable temp.a.
The sum of the above equation is being assigned to the value of temp.a
Then I am printing the sum at the end through System.out.println(temp.a);

Printing on same line

I am new to Java and I am trying to print the student numbers and numbers (cijfer in this case) on 1 line. But for some reason I get weird signs etc. Also when I'm trying something else I get a non-static context error. What does this mean and how does this exactly work?
Down here is my code:
import java.text.DecimalFormat;
import java.util.Arrays;
public class Student {
public static final int AANTAL_STUDENTEN = 50;
public int[] studentNummer = new int[AANTAL_STUDENTEN];
public String[] cijfer;
public int[] StudentNummers() {
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
studentNummer[i] = (50060001 + i);
}
return studentNummer;
}
public String[] cijfers(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
DecimalFormat df = new DecimalFormat("#.#");
String cijferformat = df.format(Math.random() * ( 10 - 1 ) + 1);
cijfer[i++] = cijferformat;
}
return cijfer;
}
public static void main(String[] Args) {
System.out.println("I cant call the cijfer and studentnummer.");
}
}
Also I'm aware my cijfer array is giving a nullpointer exception. I still have to fix this.
I am not java developer but try
System.out.print
You could loop around System.out.print. Otherwise make your functions static to access them from main. Also initialize your cijfer array.
Besides the things I noted in the comments, your design needs work. You have a class Student which contains 50 studentNummer and cijfer members. Presumably, a Student would only have one studentNummer and and one cijfer. You need 2 classes: 1 for a single Student and one to hold all the Student objects (StudentBody for example).
public class StudentBody {
// An inner class (doesn't have to be)
public class Student {
// Just one of these
public int studentNummer;
public String cijfer;
// A constructor. Pass the student #
public Student(int id) {
studentNummer = id;
DecimalFormat df = new DecimalFormat("#.#");
cijfer = df.format(Math.random() * ( 10 - 1 ) + 1);
}
// Override toString
#Override
public String toString() {
return studentNummer + " " + cijfer;
}
}
public static final int AANTAL_STUDENTEN = 50;
public Student students[] = new Student[AANTAL_STUDENTEN];
// StudentBody constructor
public StudentBody() {
// Create all Students
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
students[i] = new Student(50060001 + i);
}
}
// Function to print all Students
public void printStudents(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
System.out.println(students[i]);
}
}
public static void main(String[] Args) {
// Create a StudentBody object
StudentBody allStudents = new StudentBody();
// Print
allStudents.printStudents();
}
}
Just make all your methods and class variables as static. And then you have access to them from main method. Moreover you have got some errors in code:
public class Student {
public static final int AANTAL_STUDENTEN = 50;
// NOTE: static variables can be moved to local ones
// NOTE: only static method are available from static context
public static int[] StudentNummers() {
int[] studentNummer = new int[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
studentNummer[i] = 50060001 + i;
return studentNummer;
}
// NOTE: only static method are available from static context
public static String[] cijfers() {
// NOTE: it is better to use same `df` instance
DecimalFormat df = new DecimalFormat("#.#");
String[] cijfer = new String[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
// NOTE: remove `i++`, because we have it in the loop
cijfer[i] = df.format(Math.random() * (10 - 1) + 1);
return cijfer;
}
// NOTE: this is `static` method, therefore it has access only to static methods and variables
public static void main(String[] Args) {
String[] cijfer = cijfers();
int[] studentNummer = StudentNummers();
// TODO you can pring two arrays one element per line
for(int i = 0; i < AANTAL_STUDENTEN; i++)
Sytem.out.println(cijfer[i] + '-' + studentNummer[i]);
// TODO as alternative, you can print whole array
System.out.println(Arrays.toString(cijfer));
System.out.println(Arrays.toString(studentNummer));
}
}

How to run a method from a different class - JAVA [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to call the toh method from my main class(Driver). When I make the call it gives me a null pointer exception. How can I call the toh method in Hanoi from the driver class? When I combine the classes into one it works fine but I need them to be two separate classes. Also, I included the global variables I am using in both classes is that necessary? Any help is welcome. Thanks!
public class Hanoi {
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println("T"+cycle + " Pillar 1 | Pillar 2 | Pillar 3");
System.out.println("-------------------------------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println("\n");
cycle++;
}
}
Main class(driver):
public class Driver{
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
int num = 0;
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<>();
tower[2] = new Stack<>();
tower[3] = new Stack<>();
/* Accepting number of disks */
while(num <=0){
System.out.println("Enter number of disks(greater than 0):");
num = scan.nextInt();
}
N = num;
Hanoi.toh(num);
}
}
You are initializing your tower array inside your Driver class, however, you have not initialized it in your Hanoi class.
As I said in my comment, please do not write global variables twice, in different classes. This is because the different classes DO NOT share the same global variables. (when we say global variable, we mean that they are global to the Driver class only. To access those variables, use the dot operator)
For example, get rid of the N cycle and tower declarations from your Hanoi class
Then access those variables using the dot operator.
tower would become Driver.tower and N would become Driver.N and so forth.
Note: this only works if your Driver class is static, otherwise you would need to access it as an object attribute.
Try to initialize the tower array, something like this:
public static Stack<Integer>[] tower;
public static void toh( int n )
{
tower = new Stack[n];
for ( int d = 0 ; d < n ; d++ )
{
tower[d]=new Stack<>();
}
delete duplicated static values in a class (either Driver or Hanoi)
then in the class that no longer has the static values and add that class to the beginning of all the missing classes.
Ex:
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public static int MyVar;
public void bMethod(){
++MyVar;
}
}
↓ to ↓
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public void bMethod(){
++A.MyVar;
}
}

Returning String Methods in Java?

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

Categories

Resources