Why is this program not detecting the mode correctly? - java

I have a program that finds the mode of an array. Here is the code:
System.out.print("How many numbers do you want to find the mode of? ");
double[] inputs = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
Arrays.sort(inputs);
int count2 = 0;
int count1 = 0;
double popular1 = 0;
double popular2 = 0;
//finds most popular value in the array
for(int i = 0; i < inputs.length; i++) {
popular1 = inputs[i];
count1 = 1;
for(int j = i + 1; j < inputs.length; j++) {
if(popular1 == inputs[j]) {
count1++;
}
}
if(count1 > count2) {
popular2 = popular1;
count2 = count1;
} else if(count1 == count2) {
popular2 = Math.min(popular2, popular1); //when there are two winners, the lowest one is the mode
}
}
finalans = "The mode of those " + inputs.length + " numbers is " + popular2 + ", with a staggering " + count1 + " appearances.";
return finalans;
However when ran, I'm not getting the desired output. 1st, it doesn't count correctly, 2nd, it doesn't always detect which number is the mean. Just in case it is necessary, the full program is below.
import java.util.Arrays;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean again = true;
while(again == true) {
System.out.println(runMath());
System.out.println("Do you want to run again? true or false");
again = scanner.nextBoolean();
}
scanner.close();
}
public static String runMath() {
double solution1;
double solution2;
String finalans;
Scanner scanner = new Scanner(System.in);
System.out.println("Operation ID? 1 = Add, 2 = Sub, 3 = Mul, 4 = Div, 5 = Ave");
int ID = scanner.nextInt();
solution1 = 0;
solution2 = 0;
switch (ID) {
case 1: {System.out.println("How many numbers do you want to add?");
double[] inputs = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
for(int i = 0; i < inputs.length; i++) {
solution1 += inputs[i];
}
finalans = "The sum of those " + inputs.length + " numbers is " + solution1;
return finalans;}
case 2: {System.out.println("How many numbers do you want to subtract?");
System.out.println("All numbers are subtracted from the first number, in inputted order.");
double[] inputs = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
solution1 = inputs[0];
for(int i = 1; i < inputs.length; i++) {
solution1 -= inputs[i];
}
finalans = "The difference of those " + inputs.length + " numbers is " + solution1;
return finalans;}
case 3: {System.out.println("How many numbers do you want to multiply?");
double inputs[] = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
solution1 = inputs[0];
for(int i = 1; i < inputs.length; i++) {
solution1 *= inputs[i];
}
finalans = "The product of those " + inputs.length + " numbers is " + solution1;
return finalans;}
case 4: {System.out.println("How many numbers do you want to divide?");
System.out.println("All numbers are subtracted from the first number, in inputted order.");
double[] inputs = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
solution1 = inputs[0];
for(int i = 1; i < inputs.length; i++) {
solution1 /= inputs[i];
}
finalans = "The quotient of those " + inputs.length + " numbers is " + solution1;
return finalans;}
case 5: {System.out.println("How many numbers do you want to average?");
double[] inputs = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
for(int i = 0; i < inputs.length; i++) {
solution1 += inputs[i];
}
solution1 /= inputs.length;
finalans = "The mean of those " + inputs.length + " numbers is " + solution1;
return finalans;}
case 6: {System.out.println("How many numbers do you want to find the median of?");
double[] inputs = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
Arrays.sort(inputs);
if(inputs.length % 2 == 0) {
solution1 = (inputs[inputs.length / 2] + inputs[inputs.length / 2 - 1]) / 2;
} else solution1 = inputs[inputs.length / 2];
finalans = "The median of those " + inputs.length + " numbers is " + solution1;
return finalans;}
case 7: {System.out.println("How many numbers do you want to find the mode of? ");
double[] inputs = new double[scanner.nextInt()];
for(int i = 0; i < inputs.length; i++) {
System.out.println("Input number " + i);
inputs[i] = (double) scanner.nextDouble();
}
Arrays.sort(inputs);
int count2 = 0;
int count1 = 0;
double popular1 = 0;
double popular2 = 0;
//finds most popular value in the array
for(int i = 0; i < inputs.length; i++) {
popular1 = inputs[i];
count1 = 1;
for(int j = i + 1; j < inputs.length; j++) {
if(popular1 == inputs[j]) {
count1++;
}
}
if(count1 > count2) {
popular2 = popular1;
count2 = count1;
} else if(count1 == count2) {
popular2 = Math.min(popular2, popular1); //when there are two winners, the lowest one is the mode
}
}
finalans = "The mode of those " + inputs.length + " numbers is " + popular2 + ", with a staggering " + count1 + " appearances.";
return finalans;}
default: return "ur mom";
}
}
}
Thank you to any geniuses that might solve this!

