163k views
3 votes
Write a Java program that prompts the user to enter a sequence of non-negative numbers (0 or more), storing them in an ArrayList, and continues prompting the user for numbers until they enter a negative value. When they have finished entering non-negative numbers, your program should return the mode (most commonly entered) of the values entered.

1 Answer

1 vote

Answer: provided in explanation segment

Step-by-step explanation:

the code to carry out this program is thus;

import java.util.ArrayList;

import java.util.Scanner;

public class ArrayListMode {

public static int getMode(ArrayList<Integer>arr) {

int maxValue = 0, maxCount = 0;

for (int i = 0; i < arr.size(); ++i) {

int count = 0;

for (int j = 0; j < arr.size(); ++j) {

if (arr.get(j) == arr.get(i))

++count;

}

if (count > maxCount) {

maxCount = count;

maxValue = arr.get(i);

}

}

return maxValue;

}

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

ArrayList<Integer>list= new ArrayList<Integer>();

int n;

System.out.println("Enter sequence of numbers (negative number to quit): ");

while(true) {

n=sc.nextInt();

if(n<=0)

break;

list.add(n);

}

System.out.println("Mode : "+getMode(list));

}

}

⇒ the code would produce Mode:6

cheers i hope this helps!!!!

User Samir Alajmovic
by
4.5k points