Storing data in Arrays (Java) - java

I'm just a beginner in Java. Can someone please tell me how to arrange this program. In this program I want to store 10 marks in an array, and then output the ones that are equal to or greater than the average. Help would be appreciated.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
}
sum = sum + mark[c];
int average = sum / 10;
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}

You need loop the array twice. The first iteration sums all the elements and computes the average. And the other iteration outputs the elements that meet your constraints.
The code is below:
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
// The first iteration sums all elements
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
// This iteration outputs elements that meet your requirements.
for(int c = 0; c < 10; c++){
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}
}

You need to add another for loop to iterate your array after calculating the average. Here is the updated code with the required for loop:
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++) {
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++) {
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}

public class aver{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
int average;
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
}
for(int c = 0; c < 10; c++){
sum = sum + mark[c];
}
average = sum / 10;
for(int c = 0; c < 10; c++){
if(mark[c]>=average){
System.out.println(mark[c]);
}
}
}
}

sum = sum + mark[c];
statement must be inside your loop.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++)
{
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++)
{
if(mark[c]>=average)
{
System.out.print(mark[c]);
}
}
}

Just some modification in your code.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++){
if(mark[c]>=average)
System.out.print(mark[c]);
}
}
Explanation
You need to add each element to sum to get the total. So add each element within the for loop after taking input
you also need to check each element to compare with the average. So you need to iterate the array again to compare each element.

Related

Stuck on Discrete distribution having an issue with finishing the problem

Here is what I am suppose to be getting.
This is what I am actually getting.
Write a program DiscreteDistribution.java that takes an integer command-line argument m, followed by a sequence of positive integer command-line arguments a1,a2,…,an, and prints m random indices (separated by whitespace), choosing each index i with probability proportional to ai.
So far I have
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 0; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 0; i < n; i++) {
total += freq[i];
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
int r = (int) ((total) * Math.random() - 1); // integer in [0, total)
int sum = 0;
int event = -1;
for (int i = 0; i < n && sum <= r; i++) {
sum += freq[i];
event = i;
System.out.println(freq[i]);
}
}
}
Under the assumption that I understand your problem correctly, then you can use the following algorithm to produce m random numbers in the range 1 to n according to the given frequencies:
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 1; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 1; i < n; i++) {
total += freq[i];
}
double[] summedProbabilities = new double[n];
for (int i = 1; i < summedProbabilities.length; i++) {
final double probability = freq[i] / (double) total;
summedProbabilities[i] = summedProbabilities[i -1] + probability;
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
double randomProbability = Math.random();
int i = 1;
while (randomProbability > summedProbabilities[i]) {
i++;
}
System.out.print(i + " ");
if (j % 10 == 0) {
System.out.println();
}
}
}
I strongly suggest you to refactor the code in a way that you use methods to calculate small pieces and compose it then.
public class DiscreteDistribution{
public static void main(String[] args) {
// takes in number of times we must loop to print indices
int m = Integer.parseInt(args[0]);
// set the array size to the number of input from command line
//minus the first input
//because we are not considering the input at args[0]
int [] n = new int[args.length-1];
// cSum to store the cummulatives
int [] cSum = new int[args.length];
// to store an array of random generated
//number of size m
int [] rand = new int[m];
int count = 1;
int cCount = 1;
int sum = 0; // to add the inputs n;
// to store user input in an array in n ignoring the first input
for(int i =0; i < n.length; i++)
{
n[i] = Integer.parseInt(args[count]);
count++;
}
//stores the cummulatives of n in cSum
for(int j = 0; j < n.length; j++)
{
sum = sum + n[j];
cSum[j+1] = sum;
}
//generate a random number and stores in rand representing the //probabilites
for(int p = 0; p < m; p++) {
int r = (int)(1+Math.random()*cSum[cSum.length-1]);
rand[p] = r;
}
// loop from 0 to m to print the indices of n;
for(int s = 0; s < m; s++) {
//prints the indices corresponding to the condition
for(int q = 1; q < n.length; q++) {
if(rand[s] <= cSum[q-1]) {
System.out.print(q+" ");
}
}
}
}

Out of bounds exception in matrix multiplication [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I wrote this code.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the rows \"then\" columns of the first array: ");
int a = console.nextInt();
int b = console.nextInt();
int[][] arr1 = new int[a][b];
System.out.println("Please enter the rows \"then\" columns of the second array: ");
int c = console.nextInt();
int d = console.nextInt();
int[][] arr2 = new int[c][d];
if (b != c) {
System.out.println("these two matrices can't be multiplied!!");
} else {
int[][] mult = new int[a][c];
System.out.println("Please enter the elements of the first array : ");
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
arr1[i][j] = console.nextInt();
}
}
System.out.println("Please enter the elements of the second array : ");
for (int i = 0; i < c; i++) {
for (int j = 0; j < d; j++) {
arr2[i][j] = console.nextInt();
}
}
int sum = 0;
for (int i = 0; i < a; i++) {
for (int j = 0; j < d; j++) {
for (int k = 0; k < c; k++) {
sum += arr1[i][k] * arr2[k][j];
mult[i][j] = sum;
}
sum = 0;
}
}
for(int i=0;i<a;i++){
for(int j=0;j<d;j++) {
System.out.print(mult[i][j] + " ");
}
System.out.println("");
}
}
}
}
and when I run it, it says java.lang.ArrayIndexOutOfBoundsException.
I don't know why, Thanks for helping.
From what I see, here might be the problem: int[][] mult = new int[a][c], it should be new int[a][d]
P/s: Would be nicer if you can format the first part of your code

