I had an an assignment with this question
Write a function maxArray which receives an array of double's and returns the maximum value in the array. using this function
double maxArray(double dar[], int size);
I did what he want and I had problem with the calling sentence within the main method !!
here is my code :
public class Q3 {
public static void main(String[] args) {
double dar[] = { 22.5 , 10.23 , 15.04 , 20.77 };
double max = maxArray(dar,4);
System.out.println("the largest number is : " + max);
}
double maxArray(double dar[], int size) {
double maxV = 0;
for (int i = 0; i < dar.length; i++) {
if (dar[i] > maxV ) {
maxV = dar[i];
}
}
return maxV;
}
}
The reason you can't call your method from main() is that main() is static whereas your method isn't.
Change it to:
static double maxArray(double dar[], int size)
While you're at it, remove size since it's not necessary.
It is probably also worth noting that your method would fail if the array were to contain negative numbers.
your maxArray method is a non static method. you cannot access non-static methods from static methods without an instance of the class, you should create an instance of your class and call maxArray method
double max = new Q3().maxArray(dar,4);
Or alternatively, you could always mark your maxArray method static and call it directly from main method.
Declare your maxArray as static, so you can access it as from a static method main()
or
You create an instance of your class and call it from the object.
your issue is you are trying to call maxArray, a non-static method, from your main method, which is static. That's a problem because a non-static method can only be called from an instance of the class, whereas a static method is called via the class itself.
Either make your maxArray a static method, or initialize a Q3 object in your main method, and call maxArray like that.
Your method has to be static, so you have to say
static double maxArray(double dar[], int size)
Here are some hints how you could improve your method:
since you don't use the value "size" once, you can either throw it out or replace the i < dar.length with i < size.
Also, when initializing maxV in the maxArray method, you might want to use the first value of the array (double maxV = dar[0]), because if all doubles in the array are negative, maxV with the number 0 will be the highest. (You could also use the lowest double value possible by saying double maxV = Double.MIN_NORMAL).
1) make your method static
2) Remember in java use BigDecimal class to do any decimal arithmetic.
Related
I got this code:
public static ArrayList<Integer> MakeSequence(int N){
ArrayList<Integer> x = new ArrayList<Integer>();
if (N<1) {
return x; // need a null display value?
}
else {
for (int j=N;j>=1;j--) {
for (int i=1;i<=j;i++) {
x.add(Integer.valueOf(j));
}
}
return x;
}
}
I am trying to call it from the main method just like this:
System.out.println(MakeSequence (int N));
but I get an error...
Any recommendations? Much appreciated, thanks!
System.out.println(MakeSequence (int N));
should be
int N = 5; // or whatever value you wish
System.out.println(MakeSequence (N));
Just pass a variable of the correct type. You don't say that it is an int again;
You define the method as follow MakeSequence (int N), this means that method expects one parameter, of type int, and it'll be called N when use inside the method.
So when you call the method, you need to pass an int like :
MakeSequence(5);
// or
int value = 5;
MakeSequence(value);
Then put all of this in a print or use the result in a variable
System.out.println(MakeSequence(5));
//or
List<Integer> res = MakeSequence(5);
System.out.println(res);
All of this code, to call the method, should be in antoher method, like the main one
Change x.add(Integer.valueOf(j)); to x.add(j); as j is already an int
to follow Java naming conventions : packages, attributes, variables, parameters, method have to start in lowerCase, while class, interface should start in UpperCase
The first issue is I think that N should be some int value not defining the variable in the method call. Like
int N = 20;
ClassName.MakeSequence(N);
The other issue you will face. As System.out.println() only prints string values and you are passing the ArrayList object to it, so use it like this System.out.println(ClassName.MakeSequence(N).toString())
The following code:
public static void main(String[] args) {
int first = 1;
int second = 2;
sum(first,second);
System.out.println(sum);
}
public static int sum(int a, int b){
int sum = a+b;
return sum;
}}
will return error and I need to write
int x = sum(first,second);
System.out.println(sum);
and define that method as integer x and print x.
But for array,
public static ArrayList<String> removeLast(ArrayList<String> list) {
//code
return list;
}
public static void main(String[] args) {
//code
removeLast(persons);
System.out.println(persons);
}
will print the returned value of array without defining as another array as the was with the previous one.
I am sorry if the question has already been asked as I couldn't find it. And I am just learning Java.
Arrays are passed by (value of) reference, therefore, any change that happens to the array inside the method, will actually change the array passed in to it. On the other hand ints are passed by value. Change an int inside a method, and it won't change the int passed into the method.
For this reason, the return statement in your array method is completely unnecessary. Your code will still change the array, even if you omit the return statement.
But there's another misconception that needs to be pointed out: when you sum two ints, you are creating a new value in memory, which exists as long as the method is executed. When the sum method is done, the sum int doesn't exist anymore. To retain its value, you need to return it from within the method, and assign it to a variable where you call the code.
Because Java is pass by value, but the value of reference types (including arrays) is a reference to the Object (in this case, a List). You might use a variadic function and (in Java 8+) an IntStream to implement it like
public static int sum(int... arr) {
return IntStream.of(arr).sum();
}
Then you can call sum with as many (or few) int arguments as you like.
Will print the returned value of array without defining as another
array as the was with the previous one ?
Whatever #yeedle mentioned above is correct, but one point to add as below:
ArrayList class (actual type of persons object) has overridden the toString() method such that it
could print the array details when you invoke
System.out.println(persons);.
You need to know that for your objects (created for your custom
classes like Product, Employee, etc..), you need to override
toString() method (inherited from java.lang.Object) to print the
values like how you wanted, otherwise simply using
System.out.println(object); will print the hashcode of the
object (like #HA5431 etc..).
You can look here and here
I am learning java and trying to figure out how to implement these methods into my main class from a second class. The program takes user input to add numbers into an array and then I need to print the following using the pre-specified methods below. The parameters in the below method is what confuses me.
public static double findMin(double[] numbers, int count) //count is the count of numbers stored in the array
public static double computePositiveSum(double[] numbers, int count)
public static int countNegative(double[] numbers, int count)
Basically, I am confused as to how I link all the variables and array between the two classes so they can recognize the parameters and return the correct value to output min, sum and number of negatives. Do I want the array in the main method?
Basically, what I did now to fix it was that I created the variables in the main method and then pass the variables in the main method through the parameters of the object I created that links to the secondary class. Does that seem ok?
If you already have the array , so what you need is call your methods and pass this value to it
lets say you have this array :
double[] num = {1.2,2.3};
and your count is the length of num array , so the count is:
int count = num.length;
then call your method and pass the parameters to it like this:
findMin(num , count );
computePositiveSum(num , count );
countNegative(num , count );
Note : you need to read in Object-Oriented Programming Concepts
Sorry guys for such a question. I just needed a refresher since it has been awhile. I resolved the issue by creating the array and count variable in the main method and then passed those through the parameters so the methods in the secondary class could read them. Thanks for the quick responses and help .
You don't need a count variable, you can use myarray.length
So your code should be something like this:
public static void main(string [] args)
{
double[] myarray = {5.3, 69.365, 125, 2.36};
double result = MyClass.findMin(myarray);
}
public class MyClass
{
public static double findMin(double[] numbers)
{
// your impl
}
public static double computePositiveSum(double[] numbers)
{
// your impl
}
public static int countNegative(double[] numbers)
{
// your impl
}
}
You can create an object reference of the main class in your derived class. Then call these methods using the object of your main class.
class Main
{
------
}
class derived
{
Main m = new Main();double[] A=new double[1];
Scanner s = new Scanner(System.in);
int i=0,wc=1;
int arrayGrowth=1;
while(s.hasNext())
{
if (A.length == wc) {
// expand list
A = Arrays.copyOf(A, A.length + arrayGrowth);
wc+=arrayGrowth;
}
A[i]=s.nextDouble();
i++;
}
int len=A.length-1;
m.findMin(A,len);
m.computePositiveSum(A,len);
m.countNegative(A,len);
}
Bit stuck on a bit of my Java code. I have adjusted the code below to give a trivial example, the answers will still be applicable. Basically,
I have three class files: GUI, main, pipe1.
My GUI accepts some values for variables: length and height.
It then calls main.makePipe which is a static method containing an if statement which then creates a new pipe1 called createdPipe. Sample:
public static void makePipe(double length, double width){
if(length > 0 && length < 4){
pipe createdPipe = new pipe1(length, height);
Now my new createpipe object has a method called basicCost which makes returns the cost of the pipe:
protected void calculateCost(){
double basicCost = height * length + 300;
return basicCost;
}
I'm stuck on how to get this returned value all the way back to the GUI class?
If I run (in my GUI class):
createdpipe.calculateCost();
it says cannot find symbol. Rightly so.
If I create a method in main and put:
public double finalCost(){
pipeCost = createdPipe.calculateCost();
return pipeCost;
}
and try to call it from my GUI (main.finalCost) I get an: non static method cannot be reference from a static context.
I understand why, but can anyone tell me how I can make this object known to the GUI class or a way I can calculate data on the pipe1 class and return the data to the GUI class to be used?
the createdPipe is a local variable, so you need to change the scope of this variable.
you should declare a static variable reference to the createdPipe Object in main, like this:
private static pipe1 createdPipe;
change the makePipe method, so it will create createdPipe:
public static void makePipe(double length, double width){
if(length > 0 && length < 4){
createdPipe = new pipe1(length, height);
then you should declare the finalCost as static method:
public static double finalCost()
because createdPipe can be null, you should check if createdPipe is null in finalCost method.
In the following code the method array1 won't return the avarage because its return type is void.
I know what void means but can someone explain to me what is a void result type and how to make this method return the avarage:
public class JavaApplication4 {
public static void main(String[] args) {
int[] a = {1,2,3,4};
double result = array1 (a);
}
public static array1 (int[] b) {
double avarage;
int total = 0;
for (int x:b) {
total += x;
}
avarage = total / b.length;
return avarage;
}
The "result type" or "return type" is set in the function declaration. It just means what type of data is going to be returned after the function is called. Your function should look like:
public static double array1(int[] b) {
double average;
int total=0;
for(int x:b){
total +=x;
}
average = (double) total/b.length;
return average;
}
This will return the value of average after the function is done. So result will hold the same thing as the final value of average after the function completes.
You need to declare array1 as returning double. Change its declaration to:
public static double array1(int [] b ) {
A void function -- void array1(...) -- does not return a value.
Note that there's another error in your code:
avarage = total / b.length;
The above uses integer division, meaning that the result is truncated to integer, and only then converted to double. To fix, change the line to:
avarage = total / (double)b.length;
A return type of void means that a method doesn't return anything. This is useful when you want to preform an operation on an array, but there isn't any value associated with the operation. For example, say that you wanted to swap the first and last element in an array, you could write some method like this (ignore the necessary error checking)
public void swapArrayLocs(int[] swapping){
int temp = swapping[0];
swapping[0] = swapping[swapping.length - 1];
swapping[swapping.length - 1] = temp;
}
When you call this method, you're not expecting any sort of result from it, you're expecting your program to just take care of business and continue executing.
In this case, you actually want your array1(int[]) method to make its available to the rest of the program. You do this by specifying the return type of the function, which tells the rest of the program what type of information you expect that function to return. In your case, you'd do this by changing your method declaration to.
public static double array1(int[] b){
//the same method body
}
Note how in this case the word double is inserted after static. This tells the calling function that when it executes array1, the method will give back a value of type double. Contrast this with what you had before which said that the method would not give back any type of information.