Dom
Dom

Reputation: 159

The operator < is undefined for the argument type

No hate on my Java programming teacher, but I've had some experience with programming, and for the first project I'd like to wow the teacher. Anyways, I'm new to Java, but have some strong knowledge of C. Just to test out the array system in Java I have designed this program. What I want it to do is ask me for the size of the array. I need the size of the array, because later I'm going to fill it with the names of the employees. But I keep getting this error...

package withholding_calculator;
import java.util.Scanner;

class withholding_calculator {
public static void main(String args[]) {
    //declaring variables
    Scanner size = new Scanner(System.in);
    String[] employeeNames = new String[size.nextInt()];

    for( int i = 0; i < size; i++ ) {
        System.out.println( employeeNames[i] );
        }
    }
}

Upvotes: 0

Views: 449

Answers (1)

sprinter
sprinter

Reputation: 27976

Two points to make in response to this.

Firstly, your for loop can use the array size directly (employeeName.length) rather than referring to the scanner object (the error is caused by you comparing a scanner to an int).

Secondly, 'c' style arrays are used much less in Java than in C. Typically a Java programmer would code this as:

List<String> employeeNames = new ArrayList<>();
// fill the list using employeeNames.add
for (String name: employeeNames)
    System.out.println(name);

In Java 8 the final 2 lines can be substantially simplified to:

employeeNames.forEach(System.out::println);

Having said that it is still perfectly reasonable to use standard arrays and your code should function if you compare to the array's length rather than your scanner.

Upvotes: 1

Related Questions