JAVA: Passing an array to a method

I can't seem to pass my array to a secondary method. It only sees one of the 10 inputs, so I can't properly use it in the secondary method.
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter some numbers: ");
double [] numbers = new double [10];
int n = 0;
int i = 0;
while(n < numbers.length) {
numbers[i] = input.nextDouble();
n+=1;
}
System.out.println(min(numbers));
}
public static double min(double[] array) {
System.out.println(array[1]);
double smallest = array[0];
for (int l = 1; l < array.length; l++) {
if (array[l] < smallest) {
smallest = array[l];
System.out.println("Your smallest = " + smallest);
}
}
return 0;
}
In the first while loop, the variable i does not change.
while (n < numbers.length) {
numbers[i] = input.nextDouble();
n+=1;
}
variable i is never being changed so you are assigning each new number to the same spot in the array overwriting the previous number.
Just use your n variable instead:
while (n < numbers.length) {
numbers[n] = input.nextDouble();
n += 1;
}

.class expected error when passing array to function

public class AssignmentChapter8
{
public static void main(String[] args)
{
int randomNumbers[] = new int[100];
int oddCount;
int evenCount;
for(int x = 0; x < randomNumbers.length; x++)
randomNumbers[x] = (int)(Math.random() * 25);
for(int y = 0; y < randomNumbers.length; y++)
if(randomNumbers[y] % 2 > 0)
oddCount += 1;
else
evenCount+=1;
int oddNumbers[] = getOddNumbers(oddCount, randomNumbers[]);
int evenNumbers[] = getEvenNumbers(evenCount, randomNumbers[]);
System.out.println();
System.out.println("The list of odd numbers is:");
System.out.println();
for(int a = 0; a < oddNumbers.length; a++)
System.out.print(oddNumbers[a] + "\t");
System.out.println();
System.out.println("The list of even numbers is:");
System.out.println();
for(int b = 0; b < evenNumbers.length; b++)
System.out.print(evenNumbers[b] + "\t");
}
public static int[] getOddNumbers(int oddCount, int randomNumbers[])
{
int oddNumbers[] = new int[oddCount];
int counter = 0;
for(int x = 0; x < randomNumbers.length; x++)
if(randomNumbers[x] % 2 > 0)
{
oddNumbers[counter] = randomNumbers[x];
counter++;
}
return oddNumbers;
}
public static int[] getEvenNumbers(int evenCount, int randomNumbers[])
{
int evenNumbers[] = new int[evenCount];
int counter = 0;
for(int x = 0; x < evenNumbers.length; x++)
if(randomNumbers[x] % 2 < 1)
{
oddNumbers[counter] = randomNumbers[x];
counter++;
}
return evenNumbers;
}
}
I'm new to java and have been trying to create a program to generate 100 numbers and sort odds and evens. The program has even giving an .class expected error no matter what I do. Any help would be appreciated.
The [] is not needed in this line instead of
int randomNumbers[] = new int[100];
// and
int oddNumbers[] = getOddNumbers(oddCount, randomNumbers[]);
write
int[] randomNumbers = new int[100];
// and
int[] oddNumbers = getOddNumbers(oddCount, randomNumbers);
The [] is part of the type, not the name.
When referring to an array as a whole, don't use the [] with the variable name. Change
int oddNumbers[] = getOddNumbers(oddCount, randomNumbers[]);
int evenNumbers[] = getEvenNumbers(evenCount, randomNumbers[]);
to
int oddNumbers[] = getOddNumbers(oddCount, randomNumbers);
int evenNumbers[] = getEvenNumbers(evenCount, randomNumbers);
As Peter Lawrey stated, you don't need the brackets on the function calls. There are also a few other compilation errors. First, it looks like you have a copy/paste error in the getEvenNumbers function. Inside the for loop oddNumbers should be evenNumbers.
You also need to initialize the ints oddCount and evenCount (probably to 0).

Java permutations 2

I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPermutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPermutation(int[] p)
{
int n = p.length-1;
int j = 0;
int m;
int f = 0;
System.out.print("(");
while (f < n) {
m = p[j];
if (m == 0) {
do
f++;
while (p[f] == 0 && f < n);
j = f;
if (f != n)
System.out.print(")(");
}
else {
System.out.print(" " + m);
p[j] = 0;
j = m - 1;
}
}
System.out.print(" )");
}
}
I'm not too crazy about
int n = p.length-1;
followed by
while (f < n) {
So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.
You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);
I don't think swapping each element with a random other element will give a uniform distribution of permutations. Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
remainingValues.add(i);
for(int i = 0; i < n; i++) {
int next = rand.nextInt(remainingValues.size());
result[i] = remainingValues.remove(next);
}
Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time. There are data-structures which could handle this task in n log n time but they are very non-trivial.
This does not answer the problem you have identified.
Rather i think it identifies a mistake with your generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
System.out.println("random nums generated are: ");
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
System.out.print(r + " ");
Run the proc several times.
Do you see what i see?
Jerry.

Categories

Resources