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;
}
}
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;
}
}
}
I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.
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()
I have a program to find pythagorean triples. in it, i have an object that needs to be used to call methods. Said object is broken. Errors are " The method Triples(int) is undefined for the type Triples" and "The method greatesCommonFactor() is undefined for the type Triples" mind you, not everything in Triples does useful stuff atm. It isn't completely finished yet.
public class TriplesRunner
{
public static void main(String args[])
{
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the natural number :: ");
number=keyboard.nextInt();
Triples test = new Triples();
test.Triples(number);
test.greatestCommonFactor(number);
System.out.println(test.toString());
}
}
public class Triples
{
public int number;
public Triples(int num)
{
setNum(number);
}
public void setNum(int num)
{
int a = 0;
int b = 0;
int c = 0;
}
public int greatestCommonFactor(int a, int b, int c)
{
int max = 0;
for(a=1; a<=number-2; a++)
{
for(b=a+1; b<=number-1; b++)
{
for(c=b+1; c<=number; c++)
{
if(a*a + b*b == c*c);
}
}
}
return 1;
}
public String toString()
{
String output="";
output+="a + b + c";
return output+"\n";
}
}
you are trying to call the constructor as a method,
Change this part:
Triples test = new Triples();
test.Triples(number);
to
Triples.test = new Triples(number);
Triples isn't a method - it's your constructor, meaning it's invoked with the new operator:
Triples test = new Triples(number);
greatestCommonFactor is not defined properly. It currently takes three int arguments, instead of taking none and using Triples' data members:
public int greatestCommonFactor()
I was trying to make a program that searches for a random number, but i had problems importing the "a" variable in the other method. I would be happy if i could get some explanation. I have already tried to make the variable static, but that doesn't work
import java.util.Random;
public class verschlüsselung {
private static void nummber(int a) {
Random r = new Random();
a = r.nextInt(999);
System.out.println(a);
}
private static void search(int b) {
b = 0;
if(b =! a) {
for(b = 1; b =! a ; b++) {
if(b == a) {
System.out.println("found the number " + b);
}
}
}
}
public static void main(String args[]){
nummber(0);
search(0);
}
}
There is no such thing as using local variables in other methods.
You can return the variable from one method. Than call this method from other and get there the variable.
Declare the variable 'a' to be static and remove the parameter 'a' passed in the nummber()
function. This function does not need any input as it assigns the value of a random number to the global static variable 'a' which is accessed in the method search().
your declaration and method signature should read :
private static int a;
private static void nummber(){....}
May this help you:
private static int nummber( int a){
Random r = new Random();
a =r.nextInt(999);
System.out.println(a);
return a;
}
private static void search(int b, int a){
b = 0;
if(b =! a){
for(b =1; b =! a ; b++){
if(b == a){
System.out.println("found the number " + b);
}
}
}
}
public static void main(String args[]){
int a = nummber(0);
search(0, a);
}