How to find the mode of an array using Java -
i'm trying find mode program, user inputs amount of numbers 0-100 many want, i'm attempting find mode of these numbers each time attempt find mode gives me 3, i've found else, need mode.
import java.util.scanner; public class deveation { public static void main(string args[]) { scanner kbreader = new scanner(system.in); int sum = 0; int bob[] = new int[101]; int total = 0; int = 0; int min = 0; int max = 100; int mode = 0; boolean stay_in_loop = true; while (stay_in_loop) { system.out.println("please enter interger(s) 0-100: "); int number = kbreader.nextint(); if (number < 0) { stay_in_loop = false; } else { total++; bob[number]++; } } int median = total / 2 + 1; while (median > 0) { median -= bob[a]; a++; } a--; boolean findit = true; while (findit) { if (bob[min] != 0) findit = false; else min++; } boolean findme = true; while (findme) { if (bob[max] != 0) findme = false; else max--; } (int p = 0; p < 101; p++) { if (bob[p] > mode) { mode = bob[p]; } (int j = 0; j < 101; j++) if (bob[j] <= mode) //i don't know why i'm getting 3 { } } (int = 0; < 101; i++) { sum += bob[i] * i; } system.out.println(sum); system.out.println(sum /= total); system.out.println(a); system.out.println(min); system.out.println(max); system.out.println(mode); //you should start putting down these comments } }
mode number(s) repeated often. rid of inner loop have.
for (int p = 0; p<101; p++) { if (bob[p]>mode) { mode=bob[p]; } }
i not sure why getting three. @ end of above loop, mode variable contain largest count number in bob array.
you can loop through list (or store values while looping through it) , print out numbers have count match value of mode.
for (int p = 0; p < 101; p++) { if (bob[p] == mode) { system.out.println("mode number: " + p); } }
remember mode can more 1 number.
Comments
Post a Comment