简体   繁体   中英

Simple Java Compile Error on Mac: Trying to use Scanner Class for data input at command prompt?

I'm trying to use Java for the first time on my Mac (OS X 10.6.8). A simple "Hello World" example works fine. However, now I'm trying to input data via command prompts and compilation fails on syntax, expecting a semicolon. Code comes from the book: "Java Programming: From Problem Analysis to Program Design", 5th Edition, by DS Malik.

The compilation error is:

javac Example2_17.java
Example2_17.java:18: ';' expected
    firstName console.next();
                     ^
1 error

The java version is:

java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-10M4509)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode)

The java code is:

import java.util.*;

public class Example2_17
{

  static Scanner console = new Scanner(System.in);

  public static void main(String[] args)
  {
    String firstName;
    String lastName;

    int age;
    double weight;

    System.out.println("Enter first name, last name, age, and weight separated by spaces.");

    firstName console.next(); // <----------- ERROR HERE!
    //lastName console.next();
    //age console.nextIng();
    //weight console.nextDouble();

    //System.out.println("Name: " + firstName + " " + lastName);

    //System.out.println("Age: " + age);
    //System.out.println("Weight: " + weight);
  }
}

Any help is greatly appreciated.

Thanks!

You're missing an assignment operator =

firstName = console.next();

Without the operator the compiler considers the statement a declaration so complains when it doesn't find ; at the expected location.

You appear to be missing an equal sign after firstName.

Is..

firstName console.next();

Should be...

firstName = console.next();

You have to use try and catch statements.There must be an exception or use throwIOException. There is another error /age console.nextIng(); you added an Ing intstead of int and that may be another cause of your error.You have also forgotten the "=" operater to store the data extracted into your local variable.`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM