Java: Unable to get Median calculated with code - java

I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}

Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!

Related

How to return the array repeated three time in a single array?

I'm pretty sure I've done most of the code correctly but I'm returning the wrong thing? I've tried using copyOf() but still had the same issue. It looks like I'm returning the object of an array rather than the elements? I need the method treble to return the original array repeated in order, three times in one array. So [1,2,3,] should look like [1,2,3,1,2,3,1,2,3] when trebled.
Any help would be much appreciated.
import java.util.Scanner;
import java.util.Arrays;
public class ArrayExercises
{
public static void main(String[] args)
{
final int SIZE = 5;
int[] array = new int[SIZE];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.print("Please enter whole number " + (i + 1) + ": ");
int input = scanner.nextInt(); // get input from the user
array[i] = input; // store the value in the array
}
printArray("Input array:", array);
// call method sum and print out the result
int sum = sum(array);
System.out.println("The sum of elements is " + sum);
// call method repeat and print out the result
int[] trebled = repeat(array);
System.out.println("The repeated array is " + trebled);
}
public static void printArray(String msg, int[] array)
{
System.out.println(msg + " " + Arrays.toString(array));
}
public static int sum(int[] array)
{
int s = 0;
for (int i = 0; i < array.length; i++)
s += array[i];
return s;
}
public static int[] repeat(int[] array) //this is the part I'm having trouble with
{
int len = array.length;
int[] multiplied = new int[len*3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < len; j++)
{
multiplied[i * len + j] = array[j];
}
}
return multiplied;}
}
Try using:
System.out.println("The repeated array is " + Arrays.toString(trebled));
to print your array instead of printing using the array variable name, because otherwise that will print the address of the array rather than the content.
your method is ok, the issue is how you print it because as mentioned in the comments you do not use your printArray() method in this case.
So try changing this line :
System.out.println("The repeated array is " + trebled);
to :
printArray("The repeated array is " , trebled);

create a program that prompts the user to enter a number between 1 and 15 and print the sum as shown: 1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10

I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}

Selection sort Algorithm in Java

I'm having some trouble sorting an array. I'm trying to sort it in ascending order.
My task is to get a series of integers from the user and store them into an array, then display them back to the user in ascending order. I was fine getting input from the user, storing it in the array and displaying them back. I was able to run my code and get the results I wanted but as far as getting the integers in the array in ascending order using selection sort, I was having a lot of difficulty with that.
The size of the array depends on the value that the user inputs, so it is set to the variable numValues rather than a number.
I get an error with the sort method I created. I'm getting syntax errors and void is an invalid type. I think I'm missing something and I'm not sure how to go about fixing this. If someone can point me in the right direction. Any help would be appreciated.
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("Here are the values you've entered, in ascending order");
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
} //End for
} // End method sort
keyboard.close(); // To close Scanner object
} //End method main
You cannot have another method inside main. Get the method sort(int[] values) out of main, and call it inside main.
You had another problem. Inside your sort method:
System.out.print(values[scan] + " ");
scan has to be replaced by n.
Here is the completed code:
import java.util.*;
public class Project {
public static void main(String[] args) {
int numValues; // The number of values user has
int [] values; // Array declaration for values
Scanner keyboard = new Scanner(System.in); // Scanner object to get input from user
System.out.println("How many values do you have?"); // To get number of values for array
numValues = keyboard.nextInt();
/*
* Array to hold number of values
*/
values = new int [numValues];
/*
* Loop to gather integer values
*/
for (int n=0; n < values.length; n++ )
{
System.out.print("Enter value " + (n+1) + ":" );
values[n] = keyboard.nextInt();
} //End for loop
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + " ");
}
System.out.println("Here are the values you've entered, in ascending order");
sort(values);
keyboard.close(); // To close Scanner object
}
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
} //End for
} // End method sort
} // End class Project
Your program will not executed or will not display correct result due to some reasons.
You are using "private static void sort(int[] values)" method in main method and it's not possible because we can't define method in another method. Either you have to create a separate method outside of main method or you can use sorting functionality in your main method also.
Another mistake is in below code. You are using scan variable for displaying result in ascending order. Here is should be n.
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
}
Your logic is correct. But it's little bit large for selection sort. Below is small way to do this.
public class SelectionSort
{
public static void main(String[]args)
{
int [] values = {15,14,13,12,11};
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("\nHere are the values you've entered, in ascending order");
sort(values);
}
private static void sort(int[] values)
{
int index = 0;
int index2 = 0;
int temp = 0;
for(index=0; index<values.length; index++)
{
for(index2 = index+1; index2< values.length; index2++)
{
if(values[index] > values[index2])
{
temp = values[index];
values[index]= values[index2];
values[index2] = temp;
}
}
}
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
}
}
}
int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
//the outer loop will switch the number
for(int i=0;i<arrayToSort.length;i++){
int indexSmal=i;
//the inner loop will search for the biggest number
for(int j=i+1;j<arrayToSort.length;j++){
//search for biggest number index starting from i index
if(arrayToSort[j]>arrayToSort[indexSmal]){
indexSmal=j;
}
}//end loop
//swap the number
int smallNum=arrayToSort[indexSmal];
arrayToSort[indexSmal]=arrayToSort[i];
arrayToSort[i]=smallNum;
}// end loop
for(int i=0;i<arrayToSort.length;i++){
System.out.print(arrayToSort[i]+", ");
}

