'illegal start of expression' but outside of main - java

Please bear with me I'm very new to this. I am going through some tutorials and I am getting this error
GradeAnalyzer.java:51: error: illegal start of expression
myAnalyzer.getAverage(ArrayList<Integer>);
I have found so many threads saying take the method outside the main, however unless I am really stupid I'm pretty sure mine is outside of the main already. All advice regarding the matter is welcome (also feel free to heavily criticise the rest of my code).
import java.util.ArrayList;
public class GradeAnalyzer {
public GradeAnalyzer() {
}
public int getAverage(ArrayList<Integer> grades) {
;
if (grades.size() < 1) {
System.out.println("Unfortunately the Array you are using is empty");
return 0;
} else {
int sum = 0;
for (Integer grade: grades) {
System.out.println(grade);
sum = sum + grade;
}
int average = sum / grades.size();
System.out.println("Average =" + average);
return average;
}
}
public static void main(String[] args) {
ArrayList<Integer> myClassroom = new ArrayList<Integer>();
myClassroom.add(98);
myClassroom.add(92);
myClassroom.add(88);
myClassroom.add(75);
myClassroom.add(61);
myClassroom.add(89);
myClassroom.add(95);
}
public int myAnalyzer(ArrayList<Integer> myClassroom) {
GradeAnalyzer myAnalyzer = new GradeAnalyzer();
myAnalyzer.getAverage(ArrayList<Integer>);
}
}

This is the culprit:
myAnalyzer.getAverage(ArrayList<Integer>);
You've provided a type where an expression is expected. You probably wanted to pass in the myClassroom argument:
myAnalyzer.getAverage(myClassroom);
Other notes:
You probably want to get rid of the stray ; at the top of getAverage as well. I don't think it's a syntax error, but it's pointless.
I don't see a call to myAnalyzer (the method) anywhere.
myAnalyzer is a very strange name for a method.
It's best not to declare a local variable (myAnalyzer) inside a method with the same name (myAnalyzer) (although it's valid).
In general, try to keep variable types to interfaces rather than concrete types, so:
List<Integer> myClassroom = new ArrayList<Integer>();
...rather than using ArrayList<Integer> on the variable declaration.
If using ArrayList (which does, after all, allocate and maintain an array), where possible tell it the initial capacity to use so you ensure that you're not doing unnecessary array re-allocations as you add things.
sum += grade; is the idiomatic way to write sum = sum + grade; (although the latter works).

myAnalyzer.getAverage(ArrayList<Integer>);
is not a valid method call. You should pass an instance whose type is ArrayList<Integer>.
For example, if you call it from your main, you can write :
myAnalyzer.getAverage(myClassroom);
Or, if you don't want to put this method in your main, move the myClassroom ArrayList declaration and initialization to myAnalyzer method.

Related

How to call a static method from main class?

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())

I need help passing an array and calling basic methods on it

I'm new to programming and java, and I'm trying to write a simple bubble sorting algorithm. I might be in a bit over my head; I'm not too far along in Oracle's java tutorials. The trouble I'm having now isn't with the bubble sorting itself, but in creating the array and printing it before it is sorted.
Here is what I have so far:
public class BubbleSort {
public BubbleSort(int size) {
// creates array
int[] items = new int[size];
}
public void fillArray(int[] a) {
// fill array with random ints
for (int i=0; i<(a.length-1); i++) {
a[i] = java.util.Random.nextInt(50);
}
}
public void printArray(int[] a) {
for (int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
}
public void BubbleSortAlgorithm() {
// bubble sorting algorithm goes here
}
public static void main(String[] args) {
BubbleSort bubbleSort = new BubbleSort(20);
bubbleSort.fillArray(items);
bubbleSort.printArray(items);
// bubbleSort.BubbleSortAlgorithm(items);
// bubbleSort.printArray(items);
}
}
I'm getting 3 compiler errors:
non-static method nextInt(int) cannot be referenced from a static context
Is this because it is called in the main method? How do I get around that?
2.,3. the compiler can't find the symbol, items. Items is an array of ints that is created in the constructor for the class. Do I need to declare it in the main method?
I have a feeling that my class structure is completely off. Again, I'm very new. I'm also new to stackoverflow, so I'm also sorry if this question isn't presented well.
You call:
java.util.Random.nextInt(50);
It's preferred to import classes you're going to use. That would put this block at the top of the file:
import java.util.Random;
And change the existing code to:
Random.nextInt(50);
That fixes the style problem, but you're still going to get the same compiler error.
Static methods are things that belong to a class; they don't need you to create (instantiate) an object of that class before using them. Instead of every instantiation of a class having that method, all instantiated instances of the class share the same static methods and variables.
Specifically, .nextInt() in the Random class is not a static; it's a normal method. So it needs an instantiated Random to work on. Which means you should try:
Random random = new Random();
random.nextInt(50);
After you've instantiated a Random, you can then keep calling nextInt() on it, as many times as you'd like.
One example of static methods that are commonly used are in the Math class.
Math.min(10, 5);
Math.max(100, 100000);
And so on.
The reason Random needs to be instantiated is that it has state. It's not fully random, but pseudo-random, in that it needs a number to start with. If you don't give it a number, it takes the current time. Two Java Random objects initialized at exactly the same moment... will produce the same series of "random" numbers.
This is actually useful; you can give them Random object the number to start with, and you can use this behavior for testing purposes.
Random random = new Random(1);
That's seeding it with the number 1. Which means it'll produce the same random numbers for nextInt() every time you run your code. If you don't give it any number as a seed, it's doing this, instead:
Random random = new Random(System.currentTimeMillis());
But yeah; the problem is that Random.nextInt isn't a static method.
First thing is
NextInt method of non static
So you have to use instance of random class to use it
Second one
Item is local variable so you have to must declare it before use it

Adding numbers to arrays with methods in another class?

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);
}

