ArrayUtils has a bug? it does actually delete but [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
In case You want to test it your self:
[link]https://gist.github.com/anonymous/091750563384024e0ffa
[link]https://gist.github.com/anonymous/1f05cdd1d1685d103326
Everything worked fine in deleteItem function it deleted what i wanted, but when i tried to see the array again it shows the original array again even though I already return a new array
public static ItemTracker[] deleteItem(ItemTracker[] listItems) {
for(int i = 0; i < listItems.length; i++) {
if (listItems[i] == null) {
break;
} else if(input.equalsIgnoreCase("Everything")){
listItems = ArrayUtils.remove(listItems, i); // ArrayUtils is actually deleting it but... see output in other function
System.out.println("Content of Array : " + Arrays.toString(listItems)); // It deleted the index that i want and return a new array
// return listItems; I tried to return here as well but same result
}
}
}
return listItems; // which is here
}
Original array: [naufal,joker,batman,null,null,null,null,null,null,null]
Output after delete items, I'm deleting joker as in index 1:
[naufal,batman,null,null,null,null,null,null,null]
It worked but..
After i run displayArray method:
public static void displayArray(ItemTracker[] listItems)
System.out.println("Content of Array : "
+ Arrays.toString(listItems));
}
I get:
[naufal,joker,batman,null,null,null,null,null,null,null]
same array;
I posted multiple of same questions, and tried all the solutions from people here but it doesn't work. What is the real problem over here?, seems like i couldn't of anything else.
For the sake of this problem this only applies to array not List or ArrayList

In your code at:
case 3:
deleteItem(listItems);
break;
you forgot to assign the returned array to listitems:
case 3:
listItems=deleteItem(listItems);
break;

Related

Does print statement in java effect any variables (without using increment)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I was trying out the leetcode problem here
the code i wrote is
public int toLeaf(TreeNode j){
int ans=1;
try{
ans= Math.max(toLeaf(j.left),toLeaf(j.right))+1;
}catch(Exception e){
}
return ans;
}
public int diameterOfBinaryTree(TreeNode root) {
return toLeaf(root);
}
which gave me wrong answer but as soon as added a print statment i got correct answers on the sample testcases
public int toLeaf(TreeNode j){
int ans=1;
try{
ans= Math.max(toLeaf(j.left),toLeaf(j.right))+1;
}catch(Exception e){
}
System.out.println(j.val+" "+ans); //here
return ans;
}
public int diameterOfBinaryTree(TreeNode root) {
return toLeaf(root);
}
what is the reason behind this?
here is the screenshot
rejected
The printing is not the cause of the different behaviour but the access of j.val is.
If you had proper null-checks in your code, e.g. if (j == null) { return 0; } in the beginning of the method this would not happen.
In the first snippet if you call the method with j = null you get an NPE in the try, catch it, ignore it and then return 1. The caller will get the 1, add 1 and then return 2.
In the second snippet if you call the method with j = null you once again get an NPE in the try, ignore it, then continue to the print which raises another NPE which is then thrown from the method and the recursive caller will catch it and not perform the ans = ... + 1 successfully but simply return 1.
Therefore you have a different behaviour between the two snippets. But this is entirely unrelated to printing itself.

Projekt Hangman game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner in Java and I am working right now with a small projekt, a hangman game. One of the functions I am working on right now is a method where it takes a char input, check if the input is already added to the list or not, if it is, a message will show up saying "You have already used that character!" and the user will have to guess again, otherwise the input will be added to the list. My issue right now is that nothing is happening, inputs are not added to the list at all.
This is what I have done so far:
Any advice/help would be appreciated!
public static ArrayList<Character> getGuesses(ArrayList<Character> allGuesses, char input){
for (int i = 0; i < allGuesses.size(); i++) {
if (allGuesses.get(i) == input) {
System.out.println("You have already used that character!");
}else {
allGuesses.add(input);
}
}
return allGuesses;
}
You are adding the input character on each iteration as you search the collection. You should only add it after you have searched the collection and not found it.
for (int index = 0 ; index < allGuesses.size() ; ++index) {
if (allGuesses.get(index) == input) {
System.out.println("You already used that character!");
return allGuesses;
}
}
allGuesses.add(input);
return allGuesses;
However, this can be simplified by using the Collection contains method such that you do not employ a loop.
if (allGuesses.contains(input)) {
System.out.println("You already used that character!");
return allGuesses;
}
allGuesses.add(input);
return allGuesses;
If possible, consider switching the type of allGuesses to a Set implementation (e.g. HashSet). A Set seems to better match how you are using your collection and allows you to reduce this method to...
if (! allGuesses.add(input)) {
System.out.println("You already used that character!");
}
return allGuesses;

