Reputation: 130
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.
Upvotes: 0
Views: 103
Reputation: 1454
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
Upvotes: 2