gpt4 book ai didi

java - 输出不遵循顺序

转载 作者:行者123 更新时间:2023-12-02 02:54:03 25 4
gpt4 key购买 nike

问题是打印语句时输出不遵循一定的顺序。当用户输入问题的答案时,它应该一一打印语句。例如,它单独输出第一个语句,但一旦用户点击“输入”,它就会立即输出接下来的 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());
}
}

最佳答案

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

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

关于java - 输出不遵循顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57088537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com