Java if statements issue [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Old:
if (inv != troll) {
System.out.println("Rock " + a);
}
if (hañ != troll) {
System.out.println("Doll " + b);
}
if (tall != troll) {
System.out.println("Mirror " + c);
}
if (troll != troll) {
System.out.println("Note " + d);
}
End();
f++;
Updated:
if (!inv.equals(troll)) {
System.out.println("Rock "+ a);}
if (!hañ.equals(troll)) {
System.out.println("Doll "+ b);}
if (!tall.equals(troll)) {
System.out.println("Mirror "+ c);}
if (!high.equals(troll)) {
System.out.println("Note "+ d);}
End();
f++;
I am doing a text adventure game and the items belonging in the if statements are arrays, the a b c d are random numbers generated which are sort of a password needed. Right here I am trying to display my inventory, so I want to know if there is any way for the conditions inside the if statement to be displayed as independents. In the sense that if the first is true it displays the first and if the second is not it only displays the ones that are true and then it goes to the method end. The problem I have is that right now all are false, but it still displays all of them except the last one.
I tried adding this in to my code which was given to me in the answers I am sorry I am editing the question its just that i don't know how to comment correctly. Concerning the answer now I am not sure if I am supposed to create a method for equals(); and if so what it should include. But using the updated code it still shows me the array lists even though inv for example has "Rock" inside the array and troll has no words in it.
What I am trying to do is so that if the arrays has somehting inside it displays the value, so I created troll as an extra empty array that has no given value.
To check if the List is empty use isEmpty():
if (!inv.isEmpty()) {
}
Yes they are all declared in the class as, List inv = new ArrayList(); List hañ = new ArrayList(); List tall = new ArrayList(); List high = new ArrayList(); List troll = new ArrayList();
What I am trying to do is so that if the arrays has somehting inside it displays the value, so I created troll as an extra empty array that has no given value
If you initialize your variable this way and you just want to see if this is empty. you can do:
tall.isEmpty();
to check if it is empty.
But to be honest, this logic is not efficient. it will be better if you just create an object class of inventory with the following as attribute. It will be easier to handle everything.

Sort Objects From a File [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
(At time of posting, I do not have access to code, will add later)
I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.
When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.
This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.
So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you
static void employeeSort(Employee[] emply, int size)
{
int i;
Employee temp;
boolean flag = true;
while(flag)
{
flag = false;
for(i = 0; i < size; i++)
{
if (emply[i].getName().compareTo(emply[i+1].getName())>0)
{
System.out.println(emply[i].getName());
temp = emply[i];
emply[i] = emply[i+1];
emply[i+1] = temp;
flag = true;
}
}
}
}
On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.
public class Employee implements Serializable
{
int prefHours;
String name;
String avail;
Employee( String nam, int hours, String aval )
{
name = nam;
prefHours = hours;
avail = aval;
}
void prnEmpl()
{
System.out.print("Name: " + name);
System.out.println();
System.out.print("Prefered hours: " + prefHours);
System.out.println();
System.out.print("Availability: " + avail);
System.out.println();
}
String getName()
{
return name;
}
String getAvail()
{
return avail;
}
}
Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.

Syntax error in calling a method java (newbie) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The 2 answers posted both fixed it. thank you very much and i am embarrassed by how simple it was.
sorry for posting such a basic question and thank you for your time.
From the menu method at the top i wish to call 2 different methods to complete an action based on the input. i cannot find anywhere how to call a void method.
I don't know why the second one wont work as i used a similar thing earlier on.
public void CheckOutMenu(ArrayList basket )
{
choice = 0;
while ( choice !=4 ) {
Scanner in = new Scanner ( System.in);
{
switch(in.nextInt()){
//print the number of items in the basket
case 1:
//working
break;
case 2:
//dont know how to call on option 2 the listBasket method
break;
case 3:
//to call the method
//error and wont compile
double totalCost = CalcTotalCost(totalCost = 0);
//printing what the method returns
System.out.print("The total price of your basket is £" );
break;
case 4:
choice = 4;
break;
default:
System.out.println("please enter a whole number that represents you're choice");
}
}
}
}
protected void listBasket(ArrayList basket )
{
//code inside works fine
}
public double CalcTotalCost(double total, ArrayList basket)
{
//code inside works fine
return total;
}
you can call a void method like any other method, except that you don't have to do anything with the return value because there isn't one.
case 2:
listBasket(basket);
break;
for your third case, you have to pass in both a double and an ArrayList if you want to pass 0 as your double, than you can just post a double literal.
case 3:
/* if you don't want totalCost to go out of scope right away,
* declare it above the switch statement */
double totalCost = CalcTotalCost(0.0, basket);
...
break;
Your error is here, as I'm sure you know:
double totalCost = CalcTotalCost(totalCost = 0);
However, your CalcTotalCost method is defined thus:
public double CalcTotalCost(double total, ArrayList basket)
You've sent it the total, but you haven't sent it a basket.

Categories

Resources