The idea is if i am at a certain stair i can either go one step down or two so if am at stair 3 i can go down 1 1 1 or 2 1 for example. My code should print all the possibilities. The error I get is that I can't convert the add function to an array (since the add method is a boolean). What is wrong with this algorithm?
public class Stairs {
public static void staircase (int height ){
ArrayList<Integer> Array = null;
explore (height,Array);
}
public static void explore(int objheight,ArrayList<Integer>Array){
int intialheight = 0;
if (intialheight == objheight){
Array.toString();
}
else{ if (objheight > intialheight ){
explore(objheight-2,Array.add(2));
explore(objheight-1,Array.add(1));
}
}
after your feedback I am getting an empty output
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Stairs {
public static void staircase (int height ){
ArrayList<Integer> Array = new ArrayList<Integer>();
explore (height,Array);
}
public static void explore(int objheight,ArrayList<Integer>Array){
int intialheight = 0;
if (intialheight == objheight){
Array.toString();
}
else{ if (objheight > intialheight ){
Array.add(2);
explore(objheight-2,Array);
Array.add(1);
explore(objheight-1,Array);
}
}}
public static void main (String args[]){
staircase(3);
}
}
The method add(E e) in ArrayList returns true upon appending the element e passed as a parameter to the end of the ArrayList.
Your method, explore(int objHeight, ArrayList<Integer> Array) does not accept a boolean for its second parameter. Yet, in that same method, explore, you are recursively calling explore and passing in a boolean to the method.
The following code should be modified to first invoke the add method of Array and then pass Array to the explore method.
Before:
explore(objheight-2,Array.add(2)); This code is passing parameters int and boolean to the explore method, which is not the parameters it accepts. You should instead attempt the following.
After:
Array.add(2);
explore(objheight-2,Array); This code first adds 2 to the Array and then passes the Array to the explore method without invoking any further methods on the Array object.
You will also need to do this for the next line of code, where you have explore(objheight-1,Array.add(1));.
Edit: Upon further examination of the code, I discovered another (sooner) error that occurs. A NullPointerException will occur each time the program runs:
ArrayList<Integer> Array = null;
explore (height,Array);
Then inside the explore method, different methods on Array are invoked, despite Array always being null:
Array.toString();, Array.add(2) and Array.add(1).
The Array object must be initialized inside of either the staircase or explore methods.
ArrayList<Integer> Array = new ArrayList<Integer>(); or ArrayList<Integer> Array = null;
Array = new ArrayList<Integer>();
Related
What I want to do: read strings from keyboard using Scanner until specific string is used to break the infinite loop. save them in an arrayList, then pass them into an array with its length beeing the number of the iteration of the loop
public class InputReader {
ArrayList<Integer> list = new ArrayList<>(0);
int arrayLength;
String readInput;
Scanner ir = new Scanner(System.in);
void readInput() {
for (int m=0; ;m++) {
readInput = ir.nextLine();
if ("q".equals(readInput)) {
//problem: arrayLength does not have the value of m outside the loop
arrayLength = m;
break;
}
System.out.println("arrayLength: "+arrayLength);
intInput = Integer.parseInt(readInput);
list.add(intInput);
}
}
int[] array = new int[arrayLength];
}
}
Inside the loop arrayLength works perfectly but outside the loop it has no value as I initialized it without value. Because of this,
System.out.println("array.length: "+array.length);
always returns 0 and the compiler returns this error:
java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
when I try to save integers inside the array.
1) How can I make the changes to the variable stay outside the loop?
2) Weird observation A:
int[] array = new int[list.size()];
returns the same error despite list.size() having the right value even outside the loop (checked by printing it).
And B: The code works if I create my array inside another method instead of inside the class and then use it in the method, but this way I cannot use it in my other classes despite using inheritance or parameters.
void giveOutput() {
int[] array = new int[list.size()];
public void giveOutput () {
System.out.println("list.size()"+list.size());
System.out.println("array.length:"+array.length);
for (int n=0; n<list.size(); n++) {
array[n] = list.get(n);
System.out.print("array["+n+"]:"+array[n]+" ");
}
}
}
this creates a working array but I cant hand it over to my Minsort extends InputReader subclass where it is sorted which leads to question number
3) How to use variables initialized in methods in other classes? This way my program could work too.
(I am a bloody beginner, started seriously working with java yesterday, my first succesful project was a Minsort-Algorithm I wrote from scratch so please have mercy. And thanks in advance.)
The array array is initialized when an object of the type InputReader is instantiated, not after the readInput() method is run.
In other words, array is always initialized when you use new InputReader(), not after the readInput() method is run. That means that the arrayLength variable has not yet been modified at the moment when array is created, so the default value for an int is used, which is 0.
Try this:
public static class InputReader {
ArrayList<Integer> list = new ArrayList<>(0);
int arrayLength;
String readInput;
Scanner ir = new Scanner(System.in);
int[] array;
void readInput() {
for (int m=0; ;m++) {
readInput = ir.nextLine();
if ("q".equals(readInput)) {
//problem: arrayLength does not have the value of m outside the loop
arrayLength = m;
break;
}
int intInput = Integer.parseInt(readInput);
list.add(intInput);
}
System.out.println("arrayLength: "+arrayLength);
array = new int[arrayLength];
}
}
Also, your System.out.println("arrayLength: "+arrayLength); always returned 0 because the arrayLength changes only when q is pressed.
To answer your third point: You could create a getter function in the class InputReader. For example:
public int[] getArray() {
return array;
}
As a side-note: It is very good practice to have your instance variables be declared with a private access modifier, and to then create public getter and setters. This is called Encapsulation, and is an OOP principle (my advice is that you google the OOP principles).
More info about getters and accessors here: Why use getters and setters/accessors?
I found an exercise in a book that adds some money into an ArrayList, and then reverses them. I know we can easily use Collection.reverse(), which is what my textbook shows, but I found another cool solution online that I am trying to understand but having trouble with.
Heres the code:
class Purse {
private ArrayList<String> coins = new ArrayList<String>();
public void addCoin(String coinName) {
coins.add(coinName);
}
public void reverse() {
for(int start = 0, end = coins.size() - 1; start < coins.size() / 2; start++, end--) {
swap(start,end,coins);
}
}
private void swap(int starting, int ending, List aList) {
Object temp = aList.set(starting, aList.get(ending));
aList.set(ending,temp);
}
public String toString() {
return "Purse: " + coins;
}
}
public class PurseDemo {
public static void main(String [] args) {
Purse purseObj = new Purse();
purseObj.addCoin("Quarter");
purseObj.addCoin("Dime");
purseObj.addCoin("Penny");
purseObj.addCoin("Nickel");
System.out.println(purseObj);
purseObj.reverse();
System.out.println(purseObj);
}
}
Here is where my confusion is:
Object temp = aList.set(starting,aList.get(ending));
aList.set(ending,temp);
First of all, I think I get the idea of this. However, this is my first time seeing the Object keyword. What I don't really get is what temp actually represents ( I got this code off online, in my book they havent introduced this keyword Object yet)
Here are my thoughts on an example iteration
Suppose our arrayList has
[Quarter,Dime,Penny,Nickel]
According to Object temp = aList.set(starting,aList.get(ending));
We take the the first spot in the ArrayList Quarter and put the value of nickel in there. So we get the ArrayList
[Nickel,Dime,Penny,Nickel]
Now I'm kind of confused.. When I system.out.println(temp), it tells me the values are Quarter and Dime. But why? Can someone go through an example iteration with me?
AFTER READING ANSWER
[Quarter,Dime,Penny,Nickel]
Nickel replaces Quarter, thus temp is Quarter. So we add Quarter to the end
I.E we get
Quarter,Dime,Penny,Quarter
Wait.. But where did our nickel go?!
The set() method returns the object that is being displaced by the new object. The first line
Object temp = aList.set(starting,aList.get(ending));
is the same as:
Object temp = aList.get(starting);
aList.set(starting, aList.get(ending));
You could actually do it without the temp variable, in one line:
aList.set(ending, aList.set(starting, aList.get(ending)));
The swap method can be translated into its "usual form":
Object temp = aList.get(starting);
aList.set(starting, aList.get(ending));
aList.set(ending, temp);
All the code you found does is combine the first two lines because List.set promises to return the replaced value.
Now let's see your example, where aList initially is [Quarter,Dime,Penny,Nickel], and starting is 0 and ending is 3.
Object temp = aList.get(starting);, now temp is Quarter.
aList.set(starting, aList.get(ending));, now aList is [Nickel,Dime,Penny,Nickel].
At last, aList.set(ending, temp);, sets the last element of aList to Quarter: [Nickel,Dime,Penny,Quarter]
when I was writing my program I came across a problem with arrays and can't find any explanations on how to fix it.
The problem i ran into is how i should go about using an array from the main a method and passing it to a method, but only getting one value as a return rather than the whole array again.
note: the way i have my program set up the array is filled with random numbers every time it is ran.
im not too sure if you can do this or not, but
The way i am currently calling a method is by doing as follows:
"declared variable (not array)" = "name of method" ("the actual array name")
totalSum = sumTotal (randomArray) // example
The method I'm trying to call:
public static int[] sumTotal (int[] totals) {
int total = 0;
for (int i = 0; i < totals.lenght; i++) {
total += totals[i];
}
return total;
}
it keeps giving me a "cannot find symbol
symbol : method sumTotals(int[])
location: class oneDimensionArraysNew"
error when i try to compile,
im not too sure how i would go about fixing this, I appreciate any and all help!!
Here you say, the return value is array of int : public static int[] sumTotal...
Just change it to : public static int sumTotal...
public static int[] sumTotal(int[] totals {
...
}
The return type should be int, not int[].
public static int sumTotal(int[] totals {
...
}
So I'm creating a class called dicegame. Here's the constructor.
public class dicegame {
private static int a, b, winner;
public dicegame()
{
a = 0;
b = 0;
winner = 2;
}
And now in the main, I'm creating an array of this object (I called it spaghetti for fun).
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[10];
spaghetti[1].roll();
}
But when I try to do anything to an element in the array, I'm getting the NullPointerException. When I tried to print one of the elements, I got a null.
You created an array, but you have to assign something (e.g. new dicegame()) to each element of the array.
My Java is slightly rusty, but this should be close:
for (int i=0; i<10; i++)
{
spaghetti[i] = new dicegame();
}
new dicegame[10]
just creates an array with 10 empty elements. You still have to put a dicegame in each element:
spaghetti[0] = new dicegame();
spaghetti[1] = new dicegame();
spaghetti[2] = new dicegame();
...
You need spaghetti[1]=new dicegame() before you call roll() on it.
Right now you are allocating an array,but don't. Place any objects in this array, so by default java makes them null.
1.you have just declared the array variable but not created the object yet. try this
2.you should start index with zero not with one.
dicegame[] spaghetti = new dicegame[10]; // created array variable of dicegame
for (int i = 0; i < spaghetti.length; i++) {
spaghetti[i] = new dicegame(); // creating object an assgning to element of spaghetti
spaghetti[i].roll(); // calling roll method.
}
Firstly,you should create object for every spaghetti input of yours.
You can start with whatever value you want. Just be sure that the size of array is matched accordingly so that you won't get ArrayIndexOutOfBounds Exception.
So,if you wanted to start with 1 and have 10 objects of the class dicegame,you will have to assign the size of the array as 11(since it starts from zero).
your main function should be like :
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[11];
//the below two lines create object for every spaghetti item
for(int i=1;i<=11;i++)
spaghetti[i]=new dicegame();
//and now if you want to call the function roll for the first element,just call it
spaghetti[1].roll;
}
Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)