why would i need .class to call a method? [duplicate] - java

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 3 years ago.
I'd like to know why I got these errors and how to fix it:
Main.java:12: error: '.class' expected
populateArray(int[] aRand);
^
Main.java:12: error: ';' expected
populateArray(int[] aRand);
The instructions I was given are in the comments and I just followed what I believe what the instructions meant. I thought maybe I should do populateArray(); in the main method, but it wouldn't match the signature of public void populateArray(int[] array){}.
import java.util.Random;
public class Main {
public static void main(String args[])
{
/*
(a) Create an array of integers called aRand of capacity 20 and initialize its entries to 0.
*/
int aRand[] = new int[20];
populateArray(int[] aRand);
}
/*
(b) Populate the array in a method called populateArray(int[] array) where array is the one you want to populate.
This method returns void.
*/
public void populateArray(int[] array){
Random rand = new Random();
for (int i=0; i<array.length; i++){
array[i] = rand.nextInt();
System.out.println(array[i]);
}
}
}

Just a couple small things!
First, you already declared populateArray as a method that takes an int[], so you do not need to do so when you actually call the method.
Second, you cannot call a non-static method from a static context. Since your main method is static, you cannot call the non-static method populateArray within it. For your purposes, it should be fine to just declare populateArray as a static method.
import java.util.Random;
public class Main {
public static void main(String args[])
{
/*
(a) Create an array of integers called aRand of capacity 20 and initialize its entries to 0.
*/
int aRand[] = new int[20];
populateArray(aRand); // We already know aRand is an int[]
}
/*
(b) Populate the array in a method called populateArray(int[] array) where array is the one you want to populate.
This method returns void.
*/
public static void populateArray(int[] array){
Random rand = new Random();
for (int i=0; i<array.length; i++){
array[i] = rand.nextInt();
System.out.println(array[i]);
}
}
}
For reference, here as a helpful StackOverflow answer that discusses when you should use static vs. instance methods: Java: when to use static methods.

Related

Java, fill an array with a supplied number