Average of Int[]; Method not Returning

My task is to calculate the average of the Integers a user defines in an Array and print back to main using the method in my class file.
Currently I have both files to compile but can't seem to figure out why nothing is being printed. Please help, much appreciated!
Snippet of code in Test Program to examine:
// Print average of integers in array.
System.out.println("\nAverage of values in array =");
myArray.avgArray();
Snippet of code in Class Program to examine:
// Method to calculate average of integers in array.
public double avgArray()
{
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double avg = sum /(double)limit;
return avg;
}
This code is my program for testing purposes:
import java.util.Scanner;
public class P5test
{
public static void main(String[] args)
{
// Set up Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Input size of array desired.
System.out.print("Size of array: ");
int size = keyboard.nextInt();
// Set up object.
P5class myArray = new P5class(size);
// Allow user to fill array.
System.out.println("\nEnter data for array:");
myArray.fillArray();
// Print contents of array.
System.out.println("\nContents of array:");
myArray.printArray();
// Print average of integers in array.
System.out.println("\nAverage of values in array =");
myArray.avgArray();
// Print postive values in array.
System.out.println("\nPositive values in array:");
myArray.pvaluesArray();
// Sort contents of array in ascending order.
System.out.println("\nSorted Array:");
myArray.sortArray();
myArray.printArray();
}
}
This code contains my class with the various methods I'll be implementing to main:
import java.util.Scanner;
public class P5class
{
// Constructor setting up empty array of size specified by user.
public P5class(int size)
{
limit = size;
nrs = new int[limit];
}
// Method to fill array.
public void fillArray()
{
// Set up Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
for(int ctr = 0; ctr < limit; ctr++)
{
System.out.print("Integer #" + (ctr+1) + ": ");
nrs[ctr] = keyboard.nextInt();
}
}
// Method to display contents of array.
public void printArray()
{
for(int ctr = 0; ctr < limit; ctr++)
{
System.out.println("Nrs[" + ctr + "] = " + nrs[ctr]);
}
}
// Method to calculate average of integers in array.
public double avgArray()
{
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double avg = sum /(double)limit;
return avg;
}
// Method to examine if any positive values are present in array.
public void pvaluesArray()
{
int largest = nrs[0];
// Check to see if any other number in array is larger than first.
for(int ctr = 1; ctr < limit; ctr++)
{
if(nrs[ctr] > largest)
largest = nrs[ctr];
}
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double average = (double)sum/limit;
for(int ctr = 0; ctr < limit; ctr++)
{
if(largest <= 0)
{
System.out.println("\nArray contains no positive integers.");
break;
}
else if (nrs[ctr] > 0)
{
System.out.println("Nrs[" + ctr + "] = " + nrs[ctr]);
}
}
}
// Method to sort array into ascending order.
public void sortArray()
{
for(int ctr0 = 0; ctr0 < limit-1; ctr0++)
{
// Make one pass of Bubble Sort.
for(int ctr = 0; ctr < limit-1; ctr++)
{
if(nrs[ctr] > nrs[ctr+1])
{
int temp = nrs[ctr];
nrs[ctr] = nrs[ctr+1];
nrs[ctr+1] = temp;
}
}
}
}
// Instance variables.
private int limit;
private int[] nrs;
}
Here is an example output of the program when Run:
----jGRASP exec: java P5test
Size of array: 5
Enter data for array:
Integer #1: 0
Integer #2: -9
Integer #3: 4
Integer #4: 7
Integer #5: 2
Contents of array:
Nrs[0] = 0
Nrs[1] = -9
Nrs[2] = 4
Nrs[3] = 7
Nrs[4] = 2
Average of values in array =
Positive values in array:
Nrs[2] = 4
Nrs[3] = 7
Nrs[4] = 2
Sorted Array:
Nrs[0] = -9
Nrs[1] = 0
Nrs[2] = 2
Nrs[3] = 4
Nrs[4] = 7
----jGRASP: operation complete.
It's returning a value, but you're not doing anything with it, try:
System.out.println("\nAverage of values in array = " + myArray.avgArray());
Or:
double avg = myArray.avgArray();
System.out.println("\nAverage of values in array = " + avg);
Or one of many other ways.
Or, instead of return avg;, you can simply print it out in the method with System.out.println(avg); and change the return type to void.

Taking User Input for an Array

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Categories