basic java parameter passing, computation inside a method - java

i have initialized a variable value and an inputted value.. netbeans is giving me errors.. can anyone please point out the problem with my code
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
static Scanner sc = new Scanner(System.in);
static double maxLoad = 500;
static double currLoad;
static double loadInput = 0;
public static void main(String[] args) {
String cpNumber;
System.out.println("Enter Cellphone Number");
cpNumber = sc.nextLine();
System.out.println("Enter load to be bought");
loadInput = sc.nextDouble();
computeLoad(maxLoad, loadInput);
System.out.println(currLoad);
}
public static double computeLoad(double x, double y) {
double z = 0;
x - y = z;
return z;
}
}
i got another error. it keeps returning 0..

There are several problems with your code:
1) When you assign a variable, put the variable on the left, and the expression on the right
2) Currently, the return value of computeLoad is ignored. Even when you fix your function to compile, it is not going to work, because currLoad that you print would remain initialized to its default value.
You have two options to fix this:
Change the call to currLoad = computeLoad(maxLoad, loadInput);, or
Change the computeLoad to void, and assign currLoad right there.

it should be:
public static double computeLoad(double x, double y) {
return x- y;
}

x - y = z;
This is wrong. Assignment has to be left to right.
like : z = x - y;

x - y = z; is not a valid Java statement. The assignment operator (=) evaluates the right operand (which may be any kind of expression, method call, literal and soon) and assigns it to the left operand (which has to be an identifier).
z = x - y; would be correct.

You can't do this:
x - y = z
Because assignment works right to left.
z = x - y
Your code should be the following:
public static double computeLoad(double x, double y) {
double z = 0;
z = x - y;
return z;
}

Related

How to call on a method in Java

