0

I recently started using ArrayLists instead of Arrays, so i wrote a simple program that should change all teh positive integers in an array to 1, negative to -1 and all the 0's to 0. Now I don't know why but my code isn't working, could you please point me to the right direction since I am not yet experienced with ArrayLists? Here is my code:

private static ArrayList<Integer> ja = new ArrayList<Integer>();
private static String j = null;
private static void keskmine() {
    System.out.println("Please enter an array of integers:");
    j = sc.nextLine();
    ArrayList<String> bitsj = new ArrayList<String>(Arrays.asList(j.split(",")));
    for(int i = 0; i < bitsj.size(); i++){
        ja.add(Integer.parseInt(bitsj.get(i).trim()));
    }
    for(int i = 0; i < ja.size(); i++){

        if(ja.get(i) > 0){
            ja.set(i, 1);
        }if(ja.get(i) < 0){
            ja.set(i, -1);
        }else{
            ja.set(i, 0);
        }
    }
    System.out.println(ja);
}

Thank you in advance!

EDIT: I am so sorry, I forgot to post half that I intended to! For example if I am giving my program an input "1, 1, 1" It outputs 0, 0, 0 but it should output "1, 1, 1" and it does that to whatever I enter.

4
  • 2
    What is ja? Why aren't you using a foreach loop? Commented Oct 5, 2014 at 20:22
  • 2
    What's ja? Where is it defined? Commented Oct 5, 2014 at 20:23
  • 2
    "isn't working" doesn't tell us anything about what you expect to see or what you actually see. Please provide a short but complete program demonstrating the problem, ideally not requiring user input, and specifying what you expect to happen vs what's happening. Commented Oct 5, 2014 at 20:23
  • Have you heard of the for (<Type> element : <list>) syntax? Commented Oct 5, 2014 at 20:31

1 Answer 1

2

in this check

if(ja.get(i) > 0){
    ja.set(i, 1);
}
if(ja.get(i) < 0){
     ja.set(i, -1);
}else{
    ja.set(i, 0);
}

an else is missing. correct it to

if(ja.get(i) > 0){
    ja.set(i, 1);
} else if(ja.get(i) < 0){
     ja.set(i, -1);
} else {
    ja.set(i, 0);
}



you are currently first checking, if the number is greater than 0. after that you always check, if the number is smaller than 0.

eg: you have a 42:
check if > 0 => entry set to 1
after that: check if < 0 => false, so set to 0

Sign up to request clarification or add additional context in comments.

1 Comment

And that just solved it! I thought something was messed up when I was splitting the ArrayList but it was just this else if... Thank you for your help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.