我仍然是面向对象编程的菜鸟,所以我想问一下如何在Main.java中运行这一行:Student.displayInfo(students);
如果我尝试在方法和变量中放置一个静态修饰符,那么条件语句会做出暴力反应。你能告诉我怎么做吗?
Main.java
import java.util.Scanner;
public class Main {
public void main(String[] args) {
Scanner in = new Scanner(System.in);
Student[] students = new Student[3];
for (Student student : students) {
System.out.println("Can you code: (y/n) ");
student.canCode = (in.next().charAt(0) == 'y' || in.next().charAt(0) == 'Y');
}
Student.displayInfo(students);
}
}
Student.java
public class Student {
boolean canCode = false;
public boolean getCodingSkill() {
return canCode;
}
public void displayInfo(Student [] students) {
for (Student student : students) {
if (getCodingSkill())
System.out.println("I can code.");
else System.out.println("I can't code.");
System.out.println("\n====================");
}
}
}
答案 0 :(得分:0)
如果我正确理解了你的问题,那么这就是我的答案:
StudentDetails.java:
package TrialPrograms;
public class StudentDetails {
private static String firstname = "";
private static String lastname = "";
private static boolean cancode = false;
private static boolean iscoding = false;
public void setFname(String name) {
this.firstname=name;
}
public String getFname() {
return this.firstname;
}
public void setLname(String name) {
this.lastname=name;
}
public String getLname() {
return this.lastname;
}
public void setCanCode(boolean cancode) {
this.cancode=cancode;
}
public boolean getCanCode() {
return this.cancode;
}
public void setIsCoding(boolean iscoding) {
this.iscoding=iscoding;
}
public boolean getIsCoding() {
return this.iscoding;
}
public void displayInfo(){
System.out.println("Student Records");
System.out.println("=========================================================");
//for (Student student : students) {
System.out.println("Name: " + firstname+ " " + lastname);
if (cancode==true) {
if (iscoding==true) {
System.out.println(firstname + " is coding!!!");
}
else System.out.println(firstname + " can code.");
}
System.out.println("\n=========================================================");
}
}
Main.java:
package TrialPrograms;
import java.util.Scanner;
class Main extends StudentDetails{
public static void main(String[] args) {
StudentDetails stud = new StudentDetails();
Scanner in = new Scanner(System.in);
int noofstudents=3;
for (int i=1;i<=noofstudents;i++) {
System.out.println("Please enter your first name: ");
stud.setFname(in.next());
System.out.println("Please enter your last name: ");
stud.setLname(in.next());
System.out.println("Can you code: (y/n) ");
if (in.next().charAt(0) == 'y' || in.next().charAt(0) == 'Y') {
stud.setCanCode(true);
System.out.println("Are you coding right now: (y/n) ");
if(in.next().charAt(0) == 'y' || in.next().charAt(0) == 'Y') {
stud.setIsCoding(true);
}else {
stud.setIsCoding(false);
}
}else {
stud.setCanCode(false);
}
System.out.println("Loop is over");
stud.displayInfo();
}
in.close();
}
}
希望这段代码能回答你的问题。