我无法增加 For 中的 studentid 值
I can not increase the studentid value in For
我正在 Java 中进行一些编码,但它不起作用:
导入java.util.Scanner;
导入java.util.Arrays;
public class 主要
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String [] studentId = new String [3];
Student name;
for (int i = 0; i < 3; i++)
{
System.out.print("Enter Name => ");
name = new Student(input.next());
studentId[i] = name.toString();
}
for (int i = 0; i < 3; i++)
{
System.out.println(studentId[i]);
}
}
}
public class Student
{
private static int studentId;
private String name;
public Student(String name)
{
this.name=name;
setStudentId(studentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
@Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
我需要在创建新条目时自动增加 ID。
我什么都试过了,还是不能增加。
您正在为每个人的 ID 使用静态变量。您需要一个单独的非静态字段来存储每个单独的 ID。
public class Student
{
private static int nextAvailableStudentId = 1;
private String name;
private int studentId;
public Student(String name)
{
this.name=name;
setStudentId(nextAvailableStudentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
@Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
在构造函数中应该是:
{
public Student(String name)
{
this.name=name;
setStudentId(studentId + 1);
}
}
我正在 Java 中进行一些编码,但它不起作用:
导入java.util.Scanner;
导入java.util.Arrays;
public class 主要 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String [] studentId = new String [3];
Student name;
for (int i = 0; i < 3; i++)
{
System.out.print("Enter Name => ");
name = new Student(input.next());
studentId[i] = name.toString();
}
for (int i = 0; i < 3; i++)
{
System.out.println(studentId[i]);
}
}
}
public class Student
{
private static int studentId;
private String name;
public Student(String name)
{
this.name=name;
setStudentId(studentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
@Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
我需要在创建新条目时自动增加 ID。 我什么都试过了,还是不能增加。
您正在为每个人的 ID 使用静态变量。您需要一个单独的非静态字段来存储每个单独的 ID。
public class Student
{
private static int nextAvailableStudentId = 1;
private String name;
private int studentId;
public Student(String name)
{
this.name=name;
setStudentId(nextAvailableStudentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
@Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
在构造函数中应该是:
{
public Student(String name)
{
this.name=name;
setStudentId(studentId + 1);
}
}