Object is null after being initialized in a method - java

I'm new to programming and I have a problem in my code.
I start by initializing the Maze object to null because I don't know which will be the choice of the user. It is initialized in the method createMaze() but when I call printMaze it is null.
import java.util.Scanner;
public class Main {
public static final String EXITGAME = "EXIT";
public static final String PRINTBOARD = "PRINT";
public static final String CREATEMAZE = "UPLOAD";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Maze maze = null;
menu(maze,in);
}
private static void menu(Maze maze, Scanner in){
String option = in.nextLine();
while(option.toUpperCase() != EXITGAME){
switch(option.toUpperCase()){
case PRINTBOARD: printMaze(maze); break;
case CREATEMAZE: createMaze(in,maze); break;
}
System.out.println();
option = in.nextLine();
}
}
private static void printMaze(Maze maze){
if(maze != null){
int maxX = maze.getxSize();
int maxY = maze.getySize();
for(int x = 0; x < maxX; x++){
for(int y = 0; y < maxY; y++){
System.out.print(maze.getMazeRepresentation(x, y));
}
System.out.println();
}
}
else
System.out.println("Maze is undefined");
}
private static void createMaze(Scanner in, Maze maze){
if(maze == null || !maze.getGameStatus()){
int x = in.nextInt();
int y = in.nextInt();
in.nextLine();
char rawMaze[][] = new char[x][y];
maze = new MazeClass(x,y);
for(int i = 0; i < x; i++){
createMazeLine(in,i,y, rawMaze);
}
maze.createMaze(rawMaze);
}
else
System.out.println("Maze already defined.");
}
private static void createMazeLine(Scanner in, int lines, int y, char[][] rawMaze){
String line = in.nextLine();
for(int i = 0; i < y; i++){
rawMaze[lines][i] = line.charAt(i);
}
}
}

in Java when you pass parameter to the method (i.e. Maze maze createMaze(Scanner in, Maze maze) it is a value of reference to the maze.
In other words in your case:
there is a null value.
there is a reference to that null called null
in call to the method value of that reference passed (let say address) as pramemter
in method call there is a parameter variable which holds value of that reference
Java does not have "parameters by reference" or pointers conception.
So, when inside the method createMaze you do maze = new MazeClass(x,y);
you assign new object maze reference to the reference parameter variable.
But your initial null value and reference to it outside of method stay untouched and object you created inside method destroyed after method done.
In short, all you need is:
private static void menu(Maze maze, Scanner in){
String option = in.nextLine();
while(option.toUpperCase() != EXITGAME){
switch(option.toUpperCase()){
case PRINTBOARD: printMaze(maze); break;
case CREATEMAZE: maze = createMaze(in,maze); break;
}
System.out.println();
option = in.nextLine();
}
}
private static Maze createMaze(Scanner in, Maze maze){
if(maze == null || !maze.getGameStatus()){
... yuor code ...
maze.createMaze(rawMaze);
}
else
System.out.println("Maze already defined.");
return maze;
}
Of course code can be written in more clear style, but main point is
new value assignment to the method parameter inside the method does not replace value of variable passed as parameter in the caller

Related

Printing an Array as a String with 10 elements per line

// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length

swapping of numbers using index in java is not working

package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}

Why doesn't this class execute properly?

Here is my first class called World
public class World {
private static char[][] world2D;
private int characterRow;
private int characterColumn;
public World(int width, int height){
world2D = new char[width][height];
characterColumn = 0;
characterRow = 0;
for(int i = 0; i < world2D.length; i++){
for(int j = 0; j < world2D[i].length; j++){
world2D[i][j] = '-';
}
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveUp(){
world2D[characterRow][characterColumn] = '-';
if (characterRow > 0){
characterRow -= 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveDown(){
world2D[characterRow][characterColumn] = '-';
if (characterRow < world2D.length){
characterRow += 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveRight(){
world2D[characterRow][characterColumn] = '-';
if (characterColumn < (world2D[characterRow].length - 1)){
characterColumn += 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveLeft(){
world2D[characterRow][characterColumn] = '-';
if (characterColumn > 0){
characterColumn -= 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public static void displayWorld(){
for(int i = 0; i < world2D.length; i++){
for(int j = 0; j < world2D[i].length; j++){
System.out.print(world2D[i][j]);
}
System.out.println();
}
}
}
Here is my second class called Driver
import java.util.Scanner;
public class Driver {
public static void main(String[]args){
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("How tall should the world be?: ");
int height = input.nextInt();
System.out.print("How wide should the world be?: ");
int width = input.nextInt();
World myWorld = new World(width,height);
World.displayWorld();
}
}
Why don't I need to call displayWorld specifically on the myWorld instance of the World class?
What if I created multiple World instances? This can't be right.
**edit for more detail
I want to call one of the class methods (i.e. moveUp or moveDown) on the instance of the World class myWorld object. However, I can't pass my reference to that object (myWorld) into those methods. I want to be able to call one of those methods, which changes the postion of 'P' in the 2 dimensional array and print it out using the methods that I have defined including the displayWorld method
Please refer to this link to learn more about static types.
If you want to display worlds of different instances, remove static from public static void displayWorld() and call myWorld.displayWorld().
Static variables, such as private static char[][] world2D, exist within a class, not objects of that class. This means they are accessed through the class name, not an instance name. Since you are initializing it in your constructor, it will be changed each time you create a new world, but the value will be the same for each instance. It looks like you should make the variable world2D non-static (just remove the static keyword) and do the same on the function displayWorld()
Then, the line World.displayWorld(); can be replaced with myWorld.displayWorld();

How to make an Array Accessible from instantiation in main class? Accessible to all classes in same class

I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance

Method Calling Issues Java

So i'm trying to call a method displayBoard in java that displays the boardgame once the user enters in a number initially in the main method. I'm unable to call this method. Does anyone see where i'm going wrong or how do i fix this? Thanks.
public static void displayBoard(int [] board, boolean showItem)
{
System.out.println();
System.out.print("_");
for (int val : board){
switch(codes){
case 2:
System.out.print("x");
break;
case 3:
System.out.print(" ");
break;
case 4:
System.out.print(showItem ? "Y" : " ");
break;
}
System.out.print("_");
} //for
System.out.println();
System.out.println();
}//display
public static void main (String [] args)
{
int guess = 0;
int userInput = promptForInt("Length Of board");
int [] numbers = new int[userInput];
int randomlocs = new Random().nextInt(userInput);
int val;
int display = displayBoard(board [], boolean showItem) // doesnt work?
boolean showItem = false;
while(! showItem)
{
val = promptForInt("Try Again!");
if(guess == randomlocation)
{
System.out.println("Found it!");
showItem = true;
}
else if(guess != randomlocs)
System.out.print(val);
}
}
Problem
You must pass values to the method call. Right now, you are passing declarations to the method, which isn't proper Java syntax
How To Fix
First, declare your showItem boolean before you call the method so you have a boolean to pass to the method. It should look like this:
boolean showItem = false;
int display = displayBoard(numbers, showItem)
This will pass the vakues stored in your numbers and showItem variables. We know the values stored in these specific variables (numbers and showItem) should be passed in due to the method's parameter names.
The statements leading up to that method call should look like this:
int userInput = promptForInt("Length Of board");
int [] numbers = new int[userInput];
boolean showItem = false;
int display = displayBoard(board [], boolean showItem);
int randomlocs = new Random().nextInt(userInput); //since this isn't used before the method call, it should be declared below it
int guess = 0; //same with this
int val; //and this

Categories

Resources