import java.util.*;
public class IncreasingSum
{
public static void ArrayList(int[] args)
{
Scanner kb=new Scanner(System.in);
System.out.print("Enter a number:");
int num=kb.nextInt();
{ for (int loop=0; loop<num; loop++)
ArrayList <X> myList = new ArrayList<X>();
myList.add(loop);
}
}
}
I have imported the java.util.*; but it keeps giving error on ArrayList.
There are a number of issues
should be static void main(String [] args), instead of static void ArrayList(int [] args)
X should be Integer
Loop should be around the add(), not the new ArrayList()
extra braces not required outside the loop
Possible flaw
Code should should probably use add(n) rather than add(loop) to "fill" the array with the same number
If above true then just use Collections.fill(myList, num); and get rid of your loop
Fixed
import java.util.ArrayList;
import java.util.Scanner;
public class IncreasingSum {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter a number:");
int num = kb.nextInt();
ArrayList<Integer> myList = new ArrayList<Integer>();
for (int loop = 0; loop < num; loop++) {
myList.add(loop);
}
}
}
Syntax Errors
The reason you get an error on the ArrayList line is because of the way you've instantiated it.
Here's an example of how to use ArrayLists with generics:
http://docs.oracle.com/javase/tutorial/java/generics/why.html
Basically in your declaration, you'll need to substitute X with the class of elements you want to store in the ArrayList. In your case that would be Integer.
ArrayList <X> myList = new ArrayList<X>(); //Throws error
ArrayList<Integer> myList=new ArrayList<Integer>(); //Will suit your need
Once you've fixed the list declaration, you'll also need to fix the line with the for loop. The starting braces of your for loop should come after the loop declaration to fix your other syntax error.
{ for (int loop=0; loop<num; loop++) //Throws error for your program
for (int loop=0; loop<num; loop++){ //The declaration you need
Other potential errors:
You'll also need to include the main method in the class to execute your program.
FYI:
Java convention for method names is starting with a lowercase letter. So even if you did have a method called ArrayList, arrayList would be more in line with the method naming convention.
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Use specific class called Integer for generics as you are adding Integer within array list before for loop and add element within loop:
ArrayList <Integer> myList = new ArrayList<Integer>();
You need brackets after for loop. Right now the only intruction in for loop is to create new ArrayList several times. Array list should be declared above for loop.

What will public static int[] main (int[] ) return and where? [duplicate]

This question already has answers here:
Can a main method in Java return something?
(6 answers)
Closed 8 years ago.
class Half {
public int evaluate(int arg) {
return arg/2;
}
}
public class Box {
public static int [] main (int[] arrIn) {
int[] arrOut = new int[arrIn.length];
Half func = new Half();
for (int i=0; i< arrIn.length; i++)
arrOut[i] = func.evaluate(arrIn[i]);
return arrOut;
}
}
So contents of arrOut are the elements in arrIn divided by two.
I want to take integer array from command line arguments and print array with new contents to screen.(I don't want to take it as string values then convert to int and blah blah)
Is there any way to take direct integers as arguments?
Secondly the above code gives an error.(Obviously)
Error: Main method not found in class Box, please define the main method as:
public static void main(String[] args)
Which brings me to my next question.
Should it always be public static void main(String[] args)? Can't it be public static int main with some arguments other than string type?(Don't explain the static part.. As per my understanding main method needs to be invoked without an object which is why it is static. but if it is forced(somehow) to return an integer, where will it return it?(I mean to which method? or will it directly print to the screen?)I know it doesn't print to the screen (duh!) but then where is the control returned basically after main method finishes execution?
Should it always be public static void main(String[] args)?
Yes, if you want it to act as an entry point.
Can't it be public static int main with some arguments other than string type?
No. Section 12 of the JLS explains JVM start-up, and includes this in 12.1.4:
Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.
The method main must be declared public, static, and void. It must specify a formal parameter (ยง8.4.1) whose declared type is array of String.
Basically, the only bits which are optional are:
The name of the parameter
Whether you make it a varargs parameter or not
You can overload the method if you want, providing extra main methods with different parameter types and possibly a return value - but only the void one with a String[] parameter will be treated as an entry point.
I want to take integer array from command line arguments and print array with new contents to screen.(I don't want to take it as string values then convert to int and blah blah) Is there any way to take direct integers as arguments?
No. You have to do it yourself. It's pretty trivial though:
int[] integers = new int[args.length];
for (int i = 0; i < args.length; i++)
{
integers[i] = Integer.parseInt(args[i]);
}
First thing first:
This must always be public static void main(String[] args)
Second to read integer directly, use:
Scanner in = new Scanner(System.in);
int num = in.nextInt();

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

'This method must return a result of type int' Java?

public static void main(String args[])
{
double arr[] = {1,-6.3,9000,67.009,1.1,0.0,-456,6,23,-451.88};
ArrayList<Integer> List = new ArrayList<Integer>();
List.add(1);
List.add((int) -6.3);
List.add(9000);
List.add((int) 67.009);
List.add((int)1.1);
List.add((int)0.0);
List.add(-456);
List.add(6);
List.add(23);
List.add((int)451.88);
}
public static int ArrayListMax(ArrayList List)
{
for (int i=0; i<List.size(); ++i)
{
System.out.println(List.get(i));
}
The error is in:
public static int ArrayListMax(ArrayList List)
This is probably a very nooby mistake, but I'm new to Java so forgive me.
Any help please?
Thank you.
EDIT:
I want the ArrayListMax method to print the size of the List!
Assuming you are trying to get the maximum value in your List in the method arrayListMax, you need to return an integer in accordance with your method signature, which the error is telling you
This method must return a result of type int
Instead of printing all the values in the list, you could do:
public static int arrayListMax(List<Integer> List) {
return Collections.max(list);
}
Use Java Naming Conventions. Method & variable names begin with a lowercase letter. Using this approach helps avoid confusion between instances & types (e.g. in the case of List in the main method).
Either add a return statement to your ArrayListMax() method that returns an int or change the method signature from public static int to public static void. And add a closing } to the method too.
Also, you shouldn't use List as a name for the argument to that method because it's the name of an interface that you're actually importing in this code. The convention in java is for variable names and method names to begin with a lowercase letter (camel case) and class names to begin with an uppercase letter (pascal case).
Problem is in this method:
public static int ArrayListMax(ArrayList List)
{
for (int i=0; i<List.size(); ++i)
{
System.out.println(List.get(i));
}
}
You are not returning from this method, you must return of type int to solve that error. Since you have specified int as return type.
You created the function as returning a result
public static int ArrayListMax(ArrayList List)
In order to remove your problem, if you need not return anything, write
public static void ArrayListMax(ArrayList List)
void means you do not want the method to return a result.
if you are just printing out values the signature should be public static void ArrayListMax(ArrayList List).
First, you are not returning anything with ArrayListMax method even if you have set its retun type to int. Either return void as you are directly printing from the list.
Second, even if you set the correct return type to ArrayListMax method, you will still need to call that method in the main method as below:
public static void main(String args[])
{
double arr[] = {1,-6.3,9000,67.009,1.1,0.0,-456,6,23,-451.88};
ArrayList<Integer> List = new ArrayList<Integer>();
List.add(1);
List.add((int) -6.3);
List.add(9000);
List.add((int) 67.009);
List.add((int)1.1);
List.add((int)0.0);
List.add(-456);
List.add(6);
List.add(23);
List.add((int)451.88);
YourClassNameInWhichMethodIs.ArrayListMax(List);
}
You should use a return statement as Methode is returning an int type value.

java array declaration

I get the error shown in the comment when I call my class's constructor
(when I remove the array parts everything goes fine). Is this because of a wrong declaration of the array seq?
public class FibIt implements SeqIt{
public int counter;
public int ptr;
public int [] seq;
public FibIt(Fib x)
{ counter=0;
ptr=0;
seq[0]=x.first1; //gives me an error here saying Exception in
//thread "main" java.lang.NullPointerException
//at FibIt.<init>(FibIt.java:9)
//at Main.main(Main.java:6)
seq[1]=x.first2;
for (int i=2; seq[i-1]<=x.last; i++)
{seq[i]=seq[i-1]+seq[i-2];}
}
#Override
public int func2() {
// TODO Auto-generated method stub
ptr++;
return seq[ptr-1];
}
}
You have to initialize your array, so something like public int[] seq = new int[10];
Then replace 10 with whatever size you need.
And I was just about to answer your question when #Jack posted a good solution. ArrayList<Integer> is pretty useful if you don't know the size of the array.
You need to initialize the array. One thing is declaration, other thing is inizialization.
int[] seq declares a variable of name seq which is an array of int. Then you need to effectively inizialize it by assigning to it a constructor for an array: new int[dimension]
Yes, you have only declared the array but not initilized.
public int [] seq = new int[anySize];

Categories