One thing I've noticed in your code that you use count1 as a temporary container for your current loop. So you should use count2 in your finalans instead of count1.
finalans = "The mode of those " + inputs.length + " numbers is " + popular2 + ", with a staggering " + count2 + " appearances.";

Related

Is there perhaps a way of finding the above and below average

I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}
This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}
Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}
You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}
Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}

This program should ask user for the max num to print out to and then calculate each number starting from 1 to the maximum along with it squared

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());

The variable sum in the while loop is concating and not adding

Here's my code:
public static int baseB2int(String number, int base)
{
int product = 0;
int num = Integer.parseInt(number);
int sum;
int i = number.length();
int[] theNumber = new int[i];
for (int j = 0; j < number.length(); j++)
{
System.out.println("the length of number is " + number.length());
theNumber[j] = num%base;
System.out.println("theNumber["+j+"] is " + theNumber[j]);
num = num/base;
System.out.println("the num is "+num);
}
sum = theNumber[i - 1];
System.out.println("the sum is " + sum);
while (i > 0)
{
product = sum * base;
System.out.println("The product in the while loop is " + product);
System.out.println("theNumber[previous]" + theNumber[i-1]);
sum = product + theNumber[i-1];
System.out.println("the sum in the while loop is " + sum);
i--;
}
return product;
}

string multiplication using a big integer class

I'm trying to write a code that multiplies two strings of integers. I'm not too sure where it's going wrong... It works for some numbers, but is horribly wrong for others. I'm not asking for a full solution, but just a hint (I seriously appreciate any help possible) as to where I'm making the obviously silly mistake. Thanks in advance.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a big integer. ");
String t = scan.nextLine();
System.out.print("And another. ");
String s = scan.nextLine();
BigInt a = new BigInt(t);
BigInt b = new BigInt(s);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
}
}
class BigInt {
public BigInt() {
n = new int[1];
}
public BigInt(String s) {
n = new int[s.length()];
for (int i = 0; i < n.length; ++i) {
n[n.length - i - 1] = s.charAt(i) - '0' ;
}
}
private BigInt(int[] n) {
this.n = new int[n.length];
for (int i = 0; i < n.length; ++i) {
this.n[i] = n[i];
}
}
public String toString() {
String s = "";
for (int i : n) {
s = i + s;
}
return s;
}
public BigInt mul(BigInt o) {
int carry = 0;
int s = 0;
int digit;
int subtotal = 0;
int total = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[n.length + o.n.length];
for (int i = 0; i < o.n.length; ++i) {
int bottom = i <= o.n.length ? o.n[i] : 0;
for (s = 0; s <= n.length; ++s){
int top = s < n.length ? n[s] : 0;
int prod = (top * bottom + carry);
if (s == (max-1)) {
total = Integer.valueOf((String.valueOf(prod) + String.valueOf(subtotal)));
carry = 0;
digit = 0;
subtotal = 0;
break;
}
if (prod < 10) {
digit = prod;
subtotal += digit;
carry = 0;
}
if (prod >= 10); {
digit = prod % 10;
carry = prod / 10;
subtotal += digit;
}
}
result[i] = total;
}
return new BigInt(trim(result));
}
private int[] trim(int[] nums) {
int size = nums.length;
for (int i = nums.length - 1; i > 0; --i) {
if (nums[i] != 0) {
break;
}
--size;
}
int[] res = new int[size];
for (int i = 0; i < size; ++i) {
res[i] = nums[i];
}
return res;
}
private int[] n;
}
A quick test using:
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
System.out.println(x + " * " + y + " = " + new BigInt(Integer.toString(x)).mul(new BigInt(Integer.toString(y))));
}
}
demonstrates that somehow your multiply of x * y is actually multiplying by 10x * y. That should give you a clear hint to the problem.

