This question already has answers here:
When do you use varargs in Java?
(8 answers)
Closed 6 years ago.
I am faced with probably a very simple dilemma. I am trying to create a program that computes the averages, sums, and count of all numbers inputed to the calculator. The problem with this is that I can only accept one input or three (dependent on number of variables listed in my method parameters). How do I make my add() method actually accept n number of inputs as opposed to a predefined set?
Main Class
public class Calculator
{
public static void main (String [] args)
{
AverageCalculator calculation1 = new AverageCalculator();
AverageCalculator calculation2 = new AverageCalculator();
calculation1.add(13);
System.out.println("Sum: " + calculation1.getSum());
System.out.println("Count: " + calculation1.getCount());
System.out.println("Average: " + calculation1.getAverage());
System.out.println();
calculation2.add(3, 7, 12); // Error due to method parameters
System.out.println("Sum: " + calculation2.getSum());
System.out.println("Count: " + calculation2.getCount());
System.out.println("Average: " + calculation2.getAverage());
}
}
I get an error when compiling this:
Calculator.java:28: error: method add in class AverageCalculator cannot be applied to given types;
calc2.add(3, 7, 12);
I am then running into how am I going to deal with my add() method's functionality. I know what it must do, I am sure I must add a for Loop. However, there is no given length for it to parse. Do I have my i = 0; i < calculation 2; i++? See comments in this portion
Secondary Class
public class AverageCalculator
{
private int sum;
private int count;
public AverageCalculator () {}
public void add (int newNum) // One input due to single parameter
{
// How to accept the multiple input from main class with this mutator
// and successfully manipulate data in this method
sum += newNum;
count++;
}
public int getSum()
{ return sum; }
public int getCount()
{ return count; }
public double getAverage()
{ return (double) sum / count; }
}
Java supports this. Is is called "varargs". If you add "..." to your type, you can repeat it as many times as you want (including 0 times) and then, in your function, process it as an array. This could like this (this code is completely untested):
public void add(int... newNums) {
for (int num : newNums) {
sum += num;
count++;
}
}
A you can read a bit more here.
Related
I received this assignment today and I am kinda stuck on it.
This is what the assignments say:
Write a method called recursiveUpAndDown() that takes one non-negative integer parameter, recursively starts at zero and prints all the integers from zero to the parameter (that is, prints 0, 1, 2, etc. all the way up to the parameter), then recursively starts at the integer parameter and prints all the integers from the parameter to zero (that is, prints the parameter, the parameter - 1, the parameter - 2, etc. all the way down to 0).
I was able to write the code for writing the coding to count down then up but unable to do up then down. Here is the code I wrote
class myCounter{
static void recursiveDownAndUp(int i)
{
if (i < 1)
return;
else
{
System.out.printf("%d ",i);
recursiveDownAndUp(i-1); // recursive call
System.out.printf("%d ",i);
return;
}
}
public static void main(String[] args)
{
recursiveDownAndUp(10);
}
}
We are not allowed to use 2 parameters, a helper method or a global variable. I know it seems hard, at least for me, but the professor said it is doable
static String recursiveUpAndDown(int n) {
if (n < 0) return "";
String x = recursiveUpAndDown(n - 1);
System.out.print(n + " ");
return n + " " + x;
}
public static void main(String[] args)
{
System.out.print(recursiveUpAndDown(10));
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Sorry there was a mistake earlier in this. This actually worked, but I'm confused where the value of result is involved in the for loop.
import java.util.Scanner;
public class PowerLoop
{
public static void main(String [] args)
{
exponent(1);
}
public static int exponent(int result) // defining method for raising base to power
{
int base; // defining user input variables
int power;
{
Scanner reader = new Scanner(System.in); // scanner is called reader
System.out.println("Please enter the base."); // first input is base
base = reader.nextInt();
System.out.println("Please enter the exponent.");
power = reader.nextInt();
{
for (int i = 1; i <= power; i++)
{
result = base * result;
}
System.out.println("Result: " + base + " ^ " + power + " = " + result);
return 0;
}
In your for loop, the variable result Is created outside of the for loops scope. Essentially, you are just changing the result variable that has already been created. If you attempted to create a new variable within the for loop such as "newResult = base * result", it would fail if you attempted to use it outside of the for loop. Here is a simple example that optimizes your code:
//Start getting the proper variables in your MAIN method.
Scanner reader = new Scanner(System.in);//create scanner here.
System.out.println("Enter a base number: ");
int base = reader.nextInt();
System.out.println("Enter an exponent: ");
int power = reader.nextInt();
out.println(exponent(base, power));
Then you could optimize the exponent method like so:
public static int exponent(int base, int power) {
double r = Math.pow(base, power);
int result = (int)r;
return result;
}
Now, for your specific question, lets imagine changing the for loop in your example to this below, this is the important point:
for(int i = 1; i <= power; i++)
{
int newResult = base * result;
}
System.out.println("Result: " + base + " ^ " + power + " = " + newResult);
That code above would generate an error because you are trying to access a variable outside of the scope it was created in. However, since result is passed to the method in your example as a parameter, it is considered to be accessible by the for loop that is created later within the scope of the method. Essentially, the result variable that you already defined will simply reference a new value inside of your for loop. If we attempted to create a new result variable in the for loop such as newResult, you would not be able to reference it outside of the scope of that for-loop.
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 am trying to write a class with all the methods I need for my main, but am having trouble figuring out how to ascertain the desired values using the methods. The ones I am having trouble with are getAverageLength and getCount.
Current Output:
The length of Line 1 is 1.0
The length of Line 2 is 10.0
There are 0 lines and the average length is 0
The length of Line 1 is 1.0
The length of Line 2 is 10.0
The length of Line 3 is 7.0
There are 0 lines and the average length is 0
Expected Output:
The length of Line 1 is 1
The length of Line 2 is 10
There are 2 lines and the average length is 5.5
The length of Line 1 is 7
The length of Line 2 is 10
The length of Line 3 is 7
There are 3 lines and the average length is 8.0
This is the portion of my main method that I am using.
public class TestParts {
public static void main(String[] args) {
MyLine ml1 = new MyLine();
MyLine ml2 = new MyLine(10);
System.out.println("The length of Line 1 is " + ml1.getLength());
System.out.println("The length of Line 2 is " + ml2.getLength());
System.out.println("There are " + MyLine.getCount() +
" lines and the average length is " + MyLine.getAverageLength());
MyLine ml3 = new MyLine(7);
ml1.setLength(7);
System.out.println("The length of Line 1 is " + ml1.getLength());
System.out.println("The length of Line 2 is " + ml2.getLength());
System.out.println("The length of Line 3 is " + ml3.getLength());
System.out.println("There are " + MyLine.getCount() +
" lines and the average length is " + MyLine.getAverageLength());
}
}
And the following is the seperate class that I am writing to calculate the values.
class MyLine {
private double getLength;
MyLine() {
getLength = 1;
}
double getLength() {
return getLength;
}
MyLine(double setLength) {
getLength = setLength;
}
public void setLength(int i) {
getLength = getLength();
}
public static int getCount() {
return 0;
}
public static int getAverageLength() {
return 0;
}
}
For getCount, make a static int that is incremented by each constructor.
For getAverageLength, make a static int with the sum of the lines that is added to by each constructor and divide it by the count.
There are several problems with the code.
First, recommend documenting what the methods are supposed to do in comments.
This will help you and others.
Second, these methods:
public void setLength(int i) {
getLength = getLength();
}
The getLength private member variable is probably badly named.
I suspect the intent was a noun like length whereas getLength() is a method intended to return the current length.
This method takes a primitive int datatype to set a type of double.
Was this intentional?
Looks like a misconception.
Moreover, it has no function as it just sets the getLength (again, should be length) variable to the return value of the method getLength(), which in turn returns the value of getLength. This is a remedial logic and basic math problem:
A = 1 = getLength() = A = 1
public static int getCount() {
return 0;
}
Why would anything other than zero be expected to be returned from this method?
public static int getAverageLength() {
return 0;
}
Same here ... fundamental logic problem.
I would not post this kind of question on the forum as it lacks doing basic homework before posing the question.
build a HashMap<MyLine, Integer>
Integer is the length of the MyLine.
you just put those MyLine objects you want to count into that map.
{ml1:0,
ml2:10,
ml3:7}
then you could calculate everything you want.
Please see my comments in the code to better explain things. Basically having issues with the methods below. I can get the load method to run but I am unsure whether the numbers entered by the user are actually being stored in the array.
In addition, the search method has been throwing things off and i think its going in a loop.
See below for more. Thank you in advance.
import java.util.Scanner;
public class MyContainer {
private int[] values;
private int size;
public MyContainer(){
values=new int[50];
size=0;}
//Load Method - Display a message to the user
//and get positive intergers from user
public void load()
{
int input;
Scanner in = new Scanner(System.in);
System.out.println("Enter a series of positive integers (Negative to Terminate): ");
input=in.nextInt();
while (input >=0) {
values[size]=input;
size++;
input=in.nextInt();
}
}//End Load
//Compute Average from the above entered numbers
public double computeAverage() {
double avg= 0.0;
int count = 0;
while(values[size] >=0)
{avg = avg + values[size];
count++;
}
size = size + 1;
avg = avg / size;
return avg;
}
//Get user input to search for a number in the array
public boolean search(int myInt){
while(values[size] >=0) {
if (values[size] == myInt){
return true;}
else{
size++;}
}
return false;
}
//print the position of the number
public void print(){
for(int i=0;i>=size;i++) {
System.out.println("The number at position " + i + " is " + values[i]);
}
}
}
That is what I have so far. I also have created a tester class for the above container.
class Tester {
public static void main(String[] args) {
MyContainer in = new MyContainer();
in.load();
in.computeAverage();
in.search(); //i know for a fact this is wrong just stuck
in.print();
}
}
Any advise/help would be greatly appreciated. My professor is terrible at teaching and the book only partially explains things.
Your search() method has parameters that you aren't passing.
you declare it as...
public boolean search(int myInt) {
while (values[size] >= 0) {
if (values[size] == myInt) {
return true;
} else {
size++;
}
}
return false;
}
but call it with...
in.search();
This code won't even compile. For argument sake I set this to 5.
In your computeAverage() method, this is an infinite loop...
while (values[size] >= 0) {
avg = avg + values[size];
count++;
}
The main problem I believe you are running into is the reuse of your size variable. In the load function it will work as expected say for loading in 10 numbers size will be 10 and elements 0->9 in values will have numbers in them. However when you get to computeAverage size will still be 10. So you are in an infinite loop.
while(values[size] >= 0) {
avg = avg + values[size];
count++;
}
First iteration you will check values[10] (which is wrong remember valid elements are only in 0->9 if size is 10). Next iteration avg and count are increased but size remains the same so you will add the same number to avg and continue in the loop. You should use a different conditional for your while loops in computeAverage and search. The last negative number entered to quit will not be in the array; you will need to use something else. As a hint it will involve count and size.