Question: Write a method that takes as input a variable number of integers. The method should return the average of the integers as a double. Write a full program to test the method.
That code below creates an array of 10 integers and finds their average. However, I need it to create a variable number of arguments (int...a) where any number of integers entered can be averaged. Can someone help me.Thanks.
My code:
package average.pkgint;
import java.util.Scanner;
public class AverageInt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] number = new int [10];
Scanner b = new Scanner(System.in);
System.out.println("Enter your 10 numbers:");
for (int i = 0; i < number.length; i++) {
number[i] = b.nextInt() ;
}
System.out.println("The average is:"+Avnt(number));
}
public static int Avnt(int [] a){//declare arrays of ints
int result = 1;
int sum = 0;
//iterate through array
for (int num : a) {
sum += num;
}
double average = ( sum / a.length);//calculate average of elements in array
result = (int)average;
return result;
}
}
This is a way of getting as many variables as you want to a method and going through them all:
public static void testVarArgs(int... numbers){
for(double u: numbers) {
System.out.println(u);
}
}
If you don't want to read the number of integers as the first input you can declare a stack in stead of an array
Stack<Integer> numbers=new Stack<>()
and then you can add the numbers with the add method.
Just change your method declaration to a variable length parameter:
public static int Avnt(int ... a){//declare variable int arguments
When you use a variable length parameter, you supply the values in the method invocation. For example,
System.out.println(Avnt(1,2,3));
System.out.println(Avnt(1,2,3,4,5,6,9,9,9,10,10));
Actually, this looks like it meets your requirements. Just add method calls in your main() similar to these.
Related
The Java program below asks the user for UP TO 25 test scores, it then stores them in an array, averages them, and prints out in table form the inputted test grades as well as the calculated average. There is an unused sorting algorithm present as its own method named selectionSort. This is actually from a textbook.
I need to use that method to sort the array and create an additional output like the second example shown below where the test scores are displayed in ascending order. The only hint I have is that I need to make another array of the indices of the first array.
I'm not supposed to put any additional code in the main method, so I assume I will need a separate method? Or can I put all of the additional code in the selectionSort method so I only have to call one method? All I understand is that the selectionSort method sorts the elements, but not the indices so it won't show Test 1, 2, 3 like it's supposed to. So I need to sort the indices as well, and then somehow print both? How do I do this? Thanks
The current output is like this.
unsorted
I need an additional output like this. "Table of sorted test scores"
sorted
public class ArrayIntro2 {
public static void main(String[] args) {
//integer array
int [] TestGrades = new int[25];
//creating object of ArrayIntro2T
ArrayIntro2T pass = new ArrayIntro2T(TestGrades, 0, 0, 0);
//getting total and filling array
int scoreCount = ArrayIntro2T.FillArray(TestGrades, 0);
//get average score
double avg = pass.ComputeAverage(TestGrades, scoreCount);
//outputting table
ArrayIntro2T.OutputArray(TestGrades,scoreCount,avg);
}
}
//new class to store methods
class ArrayIntro2T{
//variable declaration
double CalcAvg = 0;
int ScoreTotal = 0;
int ScoreCount = 0;
int [] TestGrades = new int[25];
//constructor
public ArrayIntro2T(int [] TestGradesT, int ScoreCountT, double CalcAvgT, int ScoreTotalT)
{
TestGrades = TestGradesT;
ScoreCount = ScoreCountT;
CalcAvg = CalcAvgT;
ScoreTotal = ScoreTotalT;
}
//method to fill array
public static int FillArray(int [] TestGrades, int ScoreCount)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter test scores one at a time, up to 25 values or enter -1 to quit" );
TestGrades[ScoreCount]= scan.nextInt();
if(TestGrades[ScoreCount]==-1)
{
System.out.println("You have chosen to quit ");
}
while(TestGrades[ScoreCount]>=0 && ScoreCount<=25)
{
ScoreCount++;
System.out.println("Enter the next test score or -1 to finish ");
TestGrades[ScoreCount] = scan.nextInt();
}
return ScoreCount;
}
//method to compute average
public double ComputeAverage(int [] TestGrades,int ScoreCount)
{
for(int i=0; i<ScoreCount;i++)
{
ScoreTotal += TestGrades[i];
CalcAvg = (double)ScoreTotal/(double)ScoreCount;
}
return CalcAvg;
}
public static void selectionSort(int[] TestGrades){
int startScan, index, minIndex, minValue;
for(startScan=0; startScan<(TestGrades.length-1);startScan++){
minIndex = startScan;
minValue = TestGrades[startScan];
for(index = startScan+1;index<TestGrades.length; index++){
if(TestGrades[index]<minValue)
{
minValue=TestGrades[index];
minIndex=index;
}
}
TestGrades[minIndex]=TestGrades[startScan];
TestGrades[startScan]=minValue;
}
}
//method to output scores and average
public static void OutputArray(int [] TestGrades,int ScoreCount, double CalcAvg)
{
System.out.println("Grade Number\t\tGrade Value");
for(int i=0; i<ScoreCount;i++)
{
System.out.println((i+1)+"\t"+"\t"+"\t"+TestGrades[i]);
}
System.out.printf("Calculated Average\t"+ "%.2f%%", CalcAvg);
}
}
I've tried calling the selectionSort method in the main method, and also using Array.sort although they produce the same result. When I do that, I get an output that looks like this:
failed attempt
Why are you thinking about sorting the indices? The sorted output that you expect doesn't change the order of the indices. Adding the call to selectionSort() in the main method makes sense, but if you're not supposed to do that, you can add it at the end of FillArray(), or the start of OutputArray().
As to the issue with your output, you need to look into sorting only the scores that were entered by the user, and not every entry in the array.
I have to make the following program.
Write a program that builds a frequency array for data values in the range 1 to 20 and then prints their histogram. The data is to be read as input from the user. Add the following functions to your program:
a. The getData function takes input from the user and stores the data in an array.
b. The printData function prints the data in the array.
c. The makeFrequency function examines the data in the array, one element at a time, and adds 1 to the corresponding element in a frequency array based on the data value.
d. The makeHistogram function prints out a vertical histogram using asterisks for each occurrence of an element. For example, if there were five value 1s and eight value 2s in the data, it would print
1: *****
2: ********
I managed to make getData function but I can't make the other 3. Any help would be appreciated. Here is my code
import java.util.Scanner;
public class FrequencyArray {
static Scanner scan = new Scanner(System.in);
public void getData() {
System.out.println("Enter the size of array: ");
int nums = scan.nextInt();
int[] a = new int[nums];
for (int i = 1; i < a.length; i++) {
System.out.print("Enter the numbers: " + i + ":");
a[i] = scan.nextInt();
}
}
public void printData() {
getData();
}
public static void main(String[] args) {
FrequencyArray array = new FrequencyArray();
array.getData();
}
}
To print such an array, all you would need is another for-loop - loop from 0 to the array's length, and print both the loop counter's value, and the value stored in the array at that index.
System.out.println(index + ":" + array[index]);
For the histogram, do a similar loop, but for each value of the array, append an asterisk to the current line for however many instances of said number there are.
System.out.print(index);
//from 0 to the amount of this number, call System.out.print("*");
System.out.println();
Use TreeMap to store the number and their frequency in a sorted order once you get the data
then iterate over the TreeMap to print the number followed by the stars denoting the count of the value
public void printData() {
int [] numArray = getData();
Map<Integer,Integer> valueCountMap = new TreeMap();
for(int i=0;i<numArray.length;i++) {
int num = numArray[i];
if(valueCountMap.get(num) == null) {
valueCountMap.put(num,0);
}
int count = valueCountMap.get(num);
valueCountMap.put(num,count+1);
}
for(Map.Entry<Integer,Integer> entry:valueCountMap.entrySet()) {
int num = entry.getKey();
int value = entry.getValue();
System.out.print(num+":");
for(int i=0;i<value;i++) {
System.out.print("*");
}
System.out.print(" ");
}
}
Following assumptions i have made getData must return interger array and you need to print in one line. Following rectification i have done to your code
in getData i = 0 not i = 1
I am getting an error when I try to run this program as a command line argument in Eclipse. This is what the error says:
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
When I change the main method to String then I can't call on the second method as the String main method is not compatible with the int returnSum method.
I need to have the returnSums method be a int type method as per the requirements but I can't figure out how to do this without getting an error. It says in the requirements that i need to use variable number of arguments for the method but have a hard time grasping the idea.
Can someone please help me with this? Here's my code:
public static void main(int[] args) {
// Printing the entered digits
System.out.print("Passing");
System.out.print(" [ ");
for (int nums = 0; nums < args.length; nums++) {
System.out.print(args[nums] + " ");
}
System.out.print("] ");
System.out.println("\nSum is " + returnSum(args)); // Calling on the second method for the sum
}
// Taking the nums from the main method as arguments
public static int returnSum(int...args) {
int sum = 0;
// Calculating the sum
for (int nums = 0; nums < args.length; nums++) {
sum = sum + nums;
}
return sum;
}
Thank you!
Try Below Code:
public class SumOfNumbers {
public static void main(String[] args) {
int[] intArgs = new int[args.length];
for (int x = 0; x < args.length; x++) {
if (args[x].matches("\\d+")) {
intArgs[x] = Integer.parseInt(args[x]);
} else {
System.out.println(args[x] + " is not a Integer hence skiped in this program");
}
}
// Printing the entered digits
System.out.print("Passing");
System.out.print(" [ ");
for (int nums = 0; nums < intArgs.length; nums++) {
System.out.print(intArgs[nums] + " ");
}
System.out.print("] ");
System.out.println("\nSum is " + returnSum(intArgs)); // Calling on the second method for the sum
}
// Taking the nums from the main method as arguments
public static int returnSum(int... args) {
int sum = 0;
// Calculating the sum
for (int nums = 0; nums < args.length; nums++) {
sum = sum + args[nums];
}
return sum;
}
}
#Sanjay: If you will try with argument: 10, 20 , 30 you will get below output:
10, is not a Integer hence skiped in this program
, is not a Integer hence skiped in this program
Passing [ 0 20 0 30 ]
Sum is 50
10, should not be ignored only , should be ignored. also it intArgs should be of size 3 including 10 or size 2 excluding 10 it should not be of size 4.
Change your main method's parameter back to String[], as this is a required signature.
In your main method, parse each argument into an int:
int[] intArgs = new int[args.length];
for(int x=0; x<args.length; x++)
intArgs[x] = Integer.parseInt(args[x]);
Note that if you pass no arguments or ones that are not integers, this will break. If you want to handle this, you can check for args!=null before and catch a NumberFormatException around this code.
You will need to have your main method signature be (String[] args) but you can loop though the args array in your code, convert each element to an int using Integer.parseInt(), store them in a new array (of type int[]), and send this new array to returnSum.
Okay, so I created a DigitsSum application. The class is DigitsSum and it does contain a static method called sumDigits(I AM DONE WITH THIS). ( However I didn't get this part) The names must match these including the capitalization, the sumDigits method should take a single parameter, an integer, and return the sum of the digits in that integer, sumDigits method should not print anything, and it should return its answer using a return statement. I can use a main method to test my sumDigits method, and all printing should happen there. I would like to know whether if i did perfectly fine or no..also method return should be like if entered a number, suppose 345, then output should be 3+4+5=12 --> 1+2 = 3. what i am doing wrong here? Thanks in advanced!
import java.util.Scanner;
public class SumDigits {
public static double sumDigits (int a){
int sum;
int t= a%10;
sum= t+t;
a = a/10;
return (sum);
}
public static void main (String [] args){
double sumDigit;
int integer;
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
integer = in.nextInt();
sumDigit = sumDigits(integer);
System.out.println ("The sum of the digit is:" +sumDigit);
}
}
I believe that you're missing a few things:
You should always close streams and any external resource in general. id est: closing your Scanner before leaving your main method
As it has been pointed out in the comments, you should use a recursive method to implement sumDigits, because it reflects the actual behavior you're trying to implement.
Your code could be like this:
public class Main {
public static int sumDigits(final int a) {
int sum = 0;
int b = a;
do {
sum += b % 10;
b = b / 10;
} while (b > 0);
if (sum >= 10) {
return sumDigits(sum);
}
return sum;
}
public static void main(final String[] args) {
double sumDigit;
int integer;
try (final Scanner in = new Scanner(System.in)) {
System.out.print("Enter a positive integer: ");
integer = in.nextInt();
sumDigit = sumDigits(integer);
System.out.println("The sum of the digit is: " + sumDigit);
}
}
}
What I did here in the recursive method can be decomposed in two parts:
You calculate the sum of all the digits of the given number (done by the do/while loop)
If that sum itself is greater or equals to 10, then we need to return the recursive application of sumDigits on that value... otherwise, just return sum.
Note that I didn't only change the sumDigits method but also the main one, so it closes the Scanner using the try-with-resource syntax.
I have a method outside of the main method that averages. At the end of the main I am calling on that averaging method. I am not understaning the propper way to
1. use variables I declare with other methods in this program. for example the sum which is defined in the calculate_average method.
or
The sum which is defined in the main method.
Please show me
how to interchange variables in and out of the main method. interchangeably between methods that are not in main.
call on a method outside of main in main to calculate the average.
Here is my current code.
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double Sum = 0.0;
for (Double number: myArr)
{
Sum += number;
}
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
double Sum = 0;
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
return Sum / myArr.size();
}}
You have this at the end of main:
return Sum / myArr.size();
You need to move it to calculate_average:
private static Double calculate_average( ArrayList<Double> myArr )
{
Double Sum = 0.0;
for (Double number: myArr)
{
Sum += number;
}
return Sum / myArr.size();
}
Given that main is void and an average makes no sense as an exit code even if it weren't, I'm assuming that is some kind of typographical error.
Some code review
Local variables should start with a lower case letter. So sum, not Sum
You can use the primitive double instead of a Double object. Using the object will cause boxing/unboxing overhead.
Indent your while loop and its contents by four more spaces so the loop beginning aligns vertically with the code above it because it's in the same block (the method's block).
Split those last 2 braces into separate lines
Line up the last two braces vertically with the matching opening brace
You've started by creating your calculate_average method, but continue breaking up main. It's too long. Too much is going on there.
Change if (count == 20) to if (count >= 20). Harder to mess up, then.
i think you have static method,
so you can call them bye using className.MethodName Directly.
Just Declare your method as public and you can call them outside also.
programTwo.calculate_average(myArr)
No need to create object for calling static methods.
There's nothing I can see wrong with your code, except you are missing a return statement in your calculate_average method.
Also, if you name a method calculate_average, it should return the average not the sum.
Try this:
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}