How do you find the minimum and maximum to see if they match?

How do you find the minimum and maximum to see if they match? But the thing I'm finding the minimum and maximum for integers that are not an array. I need to find the minimum and maximum of the averages and compare them. So far I have this:
int i;
int totalall = 0;
int total1 = 0;
int total2 = 0;
int total3 = 0;
int total4 = 0;
int min1 = Integer.MAX_VALUE, minIndex = 0;
int max1 = Integer.MIN_VALUE, maxIndex = 0;
int average1 = 0;
int average2 = 0;
int average3 = 0;
int average4 = 0;
System.out.print("Please enter the sample size: ");
int max = input.nextInt();
int[]arr0 = new int[max + 1];
int[]arr1 = new int[max + 1];
int[]arr2 = new int[max + 1];
int[]arr3 = new int[max + 1];
System.out.println("Enter numbers for Trial 0 ");
for (i = 1;i <= max;i++){
System.out.print("Enter sample #" + (i-1) + ":");
arr0[i-1]= input.nextInt();
total1 = total1 + arr0[i-1];
}
System.out.println("Enter numbers for Trial 1 ");
for (i = 1; i <= max; i++){
System.out.print("Enter sample #" + (i-1) + ":");
arr1[i-1] = input.nextInt();
total2 = total2 + arr1[i-1];
}
System.out.println("Enter numbers for Trial 2 ");
for (i = 1; i <= max; i++){
System.out.print("Enter sample #" + (i-1) + ":");
arr2[i-1] = input.nextInt();
total3 = total3 + arr2[i-1];
}
System.out.println("Enter numbers for Trial 3 ");
for (i = 1; i <= max; i++){
System.out.print("Enter sample #" + (i-1) + ":");
arr3[i-1] = input.nextInt();
total4 = total4 + arr3[i-1];
}
totalall += total1 + total2 + total3 + total4;
average1 = total1 / (i-1);
average2 = total2 / (i-1);
average3 = total3 / (i-1);
average4 = total4 / (i-1);
System.out.println("\tSample #\tTrial 0\tTrial 1\tTrial 2\tTrial 3");
System.out.println("\t\t" + arr3[max] + "\t" + arr0[i-2] + "\t" + arr1[i-2] + "\t" + arr2[i-2] + "\t" + arr3[i-2]);
System.out.print("Average: \t\t");
System.out.println(average1 + "\t" + average2 + "\t" + average3 + "\t" + average4);
for (i=1; i < average; i++);
}
}
Perhaps this:
var averages = new List<int>(){average1,average2,average3,average4};
var maxAvg = averages.Max();
var minAvg = averages.Min();
do you need this?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
int max = 0;
int min = 0;
int total = 0;
int avg = 0;
float count = 0;
String input = "";
Scanner scanner = new Scanner(System.in);
while (!(input = scanner.nextLine()).equals("end")) {
if(max < Integer.parseInt(input))
max = Integer.parseInt(input);
else if(min > Integer.parseInt(input))
min = Integer.parseInt(input);
if(count == 0)
max = min = Integer.parseInt(input);
total += Integer.parseInt(input);
count++;
}
System.out.println("max: " + max);
System.out.println("min: " + min);
System.out.println("total: " + total);
System.out.println("avg: " + total / count);
}
}
To find the minimum of a list of variables (which are not an array) you can let java syntax help you:
The NumberUtils class comes from Apache Commons-Lang library
public class ArrayTest {
public static int min(int ... value)
{
return org.apache.commons.lang.math.NumberUtils.min(value);
}
public static int max(int ... value)
{
return org.apache.commons.lang.math.NumberUtils.max(value);
}
public static void main(String[] args) {
int average1=4, average2=20, average3=40;
System.out.println("minimum:"+min(average1,average2,average3));
System.out.println("maximum:"+max(average1,average2,average3));
}
}

Categories

Resources