输出不遵循顺序

时间:2019-07-18 06:46:48

标签: java output java.util.scanner

问题是在打印语句时输出未遵循特定顺序。当用户输入问题答案时,应该一一打印语句。例如,它单独输出第一条语句,但是一旦用户单击“ enter”,它会立即输出接下来的2条语句。

import java.util.Scanner;

class Student {
    String name;
    int age;
    int rollNumber;
    int scoreOne;
    int scoreTwo;

    public Student(String n, int a, int rN, int s1, int s2) {
        name =n;
        age =a;
        rollNumber =rN;
        scoreOne = s1;
        scoreTwo = s2;
    }

    public String toString() {
        String information;
        information = name + " is " + "years old." + name + "roll number is" + rollNumber + "." + name + "average is" + (scoreOne+scoreTwo)/2;
        return information;
    }
}

public class StudentMain {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

        System.out.print("Enter name: ");
        s.nextLine();

        System.out.print("\nEnter age: ");
        s.nextLine();

        System.out.print("\nEnter Roll Number: ");
        s.nextLine();

        System.out.print("\nEnter Score One: ");
        s.nextLine();

        System.out.println("Enter Score Two: ");
        s.nextLine();


        Student information = new Student(s.nextLine(), s.nextInt(), s.nextInt(), s.nextInt(), s.nextInt());

        System.out.print(information.toString());
    }
}

1 个答案:

答案 0 :(得分:0)

在接受字符串输入之前,您需要清除扫描仪中的缓冲区,因此只需写

s.nextLine();
before

String s=s.nextLine();

它将起作用。在我看来,您正在创建一个信息对象,该对象具有用户输入的值。那么您必须同时存储用户的值,然后接受它,然后将这些存储的值传递给创建信息对象。

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

        System.out.println("Enter name: ");
        String nm=s.nextLine();

        System.out.println("Enter age: ");
        String age=s.nextLine();

        System.out.println("Enter Roll Number: ");
        String rn=s.nextLine();

        System.out.println("Enter Score One: ");
        String one=s.nextLine();

        System.out.println("Enter Score Two: ");
        String two=s.nextLine();


        Student information = new Student(nm, Integer.parseInt(age),Integer.parseInt(rn) , Integer.parseInt(one), Integer.parseInt(two));

        System.out.print(information.toString());
    }