programming error in java due to static variable

Following code is going in else statement. I am not able to find out where i made mistake.
*A want to execute in below comments.
*B is executing in below comments.
package com.java;
import java.util.Scanner;
public class Solution
{
static int n;
static String w[];
public static void main(String[] args)
{
System.out.println("enter no of string between 1 to 50");
Scanner scanner = new Scanner(System.in);
//* A
if ((1<n) && (n<=50))
{
n = scanner.nextInt();
System.out.println("enter " +n+ "strings between 1 to 2000 length");
for (int i=0; i<n; i++)
{
w[i]= scanner.next();
if ((1<w[i].length()) && (w[i].length()<2000))
{
System.out.println("ok");
}
}
System.out.println(w);
}
// *B
else
{
System.out.println("coming due to static");
}
}
}
static means that it is a class variable, that is, it does not belong to an instance of the class. And opposite, a non static variable belongs to an instance of the class. You're referencing the variable n from a static method, and hence, it will not work unless the variable also is declared static.
(and obviously, the if itself won't work because of what the reply from #MarounMaroun mention)
You didn't initialize n, so you're not satisfying the if condition, since uninitialized static int variables are 0 by default.
So:
if ((1<n) && (n<=50)) is not evaluated to true, so else will be executed.
Note that you can't access static variable from non-static method (See #NilsH answer). And that's make a lot of sense..
First, when working with static methods, you must reference static variables. If you try to reference a non-static variable that belongs to a class, the compiler will complain because that is wrong. Static variables do not belong to a class per se.
Second, I think you have a typo or forgot some code. n is never set - ever. Therefore, since in the static context it will be zero initialized and hit the else. I think you meant for n to actually be set before the if statement either via user-input or some other means. If you leave everything static and actually provide a value for n, then your code should work.
For instance, you probably need to make this assignment:
n = scanner.nextInt();
before the if-statement.
there is another problem with your code in reading the next number you want to read, but I will leave that for you to solve.
Have you tried making static int n and static String w[] public?
IE:
public static int n ;
public static String w[] ;
what you probably want is moving all that code to a non-static method. and then in your main method just do something like this
Solution s = new Solution();
s.myNonStaticMethod();

Array and methods?

I'm doing a task for a course in Java programming and I'm not sure how the following thing is working? The method below takes the value from an array and a integer. The integer should be added to the array and then be used outside the method in other methods and so on, but how could this work when the method has no return for the new content of the array? There is a void in the method? Have I missed something? Preciate some help? Is there something about pointers?
public static void makeTransaction(int[] trans, int amount);
Arrays in Java are objects. If you modify the trans array inside the method, the changes will be reflected outside of it1. Eg:
public static void modify(int[] arr)
{
arr[0] = 10;
}
public static void main(...)
{
int x = {1, 2, 3};
System.out.println(x[0]); // prints 1
modify(x);
System.out.println(x[0]); // now it prints 10
}
Note that native arrays can't be dynamically resized in Java. You will have to use something like ArrayList if you need to do that. Alternatively you can change the return type to int[] and return a new array with the new element "appended" to the old array:
public static int[] makeTransaction(int[] trans, int amount)
{
int[] new_trans = Arrays.copyOf(trans, trans.length + 1);
new_trans[trans.length] = amount;
return new_trans;
}
1 It is also worth noting that as objects, array references are passed by value, so the following code has no effect whatsoever outside of the method:
public void no_change(int[] arr)
{
arr = new int[arr.length];
}
You can't add anything to an array. Java arrays have a fixed length. So indeed, what you want to do is impossible. You might make the method return an int[] array, but it would be a whole new array, containing all the elements of the initial one + the amount passed as argument.
If you want to add something to an array-like structure, use an ArrayList<Integer>.
Do you have to keep the method signature as is?
Also, can you be a bit more specific. When you say "the integer should be added to the array", are you referring to the amount argument? If so, then how is that amount added? Do we place it somewhere in the array or is it placed at the end, thus extending the array's length?
As far as pointers go, Java's pointers are implicit, so if you don't have a strong enough knowledge of the language, then it might not be so clear to you. Anyways, I believe that Java methods usually will pass objects by reference, and primitives by value. But, even that isn't entirely true. If you were to assign your object argument to new object, when the method terminates, the variable that you passed to the method is the same after the method executed as it was before. But, if you were to change the argument's member attributes, then when the method terminated those attributes values will be the same as they were inside of the method.
Anyways, back to your question, I believe that will work because an array is an object. So, if you were to do the following:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
}
// static int i;
/**
* #param args
*/
public static void main(String[] args)
{
int[] trans = {0,1,3};
makeTransaction(trans, 10);
for(int i = 0; i<trans.length; i++)
{
System.out.println(trans[i]);
}
}
The output of the array will be:
10
1
3
But, watch this. What if I decided to implement makeTransaction like so:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
trans = new int[3];
}
What do you think that the output will be? Will it be set to all zero's or will be the same as it was before? The answer is that the output will be the same as it was before. This ties in to what I was saying earlier.
I might've assigned that pointer to a new object in memory, but your copy of the pointer inside of the main method remains the same. It still points to the same place in memory as it did before. When the makeTransaction method terminates, the new int[3] object that I created inside of it is available for garbage collection. The original array remains intact. So, when people say that Java passes objects by reference, it's really more like passing objects' references by value.

Categories