I'm confusing myself here. My goal was to make a simple program that took the number of values the user wants to average, store them in an array (while adding them together) and finally giving the average of these numbers.
My thing is, I am trying to understand the concept of multiple classes and methods as I am new so I tried using another class just do do all the work, while the Main class would just create the object from the other class, and then run their methods. Maybe I am asking something impossible. Take a look at my code.
This is my Main class:
public class Main
{
public static void main(String[] args)
{
System.out.println("Please enter numbers to average together");
OtherClass averages = new OtherClass();
averages.collectNumbers();
averages.AverageNumbers();
}
}
Now I am not sure if anything goes in those parameters, or if I can even use "averages.AverageNumbers();" without creating another object with "OtherClass" called something else? I am pretty sure it's legal though.
Here is my other class for this project entitled "OtherClass"
import java.util.Scanner;
public class OtherClass // using this to name obj
{
public void collectNumbers() //name of our method that does things
{
Scanner sc = new Scanner(System.in);
System.out.println("how many integers would you like to average? ");
int givenNum = sc.nextInt();
System.out.println("Alright, I will average " + givenNum + " values. \nPress enter after each:");
int[] numCollect = new int[givenNum];
int sum = 0;
for (int i = 0; i < numCollect.length; i++)
{
numCollect[i] = sc.nextInt();
sum = sum + numCollect[i];
}
System.out.println(sum);
}
public int AverageNumbers(int givenNum, int sum)
{
int average = sum / givenNum;
System.out.println(average);
return average;
}
}
So when I run this now with the the method AverageNumbers, it does not work. I am suspecting that maybe I am passing in the integers wrong? I have been toying with it for about an hour now, so I am asking for help. How do I make this work?
This will work if you declare sum and givenNum as fields of your OtherClass, instead of as local variables. So, before the collectNumbers method, write
private int sum;
private int givenNum;
and remove the declarations of these two variables inside collectNumbers. So, for example, instead of
int givenNum = sc.getInt();
you'll just have
givenNum = sc.getInt();
because the variable already exists. Also change the declaration of the averageNumbers method to
public int averageNumbers()
because you no longer need to pass those two values in to this method.
This is the archetypical example of using the objects of a class to carry a small amount of data around, instead of just using a class as a way to group methods together. The two methods of this class work with sum and givenNum, so it makes sense to store these in each object of this class.
Lastly, in your averageNumbers method, you have an integer division, which will automatically round down. You probably want a floating point division instead, so you could write
double average = (double) sum / givenNum;
which converts sum to a double-precision floating point number before the division, and therefore does the division in floating point, instead of just using integers. Of course, if you make this change, you'll need to change the return type of this method to double too.
Related
I am trying to make a simple android app that can add and subtract numbers, but my challenge is to make sure that the program is Object-Oriented. Currently I have been told that it is linear, but I am confused as to how it has remained linear after trying many times to make it object-oriented. How can I make this object oriented programming. Here is my code.
import java.util.Scanner;
public class addNumbers {
public static void main(String[] args)
{ // Begin main
Scanner input = new Scanner( System.in ); // Instantiate object input
System.out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
System.out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
double sum=number1 + number2; // Add the numbers
double difference = number1 - number2; // Subtract number 2 from number1
System.out.printf("\nSum = %f\n", sum); // Print the sum
System.out.printf("Difference = %f", difference); // Print the difference.
}
} // end main
My applications use this boilerplate to execute inside an object. If you start like this, you can add methods as you need them.
public class Demo
{
public static void main (String[] args)
{
final Demo app = new Demo ();
app.execute ();
}
private void execute ()
{
// Do stuff here.
}
}
Whoever gave you this assignment is using wrong and confusing terms, because linear programming is something else. But that's a different topic.
Even though this program is not complex, we can introduce some classes by modelling the flow of the program and/or the math operations.
Here is one idea... we could have a class called Operands, that has a method to read the numbers from the input while it prints instructions to the output. Then it stores these two numbers.
So something like this (I am using static class here instead of just class in case you will put this inside your public class addNumbers)
static class Operands {
public final double first;
public final double second;
public Operands(double first, double second) {
this.first = first;
this.second = second;
}
public static Operands readFromIO(InputStream in, PrintStream out) {
Scanner input = new Scanner(in); // Instantiate object input
out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
return new Operands(number1, number2);
}
}
Then we could have another class called Calculator, that has a method to set the operands setOperands(Operands operands) and two methods to get the results for the sum and the difference. The methods could be called getSum and getDifference.
static class Calculator {
private double sum = 0;
private double difference = 0;
public void setOperands(Operands operands) {
sum = operands.first + operands.second;
difference = operands.first - operands.second;
}
public double getSum() {
return sum;
}
public double getDifference() {
return difference;
}
}
Then in the main method of the program, we just need to make an instance of the Calculator class and set the Operands on the instance. We read these operators by calling Operands.readFromIO(...). Then we retrieve the sum and the difference from the calculator instance.
So the code in main looks like this
public static void main(String[] args) {
Calculator c = new Calculator();
Operands operands = Operands.readFromIO(System.in, System.out);
c.setOperands(operands);
System.out.printf("Sum = %f\n", c.getSum()); // Print the sum
System.out.printf("Difference = %f\n", c.getDifference()); // Print the difference.
}
This is just one way to do it with some objects.
Another way could be to use an interface called Operation that contains a calculate(Operands operands) method and have 2 more classes Addition and Subtraction implement the interface. Then you would use those two classes to calculate the results.
I am trying to build a Java program based on this UML:
UML of Polygon Class
But I ran into a few hiccups along the way. This is my basic code:
import java.util.Scanner;
public class Polygon {
private int[] side;
private double perimeter;
public double addSide(double length[]) {
int i = 0;
double perimeter = 0;
while(length[i] > 0){
perimeter += (double)length[i];
i++;
}
return perimeter;
}
public int[] getSides() {return side;}
public double getPerimeter() {return perimeter;}
public static void main(String[] args) {
Polygon polygon=new Polygon();
polygon.side = new int[99];
int i=0;
do{
System.out.print("Side length(0 when done): ");
Scanner in = new Scanner(System.in);
polygon.side[i] = in.nextInt();
i++;
}while(polygon.side[i]>0);
//polygon.perimeter = addSide((double)polygon.side);
System.out.println("Perimeter of " + i + "-sided polygon: " + polygon.getPerimeter());
}
}
There's a couple of issues.
I got it to compile but when it accepts the first side[0], it immediately stops and gives me the perimeter. Exiting the loop eventhough the conditions haven't been met for it to so. So there's an issue with my while-loop. I want it to keep accepting values into the side[] array until a non-positive value is entered.
Also the UML requires I use double parameter-type for the addSide method. I tried to cast it in the argument and tried a couple of other different things with no success. How would one transition an int-array into a double-array for the perimeter calucalation which has to be double as per the requirements.
I wouldn't surprised if I made other issues since I'm new to Java so feel free to point them out to me or if you have a better way to go about this, I would love to learn your thinking.
Any advice is appreciated!
There are a number of issues with your code.
First, differences from the UML specification:
You haven't used the given signature for addSide. The UML says that it takes a single double parameter, and returns nothing, i.e. void in Java. You are passing an array of double and returning a double.
You are directly accessing sides in your main method. Java allows you to do this, because your main method is part of the Polygon class, but the UML shows that the field is private. What does direct manipulation of sides do to the validity of the value in perimeter?
The UML shows the class having a field sides of type int. Your field sides is of type int[].
Similarly you haven't used the given signature for getSides, which should probably have been named getNumberOfSides.
Your code has quite a few other issues, but I think you should fix the issues above first.
A futher hint: The only things that the Polygon class can do is to tell you how many sides it has and what its total perimeter is. It does not care about the details of individual sides.
(Off topic, it is strange to include main in the UML description of Polygon)
I've made a program that generates a random number but every time it gives back 0.0
Program:
import java.util.*;
public class RandomNumber {
public static void main(String args[]){
double QuantityColors = 5;
double Mastermind = 0;
Random(QuantityColors, Mastermind);
System.out.println(Mastermind);
}
public static double Random(double QuantityColors, double Mastermind){
Mastermind = Math.random();
Mastermind = Mastermind * QuantityColors;
Mastermind = (int) Mastermind;
return Mastermind ;
}
}
I've been searching where the problem is, but the problem is in the return.
a) you are doing nothing with the result of "Random".
b) you can not modify Java argument. See change a functions argument's values?
First of all, you can use a builtin function to generate a next integer with a certain upper bound: Random.nextInt(int). For instance:
Random rand = new Random();
int masterMind = rand.nextInt(QuantityColors);
Instead of writing a Random method yourself.
It is nearly always better to use builtins since these have been tested extensively, are implemented to be rather fast, etc.
Next you seem to assume that Java uses pass-by-reference. If you perform the following call:
Random(QuantityColors, Mastermind);
Java will make a copy of the value of MasterMind. Setting the parameter in a method has no use. The only way to set a value - not encapsulated in an object - is by returning value. So:
MasterMind = Random(QuantityColors, Mastermind);
To make a long story short: the method does not return 0, you simply don't do anything useful with it.
A better solution would thus be to drop the Random method and use:
import java.util.*;
public class RandomNumber {
public static void main(String args[]){
int quantityColors = 5;
Random rand = new Random();
int mastermind = rand.nextInt(QuantityColors);
System.out.println(mastermind);
}
}
Further remarks
In your random method:
public static double Random(double QuantityColors, double Mastermind){
the MasterMind parameter is rather useless since you immediately set it with another value, so you better remove it and use a local variable instead.
Furthermore Java standards say that the name of classes, interfaces, etc. start with an uppercase; the names of methods and variables with lowercase.
Finally it is unclear why you use doubles since all the values you calculate are clearly integral.
It looks like your code would work if you wrote
Mastermind = Random(QuantityColors, Mastermind);
...because Java is pass by value, so calling a function will not change the variable you passed in.
We've been learning about methods in java (using netbeans) in class and I'm still a bit confused about using methods. One homework question basically asks to design a grade calculator using methods by prompting the user for a mark, the max mark possible, the weighting of that test and then producing a final score for that test.
eg. (35/50)*75% = overall mark
However, I am struggling to use methods and I was wondering if someone could point me in the right direction as to why my code below has some errors and doesn't run? I don't want any full answers because I would like to try and do it best on my own and not plagiarise. Any help would be greatly appreciated :)! (Also pls be nice because I am new to programming and I'm not very good)
Thanks!
import java.util.Scanner;
public class gradeCalc
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
scoreCalc();
System.out.print("Your score is" + scoreCalc());
}
public static double scoreCalc (int score1, int maxMark, double weighting, double finalScore)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter mark");
in.hasNextInt();
score1 = in.nextInt();
System.out.print("Enter Max mark");
in.hasNextInt();
maxMark = in.nextInt();
System.out.print("Enter weighting as a decimal (eg. 75% = 0.75)");
in.hasNextInt();
weighting = in.nextInt();
finalScore = (score1/maxMark)* weighting;
return finalScore;
}
}
You are calling your method scoreCalc() without passing the parameters you defined.
When you are calling it, it was defined as having 3 parameters.
scoreCalc(7, 10, 3.0, 8.0);
Also, when creating a class, start it with upper case, GradeCalc
As you can see scoreCalc method needs a set of parameters, but you call it without parameters.
The second: there is no need in Scanner in = new Scanner(System.in); into your main(String[] args) method. You are calling it into scoreCalc method.
Third: you are calling scoreCalc twice. The first call is before System.out.println, the second is into System.out.println. And your application will ask user twice to enter values.
store result value in a variable and show it later:
double result = scoreCalc(.... required params .....);
System.out.println("Your score is: " + result);
To start :
1) Follow coding conventions. (Class name should start with a capital letter).
2) In your context, you don't need Scanner in = new Scanner(System.in); in main() because you are not using it.
3) You are a calling the method scoreCalc() without parameters. Whereas, the method needs to be called with parameters.
4) A method,is a module. It as block of code which increases re-usability. So I suggest that accept the values from user in main() method and then pass them to the method for calculation.
A couple of things spring to mind:
You execute scoreCalc() twice. Probably you want to execute it once and save the result in a double variable like: double score = scoreCalc().
Speaking of scoreCalc(): Your definition takes 4 parameters that your don't have as input for that method. You should remove those from your method definition, and instead add score1, maxMark, weighting and finalScorevariable declarations in the method-body.
In your main function, you declare and instantiate a Scanner object you don't use.
Be careful with arithmetic that mixes int and double.
Some mistakes/errors to point out are:-
1) You do not need this statement Scanner in = new Scanner(System.in); in your main() , as you are not taking input from user through that function.
2) Your function scoreCalc (int score1, int maxMark, double weighting, double finalScore) takes parameters, for example its call should look like scoreCalc(15, 50, 1.5, 2.7), but you are calling it as scoreCalc(), that is without paramters from main().
Edit:- There is one more serious flaw in your program, which might work , but is not good coding. I wont provide code for it , and will leave implementation to you. Take input from user in the main() (using scanner) , assign the result to a temp variable there, and then pass that variable as parameter to the function scoreCalc()
//pseudocode in main()
Scanner in = new Scanner(System.in);
int score= in.nextInt();
.
.
.
scoreCalc(score,...);
Or you can make your scoreCalc function without parameters, and take user input in it (like present), and finally return just the result to main().
Both approaches seem appropriate and you are free to choose :)
As opposed to other answers I will start with one other thing.
You forgot about the most important method - and that is the Constructor.
You have to create a grade calculator, so you create a class(type) that represents objects of grade calculators. Using the Java convention this class should be named GradeCalculator, don't use abbreviations like Calc so that the name is not ambiguous.
So back to the constructor - You have not created your Calculator object. It may not be needed and you may achieve your goal not using it, but it's not a good practice.
So use this method as well - this way, you'll create actual Calculator object.
It can be achieved like that:
public static void main(String[] args)
{
GradeCalculator myCalculator = new GradeCalculator();
}
And now you can imagine you have your calculator in front of you. Whan can you do with it?
Getting a mark would be a good start - so, what you can do is:
myCalculator.getMark()
Now you'll have to define an method getMark():
private void getMark() { }
In which you would prompt the user for the input.
You can also do:
myCalculator.getMaxMark() { }
and that way get max mark (after defining a method).
The same way you can call method myCalculator.getWeighting(), myCalculator.calculateFinalResult(), myCalculator.printResult().
This way you'll have actual object with the following mehtods (things that it can do):
public GradeCalculator() { } //constructor
private void getMark() { } //prompts user for mark
private void getMaxMark() { } //prompts user for max mark
private void getWeighting() { } //prompts user for weighting factor
private void calculateFinalResult() // calculates the final result
private void printResult() // prints the result.
And that I would call creating a calculator using methods - and that I would grade highly.
Try to think of the classes you are creating as a real objects and create methods representing the behaviour that objects really have. The sooner you'll start to do that the better for you.
Writing whole code in one method is not a good practice and in bigger applications can lead to various problems. So even when doing small projects try to do them using best practices, so that you don't develop bad habbits.
Edit:
So that your whole program can look like this:
import java.util.Scanner;
public class GradeCalculator
{
//here you define instance fields. Those will be visible in all of your classes methods.
private Scanner userInput; //this is the userInput the calculator keypad if you will.
private int mark; //this is the mark the user will enter.
private int maxMark; //this is the mark the user will enter.
private int weightingFactor; //this is the weighting factor the user will enter.
private int result; //this is the result that will be calculated.
public static void main(final String args[])
{
Scanner userInput = new Scanner(System.in); //create the input(keypad).
GradeCalculator calculator = new GradeCalculator(userInput); //create the calculator providing it with an input(keypad)
calculator.getMark();
calculator.getMaxMark();
calculator.getWeightingFactor();
calculator.printResult();
}
private GradeCalculator(final Scanner userInput)
{
this.userInput = userInput; //from now the provided userInput will be this calculators userInput. 'this' means that it's this specific calculators field (defined above). Some other calculator may have some other input.
}
private void getMark() { } //here some work for you to do.
private void getMaxMark() { } //here some work for you to do.
private void getWeightingFactor() { } //here some work for you to do.
private void printResult() { } //here some work for you to do.
}
Please mind the fact that after constructing the Calculator object you don't have to use methods that are static.
Looks like this is the week for this type of question. And after reading through all of the new ones and several old ones, I'm no less confused!
I have a text file with 5 employees, each having 10 salary values listed beneath their name. I am to read in this file, find and display the employee Name, minimum salary, maximum salary and the average salary for each person. I must have 3 loops: One to control reading the file, one to lad the data into the array, and one to do the calculations. I have to print the information for each person on one line, and i must allow decimals rounded to 2 decimal places apparently using Math.round which I've never heard of!
I am embarrassed to show you the mess of code I have because it's not much, but I don't know after reading all that I have if I've even started correctly. I do not know if I have even the right idea of how to proceed. Your help is appreciated.
UPDATED CODE: AGAIN!
import javax.swing.*;
import java.io.*;
public class MinMaxSalary3
{
public static void main(String args[])throws Exception
{
// Declare input file to be opened.
FileReader fr = new FileReader ("salary.dat");
BufferedReader br = new BufferedReader (fr);
//General Declarations
final String TITLE = "Employee's Salary Report";
String employeeName, salaryString;
double avgSalary=0.0;
double totalSalary = 0.0;
double sum = 0.0;
// Declare Named Constant for Array.
final int MAX_SAL = 10;
// Declare array here.
int salary[] = new int[MAX_SAL];
System.out.println (TITLE);
while ((employeeName = br.readLine()) != null)
{
System.out.print ("" + employeeName);
// Use this integer variable as your loop index.
int loopIndex;
// Assign the first element in the array to be the minimum and the maximum.
double minSalary = salary[1];
double maxSalary = salary[1];
// Start out your total with the value of the first element in the array.
sum = salary[1];
// Write a loop here to access array values starting with number[1]
for (loopIndex = 1; loopIndex < MAX_SAL ;loopIndex++)
// Within the loop test for minimum and maximum salaries.
{
if (salary[loopIndex] < minSalary)
{
minSalary = salary[loopIndex];
if (salary[loopIndex] > maxSalary)
maxSalary = salary[loopIndex];
}
{
// Also accumulate a total of all salaries.
sum += sum;
// Calculate the average of the 10 salaries.
avgSalary = sum/MAX_SAL;
}
// I know I need to close the files, and end the while loop and any other loops. I just can't think that far right now.
}
{
// Print the maximum salary, minimum salary, and average salary.
System.out.println ("Max Salary" + maxSalary);
System.out.println ("Min Salary" + minSalary);
System.out.println ("Avg Salary" + avgSalary);
}
System.exit(0);
}
}
}
I must have 3 loops: One to control reading the file, one to lad the
data into the array, and one to do the calculations.
What I've written below might just be more gobbledygook to you now, but if you ever get past this class it might be useful to know.
Another way to look at this would be more object-oriented and better decomposition to boot: You need an object to hold the data, to perform the calculations, and render output. How you get that data is immaterial. It's files today; next time it might be HTTP requests.
Start with an Employee object. I deliberately left out a lot of detail that you'll have to fill in and figure out:
package model;
public class Employee {
private String name;
private double [] salaries;
public Employee(String name, int numSalaries) {
this.name = name;
this.salaries = new double[numSalaries];
}
public double getMinSalary() {
double minSalary = Double.MAX_VALUE;
// you fill this in.
return minSalary;
};
public double getMaxSalary() {
double maxSalary = Double.MIN_VALUE;
// you fill this in.
return maxSalary;
}
public double getAveSalary() {
public aveSalary = 0.0;
if (this.salaries.length > 0) {
// you fill this in.
}
return aveSalary;
}
}
The beauty of this approach is that you can test it separately, without worrying about all the nonsense about file I/O. Get this object right, put it aside, and then tackle the next piece. Eventually you'll have a clean solution when you assemble all these smaller pieces together.
Test it without file I/O using JUnit:
package model;
public class EmployeeTest {
#Test
public void testGetters() {
double [] salaries = { 10000.0, 20000.0, 30000.0, 40000.0 };
Employee testEmployee = new Employee("John Q. Test", salaries);
Assert.assertEquals("John Q. Test", testEmployee.getName());
Assert.assertEquals(10000.0, testEmployee.getMinSalary(), 1.0e-3);
Assert.assertEquals(40000.0, testEmployee.getMaxSalary(), 1.0e-3);
Assert.assertEquals(25000.0, testEmployee.getMinSalary(), 1.0e-3);
}
}
The approach you would want to espouse in this situation is an object-oriented approach. Bear in mind that objects are a representation of related data. Consider that an Employee may have information about their salary, name, and what department they work in (as an example).
But that's just one Employee. You may have hundreds.
Consider creating a model of an Employee. Define what is most pertinent to one of them. For example, they all have to have a name, and have to have a salary.
One would then elect to handle the logic of finding information about the collection of Employees - including min, max, and average salaries - outside of the scope of the generic Employee object.
The idea is this:
An Employee knows everything about itself.
The onus is on the developer to tie multiple Employees together.
It's possible that I don't know enough about what your problem is specifically looking for - I'm not even sure that you can use objects, which would really suck - but this is definitely a start.
As for your compilation errors:
salary is a double[]. An array holds many different values of type double inside of it, but a double[] isn't directly a double. Assigning a non-array type to an array type doesn't work, from both a technical stance, and a semantic stance - you're taking something that can hold many values and trying to assign it to a container that can hold one value.
From your code sample, you want to use a loop (with a loop variable i) to iterate over all elements in salary, and assign them some value. Using just salary[0] only modifies the first element.