import acm.program.*;
import java.util.*;
public class ReverseArrayList extends ConsoleProgram {
public void run() {
println("This program reverses the elements in an ArrayList.");
println("Use 0 to signal the end of the list.");
ArrayList<Integer> list = readArrayList();
reverseArrayList(list);
printArrayList(list);
}
/* Reads the data into the list */
private ArrayList<Integer> readArrayList() {
ArrayList<Integer> list = new ArrayList<Integer>();
while (true) {
int value = readInt(" ? ");
if (value == 0) break;
list.add(value);
}
return list;
}
I dont understand the following code:
ArrayList<Integer> list = readArrayList();
I dont understand why I can't do the following instead:
list.getInput();
Why do i need to make the ArrayList equal to the method, and this confuses me because now I'm unsure which way is needed whenever I want to call a method in java
Your code shows that the method getInput() does not take in an ArrayList as argument, but returning it instead. So it is reasonable that
Arrlist=getInput()
Is the correct syntax, you are assigning the returned ArrayList from getInput() to Arrlist. While on the other hand,
Arrlist.getInput()
represents a method that must be implemented in ArrayList Class or one of its superclasses, which is not true in your case. I would recommend revising OOP concepts.
One way you might be able to pass it is using a constructor. I mocked up working code that does the same.
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ArrayListExample {
ArrayList<Integer> ofNumbers;
public ArrayListExample() {
ofNumbers = new ArrayList<>();
createArray();
}
private void createArray(){
ofNumbers = IntStream.range(0, 10)
.boxed()
.collect(Collectors
.toCollection(ArrayList::new));
}
public ArrayList<Integer> getInput() {
return ofNumbers;
}
public void getArray() {
ArrayList<Integer> newList = new ArrayList<>(ofNumbers);
for (Integer num : newList) {
System.out.println(num);
}
}
}
I also agree with Andrew. Keep it up, with a little more practice this will become second nature to you.
Related
import java.util.ArrayList;
import java.util.List;
public class arr {
public arr () {
// creat empty list
List<Integer> alpha = new ArrayList<>();
}
public static void main (String []args ) {
arr com1 = new arr();
arr com2= new arr();
//returning false but should be true the two are empty array
com1.equals(com2);
}
}
I am trying to create a class that can build a an empty array but when I am trying to compare the two-object its returning false , but the two have an empty arraylist so it should return true
You are trying to call a missing method called isEmpty().
You also need to move the list alpha as a field for the class, so that it can be accessed by the isEmpty() method.
To check for equality, just overload the equals() method.
Also as #Billy mentioned, you should override the hashCode too (so that it'll still work if you use hashSet/hashMap to store the arr class later on in your codes)
import java.util.ArrayList;
import java.util.List;
public class arr {
List<Integer> alpha = new ArrayList<>();
//creates the isEmpty method
boolean isEmpty() {return alpha.isEmpty();}
//check if two arr classes are the same
#Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass())
return false;
arr other = (arr) obj;
//checks if the alpha of this is the same as the alpha in obj
return alpha.equals(other.alpha);
}
//also override the hashCode method so that it'll work correctly for hash containers like hashMap and hashSet.
#Override
public int hashCode(){ return alpha==null?0: alpha.hashCode(); }
public static void main (String []args ) {
arr com1 = new arr();
arr com2= new arr();
//calling the isEmpty() method from the main.
System.out.println("com1 Empty? =" +com1.isEmpty());
//checks if com1 and com2 are equal
System.out.println("com1 same as com2? =" +com1.equals(com2));
}
}
You can use size() method to check Arraylist size. Checkout this for further reference: https://www.geeksforgeeks.org/arraylist-size-method-in-java-with-examples/
Your code is syntactically wrong.
class arr
Java convention says class names should be nouns, in mixed case with the first letter of each internal word capitalized. So lets assume it is named as ArrCreator
arr() is a method, so:
it must have a return type
it cannot be accessed in a static way, should be through an instance of ArrCreator class
since it create an empty List, not a empty Array, let renamed it to createEmptyList()
Naming still messy, but now at lest you can see it compiling (I hope)
import java.util.ArrayList;
import java.util.List;
public class ArrCreator
{
public List<Integer> createEmptyList()
{
// create empty list
List<Integer> alpha = new ArrayList<>();
return alpha;
}
public static void main(String[] args)
{
ArrCreator creator = new ArrCreator();
List<Integer> com1 = creator.createEmptyList();
List<Integer> com2 = creator.createEmptyList();
System.out.println(com1.equals(com2));
}
}
output: true
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>();
I need to be able to add a double value to an array list with a method. This is the one I created:
public void addPrice(double nPrice) {
if (nPrice >= 0) {
priceList.add(nPrice);
}
else {
priceList.add(null);
}
}
It is supposed to take the price that needs to be added as a parameter and not return anything. This price has to be at least 0. If the price is negative then nothing is done or added. I thought this would work but when I try the value 1.2 as my test dictates the value is not added to the least. Am I using the add operation wrong or is there something else I am missing?
I can't see all of your code so it's possible you're creating/accessing your ArrayList incorrectly.
ArrayList<Double> priceList = new ArrayList<>();
priceList.addPrice(1.2);
public void addPrice(double nPrice) {
if (nPrice >= 0) {
priceList.add(nPrice);
}
//Don't do anything if the price is not valid.
}
import java.util.ArrayList;
public class Tester{
public static void main(String[] args){
addPrice(1.2);
System.out.println(priceList.get(0));//this prints 1.2
}
/**
* Assuming you are using an arraylist like so.
* Remember to use a list you must use the class not
* just the primitive type.
*/
static ArrayList<Double> priceList = new ArrayList<>();
public static void addPrice(double nPrice) {
if (nPrice >= 0) {
priceList.add(nPrice);
}
else {
priceList.add(null);
}
}
}
I want to compare elements in two list using < > ==
Is it the right way to use intValue()?
List<Integer> a = new ArrayList<Integer>();
a.add(129);
List<Integer> b = new ArrayList<Integer>();
b.add(128);
if(a.get(0).intValue() > b.get(o).intValue()) {
// something
}
You're making it the right way.
As stated in the comments, you could also you compareTo().
An alternative to compareTo() is equals() which won't throw a NullPointerException in the case where the object is null.
Your way is correct. But with a small correction.
1)
a.get(0).intValue() == b.get(0).intValue()
2)
a.get(0).equals(b.get(0))
This is the problem in your code, you have to get(0), instead of get(1). Remember, in java it always start with 0.
Values can be compared using equals() or CompareTo method as well.
import java.util.ArrayList;
import java.util.List;
public class TestClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> a= new ArrayList<Integer>();
a.add(128);
List<Integer> b = new ArrayList<Integer>();
b.add(128);
if(a.get(0).intValue() == b.get(0).intValue()){
System.out.println("success");
}else{
System.out.println("failure");
}
if(a.get(0).equals(b.get(0))){
System.out.println("success");
}else{
System.out.println("failure");
}
}
}
So I'm making a search algorithm. I'm using a queue to store all of my objects
This is how I initialised it
Queue<Node> queue = new LinkedList<Node>();
I want to compare a variable in each object and order to queue. My plan is to use a for loop to compare the first object with each of the other objects and whichever object has the lowest variable is sent to the front of the queue. Then move onto the next object and repeat the process. My issue is I'm not sure how to retrieve an object from the queue that isn't the first object in the queue....
You could do a for loop through the Queue:
for (Node n : queue) {
do stuff with n
}
However, you aren't going to be able to remove items from the middle of the queue. Might I suggest a structure like an ArrayList?
In my opinion the best way is to use PriorityQueue. You can specify implementation of Comparator interface that will impose how elements should be sorted inside of queue.
Here is an example:
Let's say that this is your Node class:
public class Node {
// this field will be used to sort in queue
private int value;
public Node(int value) {
this.value = value;
}
public int getValue() {
return value;
}
#Override
public String toString() {
return "My value is: " + value;
}
}
And here is example of adding Nodes into queue:
import java.util.PriorityQueue;
import java.util.Random;
public class QueueExample {
public static void main(String[] args) {
Random r = new Random();
// Priority queue with custom comparator
PriorityQueue<Node> queue = new PriorityQueue<Node>(10, new SampleNodeComparator());
// adding 100 nodes with random value
for(int i = 0; i < 100; ++i) {
queue.add( new Node(r.nextInt(1000)));
}
// nodes will be removed from queue in order given by comparator
while(queue.size() != 0) {
System.out.println(queue.remove());
}
}
}
And the most important part - implementation of our custom comparator
import java.util.Comparator;
// our comparator needs to implements Comparator interface
public class SampleNodeComparator implements Comparator<Node> {
#Override
public int compare(Node o1, Node o2) {
/*
value that should be return from compare method should follow rules:
if o1 == o2 - return 0
if o1 > o2 - return any positive value
if o1 < 02 - return any negative value
*/
return o1.getValue() - o2.getValue();
}
}
When you run main method from QueueExample class you will see on console that values are removed from queue sorted by Node.value value.
Use Queue<E>#peek () to retrieve an object without removing it.
Some example code:
import java.util.*;
class Example {
public static void main (String[] args) throws Exception {
Queue<String> list = new PriorityQueue<>();
{ // Initialize the Queue
list.add ("Hello ");
list.add ("Mrs. ");
list.add ("DoubtFire! ");
}
System.out.println (list);
// Iterating through the Queue
String element;
while ( (element = list.peek()) != null) {
if (element.equals ("Mrs. ")) {
System.out.println ("\"Mrs\" found!");
}
System.out.println (element);
list.remove (element);
}
System.out.println (list); // Empty by now...
}
}
Output:
[DoubtFire! , Mrs. , Hello ]
DoubtFire!
Hello
"Mrs" found!
Mrs.
[]
Queue interface does not guarantee any particular order while iterating or polling so theoretically this task is impossible to implement with Queue.
Seeing your response to my comment, I think that in your case, you should use the PriorityQueue because it does what you need without needing you to reinvent the wheel, which is usually not recommended.
By default, the priority queue will use the default implementation of the compareTo method. Assuming that you have a composite type, you have two options:
You can make your custom class implement the Comparabale interface and have your sorting logic there.
Alternatively, you could pass your own comparator:
PriorityQueue<..> p = new PriorityQueue<..>(5, new Comparator<..>()
{
#override
public int compare(.. type1, .. type2)
{
//comparison logic done here.
}
}
You can take a look at this short tutorial for more information.