Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change value of array element to 5 if it's equal to 4 and inform number of changes?

Tags:

java

arrays

The array x={2, 3, 4, 4, -5, 4, 6, 2} the resulting array is to be x={2, 3, 5, 5, -5, 5, 6, 2}, and the number of changes reported with a message like "The number of changes is 3" printed on screen.

public class anArray {
    public static void main(String[]args) {
        int [] x = {2, 3, 4, 4, -5, 4, 6, 2};

        for (int i=0; i<x.length; i++) {
            System.out.println(x[i]);   
        }    //currently only I am able to print whole array element
    }
}
like image 366
h_club_uk Avatar asked Sep 02 '25 18:09

h_club_uk


1 Answers

public class anArray {
    public static void main(String[]args) {
        int [] x = {2, 3, 4, 4, -5, 4, 6, 2};
        int count =0;
        for (int i=0; i<x.length; i++) {
            if (x[i] == 4) {
                count++;
                x[i]=5;
            }
        }
        system.out.println("...."+count);
    } //main()
} //anArray
like image 136
Churk Avatar answered Sep 04 '25 07:09

Churk