import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
Primary test = new Primary();
test.Main();
}
}
class Primary
{
double x;
double y;
double z;
double Small;
double Avg;
int dad;
final int userNumbers = 3;
Scanner in = new Scanner(System.in);
public void Main()
{
System.out.println("Please enter 3 numbers");
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
Primary test = new Primary();
test.Smallest();
test.Average();
System.out.println("The average of the numbers is:" + Avg);
System.out.println("The smallest of the numbers is:" + Small);
}
public void Smallest()
{
if(z < y && z < x)
Small = z;
if (x < z && x < y)
Small = x;
if (y < z && y < x)
Small = y;
}
public void Average()
{
Avg = x + y + z / userNumbers;
}
}
I have no clue what to do since everything ive tried either gives me an error or I'm just not doing it right. I'm not even sure I'm doing what the professor is asking me to do, and he never responds to his emails. If anyone could help me it would be greatly appreciated (And if I'm not doing what my professor is asking please let me know).
Heres his instructions + The assignment on page 248
Around Page 248. Practice Exercise E5.1.You will create one class that has three methods: main(), smallest(), and average(). main() reads the test data values and prints the results. You may want to do this in a loop. smallest() and average() do not read data values or print the results. The main() method reads the data values and prints the results.
Write the following methods and provide a program to test them.
a. double smallest(double x, double y, double z), returning the smallest of the arguments
b. double average(double x, double y, double z), returning the average of the arguments
Here try this....`
let me know how that works
import java.util.ArrayList;
import java.util.Scanner;
package javaapplication17;
public class Question1 {
public static void main(String[] args)
{
double avg, small;
Scanner in = new Scanner(System.in);
System.out.println("Please enter 3 numbers");
double x = in.nextInt();
double y = in.nextInt();
double z = in.nextInt();
//Method calls -----------------------------------
avg = average(x, y, z);
small = smallest(x, y, z);
//Method calls -----------------------------------
System.out.println("The average of the numbers is: " + avg);
System.out.println("The smallest of the numbers is: " + small);
}
public static double smallest(double x, double y, double z)
{
double small = 0;
if(z <= y && z <= x)
small = z;
if (x <= z && x <= y)
small = x;
if (y <= z && y <= x)
small = y;
return small;
}
public static double average(double x, double y, double z)
{
return (x + y + z) / 3.0;
}
}
You do need to learn java to do this. See https://en.wikiversity.org/wiki/Java_Tutorial/Hello_World! and others like it for hints.
To answer the question given to you, you only need one class - you have two. In that class, you need three methods. Two of the methods return values - you have them returning a void. You shouldn't need any field variables in your class.
Structure the class as in the tutorial link. (This isnt' a working answer - you still have to do the homework.)
public class Question1 {
public static void main( String[] args ) {
double x, y, z;
// Add your a loop here to collect your x, y and z
// data and process it
while (true) {
// Collect the data ...
// Call the methods
double smallest = smallest(x, y, z);
double average = average(x, y, z);
// Do something with the results
}
}
public static double smallest(double x, double y, double z) {
double smallValue;
// Add your logic and set smallValue
return smallValue;
}
public static double average(double x, double y, double z) {
// Calculate the average and return that value
// as in the smallest method...
}
}
To test the functions, write another program like the following:
import Question1;
public class TestQuestion1 {
public static void main( String[] args ) {
// Add test code here. Something like
double result = Question1.smallest(1.0, 2.0, 3.0)
// Check that the result is 1.0
// Add other tests - output the results
}

Understanding swap function in java with a program

As I have read online that Java is pass by value and a general swap function won't swap the two values. I also read that it's not possible to swap the values of primitive types. I am wondering why the following program works and displays different valies after swap ?
public class swapMe {
public static void main(String[] args) {
int x = 10 , y = 20;
System.out.println("Before");
System.out.println("First number = " + x);
System.out.println("Second number = " + y);
int temp = x;
x = y;
y = temp;
System.out.println("After");
System.out.println("First number = " + x);
System.out.println("Second number = " + y);
}
}
Is it like somewhere, the original values of x = 10 and y = 20 are still stored somewhere and the swapped values displayed are not correct? Please advise. Thanks
Not entirely sure where you're getting that information, but let's take this one at a time.
As I have read online that Java is pass by value and a general swap function won't swap the two values.
Correct...if the expectation of the swap is to happen by virtue of calling a method.
public void swap(int x, int y) {
int tmp = x;
x = y;
y = tmp;
}
// meanwhile, in main
int x = 10;
int y = 20;
swap(x, y);
System.out.println(x); // still prints 10
System.out.println(y); // still prints 20
Incorrect...if the swap happens inside the method and is utilized somehow.
public void swap(int x, int y) {
int tmp = x;
x = y;
y = tmp;
System.out.println(x); // will print 20 from main
System.out.println(y); // will print 10 from main
}
// meanwhile, in main
int x = 10;
int y = 20;
swap(x, y);
System.out.println(x); // still prints 10
System.out.println(y); // still prints 20
I also read that it's not possible to swap the values of primitive types.
No, this is perfectly possible to do. You can always reassign variables.
As to why your example above works, it's because you're holding onto one of the values while you reassign one of its variables. You're basically putting one value to the side while you copy it over.
Slowly...
int x = 10;
int y = 20;
int tmp = x; // tmp = 10
x = y; // x = 20, tmp = 10
y = tmp; x = 20, y = 10; tmp = 10 (but that doesn't matter)

changing static variables from another method in java

I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.
edited:
I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.
In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.
x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.
I've already written the find() method, but I want to use helper methods to make the code better.
Is what I am trying to do even possible, and if so how do I accomplish it?
public class Test
{
public static boolean find()
{
int x = 10;
int y = 20;
int z = 30;
change(x,y,z); // call helper method to change this method's variables.
System.out.println(x); // should be 20
System.out.println(y); // should be 22
System.out.println(z); // should be 15
}
//helper method to be called from find() method
private static void change(int changeX ,int changeY,int changeZ)
{
//change find() variables.
x = changeX * 2;
y = changeY + 2;
z = changeZ /2;
}
}
The problem comes from your second method. You pass changeX, changeY, and changeZ but try to set the values of x, y, and z. The variables x, y, and z are not within the scope of this method and therefore the program will throw an error.
Moreover, this methodology will not work regardless of these names. Java does not allow you to change the values of primitives when you pass them to a new method. The best solution is probably to put them in an array and change the second method to accept an array. The body of your first method may now look like
int [] intarray = new int[3];
intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
change(intarray);
System.out.println(intarray[0]);
System.out.println(intarray[1]);
System.out.println(intarray[2]);
and the second method would become
private static void change(int [] changeArray) {
changeArray[0] *= 2;
changeArray[1] += 2;
changeArray[2] /= 2;
}
(The *=, +=, and /= operators are shorthand for what you were doing above.
You declared variables inside of method so you don't have access to them, if you want to change them you either make them global(define them outside of method):
public class Test
{
int x;
int y;
int z;
void yourMethod(){
}
}
Or change method find to take x, y and z values as parameters.
You could write a class encapsulating your x, y, z as fields and convert your methods to its instance methods (that is, they should not be static anymore).
public class Calculation {
private int x = 10, y = 20, z = 30;
public boolean find()
{
x = 10;
y = 20;
z = 30;
change(x,y,z); // call helper method to change this method's variables.
System.out.println(x); // should be 20
System.out.println(y); // should be 22
System.out.println(z); // should be 15
}
private void change(int changeX ,int changeY,int changeZ)
and so on.
Then create an instance of it and call your methods on it:
Calculation calculation = new Calculation();
calculation.find();
...
You can achieve that in more organized way :
Create Calculation class then put all your variables and methods on it
File Calculation.java:
public class Calculation {
private int x = 10;
private int y = 20;
private int z = 30;
public void setX(int value){
x = value;
}
public void setY(int value){
y = value;
}
public void setZ(int value){
z = value;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getZ(){
return z;
}
private void change(int changeX, int changeY, int changeZ){
setX(changeX * 2);
setY(changeY + 2);
setZ(changeZ / 2);
}
public void find(){
change(x,y,z);
System.out.println(getX());
System.out.println(getY());
System.out.println(getZ());
}
}
After that just create new object of class Calculation in your main program and call find() method on this object variable
File Main.java:
public class Main {
public static void main(String[] args) {
Calculation c = new Calculation();
c.find();
}
}
Output:
20
22
15

Prompt user to enter 3 numbers, add the 2 highest numbers (Cannot call method)

I'm trying to prompt the user to enter 3 numbers. After those numbers are entered, I am to add the highest two numbers. The main method is to handle all print statements and is to call the other method. I'm not allowed to use for loop for this problem. The variables from the main, should be passed down to the other method.
I am not sure why I am unable to call the method from the main. Here is my code:
public class HW {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter three numbers.");
int x = console.nextInt();
int y = console.nextInt();
int z = console.nextInt();
HW.calLargestSum(); //ERROR
HW.calLargestSum(int x, int y, int z); //STILL ERROR
}
public int calLargestSum(int x, int y, int z){
if ( x > y && x > z && y > z )
return x + y;
else if ( y > x && y > z && x > z )
return y + x;
else if ( z > x && z > y && y > x )
return z + y;
return 0;
}
}
You can't call it because you have not instantiated an HW object. Two solutions:
HW hw = new HW();
hw.calLargestSum();
Or make the method static, so that you don't need to instantiate it:
public static int calLargetSum();
Further... ok, so many problems...
HW.calLargestSum(); //ERROR
There is no method calLargestSum(), there is only calLargestSum(int x, int y, int z).
HW.calLargestSum(int x, int y, int z); //STILL ERROR
You need to pass values here. int x is not a value. You need to pass values like:
HW.calLargestSum(1, 2, 3);
Problem
You are making some mistakes when calling the method from main. The non-trivial mistake is that you can't call non-static from static. This happens because if it is not static then it is an instance method. Thus, it requires an instance to access it.
Static Solution
Make your method static. So change your method to:
public static int calLargestSum(int x, int y, int z)
{ ... }
To call the method, you can use:
calLargestSum(1,2,3);
// or in your case.
calLargestSum(x,y,z);
Instance Solution
The other option is to make a new instance of your class (if you don't want it to use static). Like so:
HW hwObj = new HW();
To call use this:
hwObj.calLargestSum(1,2,3);
To See Returned Value/Print
int largest = calLargestSum(x, y, z);
System.out.println(largest);

Find the max of 3 numbers in Java with different data types

Say I have the following three constants:
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:
// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);
Please let me know what I'm doing wrong.
Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).
you can use this:
Collections.max(Arrays.asList(1,2,3,4));
or create a function
public static int max(Integer... vals) {
return Collections.max(Arrays.asList(vals));
}
If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])
NumberUtils.max(int[])
Math.max only takes two arguments, no more and no less.
Another different solution to the already posted answers would be using DoubleStream.of:
double max = DoubleStream.of(firstValue, secondValue, thirdValue)
.max()
.getAsDouble();
Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so
public static double max(double... n) {
int i = 0;
double max = n[i];
while (++i < n.length)
if (n[i] > max)
max = n[i];
return max;
}
In your example, max could be used like this
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String[] args) {
double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
Java 8 way. Works for multiple parameters:
Stream.of(first, second, third).max(Integer::compareTo).get()
I have a very simple idea:
int smallest = Math.min(a, Math.min(b, Math.min(c, d)));
Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.
Regards,
Norbert
Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().
If you don't like that you can always create your own method for it...
public class test {
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String args[]) {
double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
}
public static Object multiMax(Object... values) {
Object returnValue = null;
for (Object value : values)
returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
: (value instanceof Double) ? (Double) value
: (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
: (returnValue instanceof Double) ? (Double) returnValue
: (Float) returnValue)) ? value : returnValue)
: value;
return returnValue;
}
}
This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.
It might also be throwing an error since there is no such thing as "MY_DOUBLE2".
int first = 3;
int mid = 4;
int last = 6;
//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
You can do like this:
public static void main(String[] args) {
int x=2 , y=7, z=14;
int max1= Math.max(x,y);
System.out.println("Max value is: "+ Math.max(max1, z));
}
if you want to do a simple, it will be like this
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;
public class MaximumFinder
{
// obtain three floating-point values and locate the maximum value
public static void main(String[] args)
{
// create Scanner for input from command window
Scanner input = new Scanner(System.in);
// prompt for and input three floating-point values
System.out.print(
"Enter three floating-point values separated by spaces: ");
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum(number1, number2, number3);
// display maximum value
System.out.println("Maximum is: " + result);
}
// returns the maximum of its three double parameters
public static double maximum(double x, double y, double z)
{
double maximumValue = x; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue)
maximumValue = y;
// determine whether z is greater than maximumValue
if (z > maximumValue)
maximumValue = z;
return maximumValue;
}
} // end class MaximumFinder
and the output will be something like this
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
References Java™ How To Program (Early Objects), Tenth Edition
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));

Categories

Resources