This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I know Java foreach loops are only meant to read values and not assign them, but I was wondering if they can call mutator methods on object. To find out I designed an experiment. Unfortunately the experiment crashes and I'm curious as to why.
public class test {
public static void main(String[] args)
{
foo[] f = new foo[4];
/*this would be a foreach loop, once I got the program working normally*/
for(int i = 0; i < f.length; i++) {
System.out.println(f[i].get());
f[i].add();
System.out.println(f[i].get());
}
}
private class foo {
foo() {
int x = 5;
}
void add() {
x++;
}
int get() {
return x;
}
private int x;
}
}
Gives Exception in thread "main" java.lang.NullPointerException when I expected the output to be 5 6. Is it because the constructor to foo isn't being called? If so, how can it be called? Must foo be made a static class?
You have an array of null and have not initialized any of the Foo items in the array, meaning it holds nothing but nulls.
Foo[] foos = new Foo[4];
// you need to first do this! You need to fill your array with **objects**!
for (int i = 0; i < foos.length; i++) {
foos[i] = new Foo(); // ******* add this!!*******
System.out.println(foos[i].get()); // this will now work
foos[i].add();
System.out.println(foos[i].get());
}
// now you can use the array
As an aside, your x will be 0 initially because you shadow the variable in the Foo constructor.
public class Foo {
private int x;
Foo() {
// this **re-declares the x variable**
int x = 5;
}
//....
Instead you want to do:
public class Foo {
private int x;
Foo() {
x = 5;
}
//....
Aside #2: you will want to learn and use Java naming conventions. Class names should all begin with an upper-case letter and variable names with a lower-case letter. This is important if you need others (us!!) to understand your code quickly and easily.
An example of a single class. Call it Foo.java and have it hold only one class:
public class Foo {
private int x;
public Foo() {
x = 5;
// not!
// int x = 5;
}
public void increment() {
x++;
}
public void decrement() {
x--;
}
public int getX() {
return x;
}
public static void main(String[] args) {
int fooCount = 10;
Foo[] foos = new Foo[fooCount];
for (int i = 0; i < foos.length; i++) {
foos[i] = new Foo();
System.out.println(foos[i].getX());
foos[i].increment();
foos[i].increment();
System.out.println(foos[i].getX());
}
for (Foo foo : foos) {
foo.decrement();
foo.decrement();
foo.decrement();
System.out.println(foo.getX());
}
}
}
Related
I have a class:
public class a {
public int memberA;
private int memberB;
public a (int i) {
memberA = i;
memberB = ...;
}
}
and another one:
public class b {
public a[] = new a[10]; // <-- How do I call the constructor of 'a' with a value?
...
}
I tried many things, but nothing works! My app crashes if I don't call the constructor!
You can just use a for loop to instantiate each element of the array.
public class b {
public a[] arr = new a[10];
{
for(int i = 0; i < arr.length; i++) arr[i] = new a(/*some value*/);
}
}
As an aside, always follow Java naming conventions e.g. the name of the classes should be A and B instead of a and b. Better if you use self-descriptive names.
class decimaltobinary{
int y= 56;
int array[] = new int[10];
public static void main(String[] args) {
converttobinary con = new converttobinary();
}
class converttobinary{ //Error occurring at this line
for(int i = 0; i<11;i++) {
while(y > 0) {
int x = y%2;
array[i]= x;
}
}
}
}
// Error occurring at the class convert to binary.
// It says insert Class body to complete class declaration.
Well the error speaks for itself.
Insert Class body to complete class declaration.
For loops must be either inside a method or a block.
class converttobinary {
{
for (int i = 0; i < 11; i++) {
while (y > 0) {
int x = y % 2;
array[i] = x;
}
}
}
}
And then you'll have another problem in your code.
Non-static variables cannot be referenced from a static context.
When you are coding in the main method note that it is static (public static void main(...)) so either you have to make all variables static or create a new instance of decimaltobinary class.
Easiest way to solve this is by creating a new instance of decimaltobinary
converttobinary con = new decimaltobinary().new converttobinary();
Below code must be kept inside some method :
for(int i = 0; i<11;i++) {
while(y > 0) {
int x = y%2;
array[i]= x;
}
}
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;
}
}
This question already has answers here:
Why do arrays change in method calls? [duplicate]
(6 answers)
Closed 7 years ago.
I'm confused about the method. I thought typically you need to return something. Or in my mind I would have thought the need for a for loop that passes the elements back from the method that adds 5 to each element.
However When the array is passed to the method, the array itself changes, but why?
public static void main(String[] args) {
int ray[]={3,4,5,6,7};
change(ray);
for(int y: ray){
System.out.println(y);
}
}
public static void change(int x[]){
for(int counter = 0; counter < x.length;counter++){
x[counter]+=5;
}
}
In Java, all objects are passed by reference, and arrays are objects. That means that your change method receives the same array that was created in main--not a copy of it, the same object. So when you modify it, the main method sees that change too.
Java is pass-by-value for primitives, and pass-by-reference(value) for everything else (including arrays).
http://javadude.com/articles/passbyvalue.htm
What that basically means is that your function does not get a copy of the array, it gets the array itself.
Try it with an int (the original value will not change, because it's a primitive).
public static void main(String[] args) {
int ray[]={3,4,5,6,7};
change(ray);
for(int y: ray){
System.out.println(y);
}
}
public static void change(int i){
i = i + 10;
}
public static void change(int x[]){
for(int counter = 0; counter < x.length;counter++){
x[counter]+=5;
}
}
Some will say that Java always passes by value, but that's because of a poor choice of definitions when it comes to references.
Objects are conceptually passed by reference, and primitives by value. You can call it what you like but it looks like a duck, walks like a duck and quacks like a duck.
Try this, you'll get a better idea:
/**
* Main
*
*/
public class Main {
static class IntegerClass {
int internal;
public IntegerClass(int i) {
internal = i;
}
public void setInternal(int i) {
internal = i;
}
public int getInternal() {
return internal;
}
}
public static void main(String[] a) {
int x = 10;
changeInteger(x);
System.err.println(x);
IntegerClass ic = new IntegerClass(10);
changeIntegerClass(ic);
System.err.println(ic.getInternal());
}
public static void changeIntegerClass(IntegerClass ic) {
ic.setInternal(500);
}
public static void changeInteger(Integer i) {
i = 500;
}
}
I have a quick question out of curiosity...if I declare an integer in one method, for example: i = 1, is it possible for me to take that i and use its value in my main class (or another method)? The following code may be helpful in understanding what I'm asking...of course, the code might not be correct depending on what the answer is.
public class main {
public main() {
int n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
No you cannot! Not unless you make it an instance variable!
Or actually send it to the function as an argument!
First, let's start simple. All methods that are not constructors require a return type. In other words,
public void number(){
i = 1;
}
would be more proper.
Second: the main method traditionally has a signature of public static void main(String[] args).
Now, on to your question at hand. Let's consider a few cases. I will be breaking a few common coding conventions to get my point across.
Case 1
public void number(){
i = 1;
}
As your code stands now, you will have a compile-time error because i is not ever declared. You could solve this by declaring this somewhere in the class. To access this variable, you will need an object of type Main, which would make your class look like this:
public class Main {
int i;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
i = 1;
}
}
Case 2
Let's say you don't want to make i a class variable. You just want it to be a value returned by the function. Your code would then look like this:
public class Main {
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
}
public int number(){ //the int here means we are returning an int
i = 1;
return i;
}
}
Case 3
Both of the previous cases will print out 1 as their output. But let's try something different.
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
int i = 1;
}
}
What do you think the output would be in this case? It's not 1! In this case, our output is 0. Why?
The statement int i = 1; in number(), it creates a new variable, also referred to as i, in the scope of number(). As soon as number() finishes, that variable is wiped out. The original i, declared right under public class Main has not changed. Thus, when we print out myMain.i, its value is 0.
Case 4
One more case, just for fun:
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
System.out.print(myMain.i);
}
public int number(){
int i = 1;
return i;
}
}
What will the output of this be? It's 10. Why you ask? Because the i returned by number() is the i in the scope of number() and has a value of 1. myMain's i, however, remains unchanged as in Case 3.
You may use a class-scope field to store you variable in a class object or you can return it from one method or pass it as a parameter to the other. Mind that you will need to call your methods in the right order, which is not the best design possible.
public class main {
int n;
int i;
public main() {
n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
Yes, create a classmember:
public class Main
{
private int i;
public main() {
int n = 1;
System.out.print(n + i);
number();
System.out.print(n + i);
}
public number(){
i = 1;
}
}
void method(){
int i = 0; //has only method scope and cannot be used outside it
}
void method1(){
i = 1; //cannot do this
}
This is because the scope of i is limited to the method it is declared in.