I have to create a java program with two classes and the challenge is =
"Enter in 10 numbers. Calculate the average and display all numbers greater than the average."
I am fairly new to java and I have no idea on what I am doing and how to send array values from one class to another.
import BreezySwing.KeyboardReader;
import javax.swing.*;
public class Average {
public static void main(String[] args) {
KeyboardReader reader = new KeyboardReader();
System.out.print('\u000C');
AverageTest at = new AverageTest();
int numberArray[];
int i;
numberArray = new int[10];
for (i = 0; i < 10; i++) {
numberArray[i] = reader.readInt("Enter a number: ");
at.setnumber(numberArray);
}
}
}
import javax.swing.*;
import BreezySwing.*;
public class AverageTest
{
private int number[];
private int a;
public void setnumber(int number)
{
number = numberArray;
}
}
import java.util.Scanner;
public class AverageTest {
public static void main(String[] args) {
int[] array = new int[10];
// Try with resources, automatically closes the reader once the work is done
// Read 10 integers from the standard input
try (Scanner reader = new Scanner(System.in);) {
for (int i = 0; i < 2; i++) {
System.out.println("Enter a number: ");
array[i] = reader.nextInt();
}
} catch (Exception e) {
e.printStackTrace();
}
// we have an array with 10 numbers, now create an average object by passing
// this array to the Average class constructor
Average averageObj = new Average(array);
// Compute the average
float average = averageObj.average();
System.out.println("Average: " + average);
System.out.println("Numbers greater than average: ");
// Print out the numbers which are greater than or equal to the average
for (int i = 0; i < array.length; i++) {
if (array[i] >= average) {
System.out.println(array[i]);
}
}
}
}
class Average {
private int[] array;
public Average(int[] array) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException("Array cannot be null or empty");
}
this.array = array;
}
public int[] getArray() {
return array;
}
/**
* Computes the average of the given array and returns it.
*/
public float average() {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return (float) sum/array.length;
}
}
there are 3 steps about this issue:
1.Enter in 10 numbers.
2.Calculate the average.
3.display all numbers greater than the average.
you have done the step 1,that's great.
and I can see that you are trying to do the step 2.
here's the suggestion of your issue:
if you want to send array values from A class to B,you just need to invoke the method of B in the A correctly.
I think I know what you are trying to do.
the problem of your code that you can't send array values from one class to another is because the method's parameter type is not matching.
the method public void setnumber(int number),the parameter is an int type,and you try to refer it to an int array,this's wrong.
first, you need to change the method's definition to public void setnumber(int[] numberarray),and try to figure out why we have to write like this.
then finish the step 2.
Hope it'll help.
Related
Our assignment says we should "write the source code and test code for a function named sumArray that accepts an array of ints and returns the sum of all elements from the array".
I think I've got SumArray.java to return sum OK, but I'm struggling to apply my method to the test input. Any help please? TIA.
SumArray.java
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
SumArrayTest.java
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
/**
* Test of main method, of class SumArray.
*/
#Test
public void testMain() {
System.out.println("main");
String[] args = null;
SumArray.main(args);
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
// int testResult = sumArray({2, 3, 4});
int testResult = SumArray sumArray(intArray);
assertEquals(expectedResult, testResult);
// fail("The test case is a prototype.");
}
}
Edit: I've tried to implement what's been suggested so far with some changes; really not sure of any of this is right; a lot of it is guesswork TBH.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray;
public static int sumArray(int[] arr) {
return sum;
}
public static SumArray input() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return new SumArray();
}
public static void main(String[] args) {
SumArray result = input();
System.out.println(result.sumArray(SumArray));
}
}
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
#Test
public void testSumArray() {
System.out.println("main");
String[] args = null;
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
assertEquals(expectedResult, SumArray.sumArray(intArray));
// fail("The test case is a prototype.");
}
}
The only error I'm seeing currently is 'cannot find symbol' for SumArray in main.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
The above is the original code you posted. Now, you say you get the correct output. Yes, here you do:
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray(); // this one will return the correct answer
sumArray(); // this one will not
}
}
The second one will return wrong data, because you don't reset the value of sum.
You should split the tasks: sumArray should receive an array, and should return the sum of the elements. Either you should change the name of the method, or change the implementation, that is what Mahmoud told you.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static Scanner scan = new Scanner(System.in); // create this on class level, not every execution of your method
public static int[] buildArray(int elements) {
int[] arr = new int[elements];
for ( int i = 0; i < elements; i++ ) {
System.out.println("Enter element nr: " + (i+1));
arr[i] = scan.nextInt();
}
return arr;
}
public static int sumArray(int[] input) {
int sum = 0; // don't use a class level one. especially not a static one, it's value could be altered by another thread
for ( int in : input ) { // iterate over the array and add the values
sum += in; // this should be in -> each iteration we add the value of in (the element of the array) to sum
}
return sum;
}
public static void main(String[] args) {
System.out.println("Provide the size of the array: ");
int param = scan.nextInt();
int[] array = buildArray(param);
int result = sumArray(array);
System.out.println("The sum of the array is: " + result);
}
}
This approach will land you with far lesser issues. It also doesn't have static variables like n and sum in your class that might lead to wrong results.
The main() method is the entry point into the application, you shouldn't test the main() method. Instead, you should test the sumArray() method and compare the expected Vs. the actual returned value from the method.
As a side note, you can better pass the input array to the sumArray() method as a parameter instead of reading it from System.in within the method body.
So your method signature can look like this:
public static int sumArray(int[] arr). The client code which uses this method, which is the main method in your case (or the unit test) can pass the array without bothering the method how this input array was got.
I'm doing something that produces the right result. However, it is wrong from a design POV.
The point of the program is to list the result of all the powers of a number up to and including the user-defined limit.
I have a constructor which accepts the base and the exponent from the Scanner. Then a method, which utilises a for loop to calculate the power for each exponent.
Now, the problem is that I'm printing the result from each loop iteration directly from this method. This beats the point of private variables and it being void in the 1st place.
Therefore, I want to define a getter method which returns the result of each power to the output. I used to set them just fine for if/switch statements, but I don't know how to do the same for loops. If I assign the result to a variable within the loop and return that variable from the getter then it will return only the output from the final iteration.
Private implementation
package Chapter6Review;
public class Powers {
private int target;
private int power;
public Powers(int target, int power) {
this.target = target;
this.power = power;
}
public void calculatePower() {
for (int i = 0; i <= power; i++) {
System.out.println((int) Math.pow(target, i));
}
}
/*
public int getPower() {
return
}
*/
}
User interface
package Chapter6Review;
import java.util.Scanner;
public class PowersTester {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your base: ");
int target = in.nextInt();
System.out.print("Enter your exponent: ");
int power = in.nextInt();
Powers tester = new Powers(target, power);
tester.calculatePower();
}
}
You can simply use a List ;
public List<Integer> calculatePower() {
int p;
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i <= power; i++) {
p = (int) Math.pow(target, i);
result.add(p);
}
return result;
}
Then in you main method, you can iterate the list to print the powers like that :
List<Integer> result = new ArrayList<Integer>();
Powers tester = new Powers(target, power);
result = tester.calculatePower();
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
You could store each of the results in a List:
List<Power> list = new ArrayList<>();
and when you call it add it as well
list.add(new Powers(target, power));
At the end you can iterate over the list like this:
for (Power power : list){
// your code
}
You might consider using streams as well
public List<Integer> calculatePower() {
return IntStream
.rangeClosed(0, power). // iterate from 0 till power inclusive
.mapToObj(i -> (int) Math.pow(target,i))
.collect(Collectors.toList()); // get result as list
}
Thanks for all the answers. Using a list seems to be a good choice.
Since I haven't covered lists yet, I resorted to this solution for now. But I don't like having code that can affect the solution in the main. Ideally, the loop should go in the private implementation.
Main
Powers tester = new Powers(target, power);
for (int i = 0; i <= power; i++) {
tester.calculatePower(i);
System.out.println(tester.getPower());
}
Private implementation
public void calculatePower(int iPower) {
result = (int) Math.pow(target, iPower);
}
public int getPower() {
return result;
}
We had to write a sorting algorithm ourselves. I wrote one, it works for 20-5000 data sets of integer, finishes in about 4 milliseconds. However, when I moved on to the 25000 data set, it stopped working at numbers with value 804; I have been trying to figure out why for the past 2 days and have no luck, my teacher tried his hand at it for 5 minutes and gave up. Any ideas as to why it would just get stuck on an infinite loop on the same number would be very much appreciated!
Edit: Commented inner loop
Edit 2: Added full code
Here is the code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
public class sort_old
{
static long steps=0;
static int nums, temp;
static int[] numbers, sorted, usedNum;
static String path="20_source.txt";
static Scanner scan;
static boolean used;
public static void main()
{
try
{
scan = new Scanner(new File(path));
while(scan.hasNextInt())
{
nums++;
scan.nextInt();
}
numbers= new int[nums];
sorted = new int[nums];
usedNum = new int[nums];
scan.close();
scan = new Scanner (new File(path));
try
{
for(int x = 0; x < nums; x++)
{
numbers[x]=scan.nextInt();
}
}
catch(NoSuchElementException e)
{
}
scan.close();
sortLargestToSmallest();
System.out.println(checkResults(sorted,true));
}
catch(FileNotFoundException e)
{
System.out.println("Sucks to suck");
}
}
private static void sortLargestToSmallest()
{
int counter=nums-1; // mums is the number of numbers in the data set.
for(int y = 0; y < nums; y ++)
{
temp = num[0]; //num[] is the array containing all the numbers
used=false; //boolean to for checking if the number was used already
for(int x = 0; x < nums; x ++)
{
if(temp<=num[x]) //finding the largest number
{
for(int j = 0; j < y; j++) //only check up to the numbers already assigned
{
if(usedNum[j]==x) //see if the number is already used. usedNum[] stores indexes of numbers already used; compare to current index
{
used=true; //the number is already sorted, so it moves on to the next
break;
}
else
used=false;
step++;
}
if(!used)//only if the number is not already sorted is it changed to temp
{
temp=num[x];
usedNum[y]=x;
}
}
}
sorted[counter]=temp; //putting the sorted value into the sorted array
counter--; // we were asked to sort from smallest to largest, but for some reason it didn't work.
}
}
}
public static boolean checkResults (int[] theArray, boolean report)
{
System.out.println("Checking Validity");
boolean stillValid = true;
int counter = 0;
while (stillValid && counter < theArray.length - 1)
{
if (theArray[counter] > theArray[counter + 1])
{
stillValid = false;
}
counter++;
}
if (report)
{
if (stillValid)
{
System.out.println("Checked " + theArray.length + " values. Sort is valid");
}
else
{
System.out.println("Checked " + theArray.length + " values. Found error at " + counter);
}
}
return stillValid;
}
}
I am new to programming and don't get why the program gives me a run time error for NullPointerException when I have tried initializing n, numInt, and arrayMenu. None of which seem to work. The program's job is to gather a set of random integers to store in an array and allow the user to pick which sort to choose from. Thanks for reading.
import java.util.Scanner;
import java.util.Random;
public class VariousSortsHS
{
private static int[] arrayMenu;
private static Random generator;
/**
* Constructor for objects of class VariousSortsHS.
*/
public VariousSortsHS(int n) //The error starts here
{
arrayMenu = new int[n]; //I don't get why it says null in the array when
//i am initializing the length of the array to n
/*Assigns a random number between 0 too 100.*/
for(int i = 0; i < n; i++)
{
int temp = generator.nextInt(100);
arrayMenu[n] = temp;
}
}
/**
* Selection Sort method.
*/
public static void selection(int n)
{
for(int i = 0; i < arrayMenu.length - 1; i++)
{
int minPos = i;
for(int j = i + 1; j < arrayMenu.length; j++)
{
if(arrayMenu[j] < arrayMenu[minPos]) minPos = j;
}
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[minPos];
arrayMenu[minPos] = temp;
System.out.print(temp + " ");
}
}
/**
* Insertion Sort method.
*/
public static void insertion(int n)
{
for(int i = 1; i < arrayMenu.length; i++)
{
int next = arrayMenu[i];
int j = i;
while(j > 0 && arrayMenu[j - 1] > next)
{
arrayMenu[j] = arrayMenu[j - 1];
j--;
}
arrayMenu[j] = next;
System.out.print(next + " ");
}
}
/**
* Quick Sort method.
*/
public static void quick(int n)
{
int pivot = arrayMenu[0];
int i = 0 - 1;
int j = n + 1;
while(i < j)
{
i++; while(arrayMenu[i] < pivot) i++;
j++; while(arrayMenu[j] > pivot) j++;
if(i < j)
{
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[j];
arrayMenu[j] = temp;
System.out.print(temp + " ");
}
}
}
/**
* Main method that allows user to input data.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you wish to sort random integers? (Yes or No) ");
String answer = in.next();
String answer2 = answer.toLowerCase();
do
{
/*Prompts for array length.*/
System.out.println("How many random integers do you wish to sort?");
int numInt = in.nextInt();
/*Promps for sort selection choice.*/
System.out.println("Select a sort to use: \n\t1)Selection\n\t2)Insertion\n\t3)Quick");
String sort = in.next();
String sort2 = sort.toLowerCase();
if(sort2.equals("selection"))
{
selection(numInt);
}
else if(sort2.equals("insertion"))
{
insertion(numInt);
}
else if(sort2.equals("quick"))
{
quick(numInt);
}
else
{
System.out.println("You have entered the wrong input.");
}
} while(!answer2.equals("no"));
}
}
Everything in your code is static. This means the constructor you wrote is never called, and the array has never been changed from its default value, null. Consider changing your constructor code to a static initialization block instead.
generator is never set to anything, so it's null too and you can't call nextInt on it
initializing the array is setting arrayMenu[n] instead of arrayMenu[i]
When you call insertion(numInt);, method public static void insertion(int n) is called and then you are trying to do the for-loop like this for(int i = 1; i < arrayMenu.length; i++)
However, arrayMenu was not initialized, it is null. When you try to call a length, on null, you get NullPointerException.
You need to add a static constructor and initialize the size using a static int
//set parameter = n
public static int parameter;
static
{
arrayMenu = new int[parameter];
}
I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH