method returning average of double array - java

Im new with programming and have been trying to solve this problem for a while, been looking at similar questions but im not understanding whats wrong with my code.
So the assignment is to write a method that takes an array that has three doubles in it. Then return the average of the three doubles. Then write a main that should call and then type the method.
Thanks!
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double []arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(double arr[]);
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[]arr){
while(i<arr[].length()){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr[].length();
return genomsnitt;
}
}
PS. they are two different classes with 1 main and 1 class they are not in the same file!
The error:
Syntax error on token "double", new expected
Variable must provide either dimension expressions or an array initializer
arr cannot be resolved to a type
at Tenta131031upg1main.main(Tenta131031upg1main.java:7)

Please correct the two lines in the first file like this:
double[] arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(arr);
You were creating a new, empty array in the second line.

Try this:
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double[] arr ={3.15, 4.41, 7.64};
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[] arr){
while(i<arr.length){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr.length;
return genomsnitt;
}
}
Changes are:
change in method call
arr.length instead of arr[].length()

Related

Find the minimum of a set of data input from the keyboard

I have an algorithm in my textbook written in pseudocode which is then supposed to be "implemented to a Java method". It goes like this:
read min;
while not eoln do
read x
if x < min then
min <- x
end if
end while
print min;
Then I'm given this code:
import java.util.Scanner;
int min() {
Scanner input = new Scanner(System.in);
System.out.println("x=? (999 to end)");
int x = input.nextInt();
int min = x;
while (x!=999) {
System.out.println("x=? (999 to end)");
x = input.nextInt();
if (x < min) {
min = x;
}
}
return min;
}
I put everything below import.Scanner inside of the main method and inside of a class like this:
public class MyAlgorithm {
public static void main(String[] args) {
// code here
}
}
But then I get this error message in Terminal:
MyAlgorithm.java:7: error: ';' expected
int min() {
^
1 error
Am I missing something? If I put the semicolon there, the whole thing just won't work.
It seems like you put your min method inside of main, this is defining methods from within other methods which will not work properly and cannot compile. The main method is the commands you want to run as soon as you start your program, any other functions in the class should be declared outside of it, and if you want them to run in main you do a method call.
it should look something like this:
import java.util.Scanner;
public class MyAlgorithm {
int min() {
//(min code)
}
public static void main(String[] args) {
// code here
//corrected according to Uli's comment
MyAlgorithm m = new MyAlgorithm();
int result = m.min();
}
}
I suggest reading up on how java programs are structured. Here's an article on methods.
Don't put your method min() inside the main() method. In Java, you can not define a method inside a method. In Java, you need an object to call its methods (Except you make the methods static). So your final Code looks something like this.
import java.util.Scanner;
public class MyAlgorithm {
public static void main(String[] args) {
MyAlgorithm m = new MyAlgorithm ();
m.min();
}
int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
}
If you are allowed to use static methods, (which I don't think) you can use the following alternative:
static int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
public static void main(String[] args) {
int result = MyAlgorithm.min();
}

Java program without main method

For my class I need to write code that adds up the numbers 1-100 which will produce the number 5050. He told us not to use a main method and use a for loop. Is a main method 'public static void main (String[] args)' or something else. I am just still very confused on what exactly the main method is. Here is the code I have so far that works
public class SumAndAverageForLoop{
public static void main (String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
From what I read more and after talking to some other kids in the class they said I need to make another class with a main method that calls this class but how do you call one class from another?
How to call one class from another that has a main method?
Yes the public static void main(String[] args) signature is the main method.
It sounds like you're writing library style code. So just create a method with a meaningful name for what your code does. Like AddOnetoOneHundred or similar.
You can create a method like this:
public static int CountUp() {
// code that was in your main method before
}
Double check your assignment, your teaching might have specified a class and method name and already has a program that will test your code.
A main method is fundamental to any given program as the Java compiler searches for the method as a starting point of execution. However, you are trying to make a utility class so:
class SumAndAverageForLoop {
// no main method
public static int sum() {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
class MainClassProgram {
// main in another class
public static void main() {
SumAndAverageForLoop.sum();
}
}
Try to create a method to do the calculation. The idea is create code that is unit testable.
public class SumAndAverageForLoop{
public static void main (String[] args) {
int returned = SumUp(1, 100);
System.Out.Println("sum is " + returned);
}
public int SumUp(int startInt, int endInt) {
int sum = 0;
if (endInt > startInt) {
for (int i = startInt; i <= endInt; i++) sum += i;
}
return sum;
}
}
Short Answer:
Yes, that (public static void main (String[] args)) is the main method.
Long Answer:
The main method is the entry point for an application. Without it, you may have code, but that code must somehow link to a main method or it cannot be ran. Counter-intuitively, the main method doesn't actually have to be a method. In C, you can create an integer array called main and execute it. It will translate the integers into hexadecimal and execute a corresponding Assembly command for each one, iteratively.
If you do what the professor says, you will not be able to test the program as an executable. He probably has a program made to run your code and test it for him, which is why he doesn't want a main method.
I'm not sure by what your teacher means by, "not using a main method". But you can declare a method outside of you main method and call it from there;
public class SumAndAverageForLoop{
public static void main (String[] args) {
makeSum();
}
public static void makeSum() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
}
}
Also, since one of your comments asked "How to create a method?".
I suggest you read up on some books for beginners. I'd recommend the book Head First Java.

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

Addition with the help of varag and enhanced for loop

Hi i am trying to do the addition with the help of "varags" and" enhanced for loop".But i am getting this marker "This method must return a result of type int".
class Hello1 {
int pluss(int...v){
int plus=0;
for(int x :v){
plus=plus+x;
System.out.println(plus);
return plus;
}
}}
public class Addition{
public static void main(String args[]) {
Hello1 h1=new Hello1();
h1.pluss(3,7,9,10);
}}
You are re-declaring plus every loop, which is useless. Declare it before the loop and accumulate the total. Consider also returning it:
static int pluss(int...v){
int plus=0;
for(int x :v){
plus += x;
}
System.out.println(plus);
return plus;
}
Also note how the method can be static, because it doesn't use any instance fields.
Hello1 hl=new Hello1();
h1.pluss(3,7,9,10);
Just a typo, use better fonts...
h1 versus hl.

Problem with object oriented programming in Java

So I would like to start out by telling you that I am learning Java on my own and you guys are the nearest thing I have to teachers. So thank you so much for putting up with my simple and obvious question. I am just trying to learn. Once again I am getting an error that for the life of me I cannot figure out.
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at Advisor_score.All_user.Score1(All_user.java:13)
at Advisor_score.All_user.main(All_user.java:28)
Here is my code for the ratings class:
package Advisor_score;
public class Rating {
double [] Ratings;
double sum=0;
double raw_advisor;
double advisor_score;
public Rating (double [] x){
Ratings = x;
}
public double Score(){
for(int i=2;i<Ratings.length;i++){
sum+=Ratings[i];
}
raw_advisor=((sum-(3*(Ratings.length-2)))/4);
advisor_score= 2.5+(2.5*(1-Math.pow(Math.E, -.5*raw_advisor)));
return advisor_score;
}
Here is my code for the other class:
package Advisor_score;
public class All_user{
double [] ADVISOR_SCORE;
Rating [] All_users;
double score;
public All_user(Rating...args){
All_users=args;
}
public double [] Score1(){
for (int j = 0;j<All_users.length;j++){
score=All_users[j].Score();
ADVISOR_SCORE[j]=score;
}
return ADVISOR_SCORE;
}
public void print(){
for(int i = 0;i<ADVISOR_SCORE.length;i++){
System.out.println(ADVISOR_SCORE[i]);
}
}
public static void main(String[] args){
double p1_1[] = {101,1,5,5,5};
double p2_1[] = {101,1,1,2,3};
Rating d = new Rating(p1_1);
Rating e = new Rating(p2_1);
All_user all=new All_user(d, e);
all.Score1();
all.print();
}
}
Again, I cannot thank you guys enough at StackOverflow. Your help has been invaluable!!
You have not initialized the ADVISOR_SCORE and All_users arrays, but you do try to assign values and use them. When you declare
double[] ADVISOR_SCORE; // this is null until assigned
At some point, it needs to be assigned
ADVISOR_SCORE = new double[size];
this variable:
double [] ADVISOR_SCORE;
hasn't been initialized... and therefore it's null.
ADVISOR_SCORE has not been initialised
Jeff Storey provided the best explanation, here are two semi-related tips I had to learn when learning Java:
1) Once you initialize that array
ADVISOR_SCORE = new double[size];
You cannot modify the array's length unless you re-initialize it. Students often will try to add another value onto the end of an array or otherwise "grow" it somehow. If this is something you need, checkout Vector and ArrayList.
2) Java coding conventions are to capitalize class names...
public class Rating {
...but leave the first letter of method names in lower case.
public double [] getFirstScore() {
It'll help readability when others start working on your code.
Happy coding!

Categories