简体   繁体   中英

System.out.print() reads Scanner incorrectly

I was trying to code this program for one of my classes and I ran into a problem with my output. It is supposed to read whatever I have typed in for the Scanner input. However, the output skips the first word and I'm not really sure why. You can ignore most of the declarations of variables in the main method. Those are useful just for the rest of the program.

public static void main(String[] args) {

    String fullName;
    int anniversaryM;
    int anniversaryY;
    int periodHours;

    String jobTitle;
    double payRate;
    int monthsWorked;
    double vacationHours;
    double grossPay;
    double retirement;
    double taxWithholding;
    double netPay;

    Scanner in = new Scanner(System.in); 

    fullName = inputLine(in, "Enter your full name:");
    System.out.print(fullName);
}

public static double inputNumber(Scanner input, String prompt) {

    Scanner in = new Scanner(System.in);

    in.nextDouble();
    return in.nextDouble();
}

public static String inputLine(Scanner input, String prompt) {

    Scanner in = new Scanner(System.in); 

    System.out.println(prompt);
    in.next();
    return in.next();
}

public static double calcPercentage(double grossPay, double retirement) {

    Scanner in = new Scanner(System.in);

    in.nextDouble();
    return in.nextDouble();
}

Output:

Enter your full name:
John Doe
Doe

You have a double call to in.next() . Just remove it and you should be OK. Additionally, note that you're passing the Scanner to the method, so you shouldn't create a new inside the method:

public static String inputLine(Scanner input, String prompt) {
    System.out.println(prompt);
    return input.nextLine();
}

I think your problem is the in.next(); return in.next(); in.next(); return in.next(); . in which case it will call the reader two times, if you want to return the value of the in.next(); you should put it in a container and return that container or just go straight return in.next();

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