adding parts of a javabean together - java

How do I take the return values of some methods that I wrote in a bean and add them together for an return? For instance:
public double getPart1Average() {
String[] average = new String[]{Part01, Part02, Part03};
int sum = 0;
for (String input : average) {
sum += Integer.parseInt(input);
}
return ((sum * (10) / (3)) * .25);
}
If I have six methods like mostly like this and I need to write a method to return a sum of these methods how would I go about doing this?
Thanks!

If I understood your question then I you just need this:
public static void main(String[] args) {
System.out.println("Sum Of Average:: " + new Average().getSumOfAverage());
}
private double getSumOfAverage() {
return getPart1Average() + getPart2Average() + getPart3Average(); // call all required method here
}
Let me know if this is not what you want.

Related

How to manipulate numbers from the user in a method?

I want to perform a couple of methods, but only with the numbers the user will be giving, so the methods will ask for int x, and int y, and I want to put the user's data into those fields, for the example, I will be using the Scanner technology, I have an idea, that it could be something like:
public class TestClass1 {
static Scanner scanit = new Scanner(System.in);
//How to manipulate int numbers from the user, in order to use them in methods?
public static void main(String[] args) {
TestClass1 pumpkin = new TestClass1();
System.out.println("Enter your numbers");
int coordenate1= scanit.nextInt();
int coordenate2= scanit.nextInt();
//Here works actually right
System.out.println(coordenate1 + "and" + coordenate2);
System.out.println("Common sum without method" + coordenate1 + coordenate2);
System.out.println("using the method sum" /*Don't know how to implement it here*/ );
System.out.println("here with multiplication as well");
//this is another idea I think would work
TestClass1.addition(coordenate1, coordenate2);
TestClass1.multiplication(coordenate1, coordenate2);
scanit.close();
}
public static void addition(int coordenate1, int coordenate2) {
System.out.println(coordenate1+coordenate2);
}
public static void multiplication (int coordenate1, int coordenate2) {
System.out.println(coordenate1*coordenate2);
}
}
From what I have seen from the comments, you want to "execute":
public static void addition(int coordinate1, int coordinate2) {
System.out.println(coordinate1 + coordinate2);
}
Right?
Well, if you want to print the value on that "using the sum method", you can change the return type from the addition method from void (no return at all) to String, using the return keyword, such as this:
public static String addition(int coordenate1, int coordenate2) {
int result = coordenate1 + coordenate2;
return String.valueOf(result);
}
Then later to call the method like:
System.out.println("using the sum method " + TestClass1.addition(coordenate1, coordenate2));
Or since your addition method already outputs the result, simply call it outside the first println() call.

How to call and declare a method with a variable amount of arguments?

I'm hopelessly trying to call a function with (int = amountCoefficients) amount of arguments, and declaring a function with that amount of arguments too.
What makes it harder is that for example amountCoefficients = 5, then it means that there's an array of 5 blocks that each have a value (double). So the first argument would have to be equal to the value of the first block of that array, the second argument would have to be equal to the value of the second block of that array etc.
And beforehand we don't know how many arguments we need, as that depends on the amount of doubles that are filled in by the user, so amountCoefficients could be equal to 2, 4, or any other positive integer.
I'm pretty new to Java and I really don't have no idea what to do. As you can see below I tried to do something with a for loop, but I don't think that works.
public class Interpol {
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
//acquire user input (polynomial coefficients and interval values x1 and x2)
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
int amountCoefficients = 0;
while (scanner.hasNextDouble()) {
polynomialCoefficients.add(scanner.nextDouble());
amountCoefficients++;
}
String in = scanner.next();
double x1 = scanner.nextDouble();
double x2 = scanner.nextDouble();
//call method f to determine the polynomial function
int i = 0;
for (i = 0; i < amountCoefficients; i++) {
f
}
//call method findaroot to determine the root
//print result
}
}
public static double f(double x) {
//function of which a root is to be found
}
You can create a method that takes a list or array. Then the method can use List.size() and array.length to process every object.
public static void main(String[] args){
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
// get data
...
process(polynomialCoefficients);
}
public void process(List<Double> coefficients){
for(int i = 0; i < coefficients.size(); i ++){
System.out.println("Element " + i + ": " + coefficients.get(i));
}
}
You can use the VarArgs notation to receive an arbitrary amount of parameters, although they will be converted into an array. This is achieved by a code like the following:
public void printOneEachLine(String... parameters) {
for (String parameter : parameters) {
System.out.println(parameter);
}
}
And you can call it with:
printOneEachLine("msg1", "msg2");
printOneEachLine("msg3", "msg4", "msg5", "msg6");

Getting error for the product of items in an array

I want to take inputs from console and use the numbers in performing calculations. I want to stop receiving items into array when i receive some ref value like"10"(in this case) from console. As soon as i enter 10 in console the array has to be ended and the values in array have to be multiplied. I have tried this as a program but am getting 0 as answer for the product being performed.
public class Scrap {
private static int i;
private static double[] as;
public static void main(String[] args)
{
as=new double[100];
for(i=0;i<as.length;i++)
{
as[i]=dscan();
if(as[i]==10)
break;
}
double d=1;
for(i=0;i<as.length;i++)
{
d=d*as[i];
}
System.out.println("Product is :"+(d/10));
}
public static double dscan()
{
System.out.print(" : ");
return new Scanner(System.in).nextDouble();
}
}
In your case as=new double[100]; will initialize array with 100 zeros (default value for primitive double) and as.length will always return 100 (the size of initialized array) and not the number of valid elements, so if you enter less than 100 values the rest will remain zeros, which will be used for multiplication..
To make it work you either need to count the number of valid elements in a separate variable and then use it restrict your array window or as Matej sugests use a dynamically sized collection.
this code works ... i improved it to use List instead of array , because at start you dont know how many inputs you will have ... if you dont understand anything , just ask ...
public class Scrap {
private static int i;
private static ArrayList<Double> al = new ArrayList<Double>();
public static void main(String[] args) {
while (true) {
double d = dscan();
if (d != 10) {
al.add(d);
}else{
break;
}
}
double d = 1;
for (i = 0; i < al.size(); i++) {
d = d * al.get(i);
}
System.out.println("Product is :" + (d / 10));
}
public static double dscan() {
System.out.print(" : ");
return new Scanner(System.in).nextDouble();
}
}

Java ArrayList<Double> as Parameter

I am currently working on a lab and would like to know how to handle the following problem which I have spent at least two hours on:
I am asked to create an ArrayList containing the values 1, 2, 3, 4 and 10. Whilst I usually never have any trouble creating an ArrayList with said values, I am having trouble this time. Should I create the ArrayList outside of the method or inside the method? Whichever way I have attempted it, I have been presented with numerous error messages. How do I add values to this ArrayList parameter? I have attempted to add values to it when calling it from the main method, but this still doesn't work. Here is the method in question.
public static double ScalesFitness(ArrayList<Double> weights){
//code emitted for illustration purposes
}
If anybody could help me it would be greatly appreciated. If any more code is required, then please let me know.
Thank you so much.
Mick.
EDIT: The code for the class in question is as follows:
import java.util.*;
public class ScalesSolution
{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
for(int i = 0; i > s.length(); i++){
CS2004.UI(0,1);
if(i == 0){
System.out.println(s + "0");
}
else if(i == 0){
System.out.println(s + "1");
}
}
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public static double scalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
double L = 0;
double R = 0;
for(int i = 0; i < scasol.length(); i++){
if(lhs == 0){
L = L + i;
}
else{
R = R + i;
}
}
int n = scasol.length();
return(Math.abs(lhs-rhs));
}
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
The other class file that I am using (Lab7) is:
import java.util.ArrayList;
public class Lab7 {
public static void main(String args[])
{
for(int i = 0 ; i < 10; ++i)
{
double x = CS2004.UI(-1, 1);
System.out.println(x);
}
System.out.println();
ScalesSolution s = new ScalesSolution("10101");
s.println();
}
}
you can these
1) use varargs instead of list
public static double scalesFitness(Double...weights)
so you can call this method with :
scalesFitness(1.0, 2.0, 3.0, 4.0, 10.0);
2) create the list outside your method
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(1.0);
weights.add(2.0);
weights.add(3.0);
weights.add(4.0);
weights.add(10.0);
scalesFitness(weights);
Towards your initial posting, this would work:
scalesFitness (new ArrayList<Double> (Arrays.asList (new Double [] {1.0, 2.0, 4.0, 10.0})));
You may explicitly list the values in Array form, but
you have to use 1.0 instead of 1, to indicate doubles
you have to prefix it with new Double [] to make an Array, and an Array not just of doubles
Arrays.asList() creates a form of List, but not an ArrayList, but
fortunately, ArrayList accepts a Collection as initial parameter in its constructor.
So with nearly no boilerplate, you're done. :)
If you can rewrite scalesFitness that would be of course a bit more easy. List<Double> as parameter is already an improvement.
Should I create the ArrayList outside of the method or inside the method?
The ArrayList is a parameter for the method so it need to be created outside the method, before you invoke the method.
You need to import ArrayList in the file that includes your methods. This is probably solved but that's the issue I was encountering.

How to turn static methods into non-static. Small explanation/examples related to java oop

I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.

Categories