对象的循环不仅仅适用于方法java

eqqqjvef  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(310)

该程序似乎编译和工作良好唯一的问题是在可用的书籍(字符串标题)方法,甚至不循环通过列表“数学”和工作不正常。我不明白为什么会出现这个问题。我是新的编程和任何帮助将不胜感激。谢谢你在这方面。:)
主要类别:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;
import java.lang.String;
public class MainLibrary {
    static Scanner scan=new Scanner(System.in);
    public List <Student> mathites=new ArrayList<Student>();
    public List <Professor> daskaloi=new ArrayList<Professor>();
    public Student Scurrent;//apothikeuoun to antikeimeno pou brethike apo AnazitisiName
    public Professor Pcurrent;
    String biblia[]=new String[]{"2666","All About Love","Desert Solitaire","Disgrace","Geek Love","Gilead","A Good Man Is Hard to Find","The Handmaid's Tale",
    "The Hitchhiker's Guide to the Galaxy","Infinite Jest","The Left Hand of Darkness","Lolita"};

    public void firstMenu(){
      boolean ch=true;
      int answer=0;
      while (ch){
        System.out.println("=======MENU========\n1.Make account.\n2.Login\n3.Exit programm.");
        answer=ChooseOption(1,3);

      switch(answer){
        case 1:
          MakeAcc();
          break;
        case 2:
          LoginSystem();
          break;
        case 3:
          return;
        default:
          System.out.println("Wrong input!!");
      }
    }
}
    public  int PorS(){
      boolean check=true;
      int an=0;
      while(check){  // check if student or Professor
        check=false;
        System.out.println("Are you a Student or Professor?    ~~1=Student || 2=Professor");
        try{
          an=scan.nextInt(); //an= account property
          scan.nextLine();
          if(an!=1 && an!=2){
            throw new InputMismatchException();
          }
        }
        catch(InputMismatchException imex){
          scan.nextLine();
          System.out.println("Invalid Input");
          check=true;
        }
    }
    return an;
    }

    public void LoginSystem(){
      boolean check;
      int an,i,j;
      String name="";

      an=PorS();
      check=true;
      while (check){
        check=false;
        System.out.print("Enter username:");
        name=scan.nextLine();
        if(name.equals("exit")){
          return;
        }
        if(AnazitisiName(name,an)){
          System.out.println("Username: '"+name+"' does not exist.Type 'exit' if you want to quit ");
          check=true;
        }
      }
      if(an==1){
        Scurrent.login();
        Scurrent.LoginMenu();
    }
      else{
        Pcurrent.login();
        Pcurrent.LoginMenu();
      }
    }

    public int ChooseOption(int a,int b){ //basic diabasma epilogon apo a mexri b
      int an;
      while(true){
        try{
          System.out.print("Option: ");
          an=scan.nextInt();
          System.out.println();
          if (an<a || an>b)
            throw new InputMismatchException();
          return an;
       }
          catch(InputMismatchException aex){
            System.out.println("Invalid Input!!");
            scan.nextLine();
          }
        }
    }

    public void displayBooks (){ //kanei display ta biblia k dixnei poia einai available
      int i=1;
      System.out.println("---------Library Books---------");
      for(String t : biblia){
        System.out.println(i+++"."+t);
        System.out.print(AvailabilityBooks(t)?"    |Available":"    |Not Available");
        System.out.println();
      }

      System.out.println("13.exit");
      System.out.println("-------------------------------");
    }

    public boolean AvailabilityBooks (String tittle){ //true if it's available

      for (Student s : mathites){
          System.out.println("AAA");
          for (int i=0; i<s.books; i++){
            if (s.GetTittle(i).equals(tittle))
              return false;
          }
        }
        for (Professor s : daskaloi){
          for (int j=0; j<s.books; j++){
            if (s.GetTittle(j).equals(tittle))
              return false;
          }
       }

       return true;
    }

    public  void MakeAcc(){
      String name="empty";
      int password;
      int temp,clas=0;
      boolean check=true,upper;
      clas=PorS();

      check=true;
      while(check){ //username input
          System.out.println("Enter Username |5-12 characters used |at least 1 number and no more than 2 |at least 1 Uppercase letter    !!!type 'exit' if you dont want to create account.");
          System.out.print("Username: ");
          name=scan.nextLine();
          if (name.equals("exit")){
            return;
          }
          System.out.println();
          check=false;
          upper=false;//check if there is one upper letter
          if(!AnazitisiName(name,clas)){ //check if it's already exists
            check=true;
            System.out.println("This username already exists");
          }
          else if (name.length()<5 || name.length()>12){  //check username leangth
            System.out.println("Invalid length!");
            check=true;
          }
          else{
            temp=0; //count characters
            for (char p: name.toCharArray()){ //check if there are more than 2 digits
                if( Character.isDigit(p) ){
                  temp++;
                }
                if (Character.isUpperCase(p)){
                  upper=true;
                }
            }
          if (temp>2){
            System.out.println("Only 2 numbers are allowed");
            check=true;
          }
          else if (temp==0){
            System.out.println("Username must contain at least 1 number!");
            check=true;
          }
          if (!upper){
            System.out.println("Username must contain at least 1 Uppercase letter ");
            check=true;
          }
        }
       }
       System.out.println("New account ||| "+ name);

      if(clas==1)
        mathites.add(new Student(name));
      else if (clas==2)
        daskaloi.add(new Professor(name));

  }
  public  boolean AnazitisiName(String n,int b){//true if name is available  ||  b=1 then Student
    int a;
    if(b==1){
      if (mathites.isEmpty()){
        return true;
      }
      for (Student s : mathites){
        System.out.println("AA");
        if(s.GetName().equals(n)){
          Scurrent=s;
          return false;
        }
      }
        return true;
    }
    else{
      if (daskaloi.isEmpty()){
        return true;
      }
      for (Professor s : daskaloi){
        if(s.GetName().equals(n)){
          Pcurrent=s;
          return false;
        }
      }
        return true;
    }
 }
 public void printmath(){
   for(Student p : mathites)
    System.out.println(p.toString());

 }

  public static void main(String[] args) {
      MainLibrary l1=new MainLibrary();
      l1.firstMenu();

  }
}

学生班级:

import java.util.ArrayList;
import java.util.List;
public class Student extends MainLibrary implements LibraryAccess,NetworkAccess{
      private String name;
      public int books=0;
      private List<String> titloi = new ArrayList<String>();
      public int connection=0;

      Student(String n){
        this.name=n;
        for (String s : this.titloi){
          s="Empty";
        }
      }
      public String GetName(){
        return this.name;
      }

      public String GetTittle(int k){
        return this.titloi.get(k);
      }

      public String toString(){
          String stat= (this.connection==0) ? " off" : " on";

          return ("\n\nStudent Status: \nName:"+this.name+ "\nConnection:"+stat+"\nBooks borrowed: "+this.books+" || "+this.titloi);
      }

      public void returnBook(String tittle){
        String temp;
        if (this.books > 0){
          this.titloi.remove(tittle);
          this.books--;
          System.out.println("Book '"+tittle+ "' returned succesfully! \n");
          }
        else
          System.out.println(this.name+",you have 0 books.What are u supposed to return. >:| \n");
      }

      public void borrowBook(String tittle){
        if (this.books < 3){
          this.titloi.add(tittle);
          this.books++;
          System.out.println("Book '"+tittle+"' borrowed succesfully!\n");
        }
        else
          System.out.println("Sorry "+this.name+" you have already 3 books.You have to return a book if you want to borrow another one. :)\n");
      }

      public void login(){
        if (this.connection==0)
          this.connection++;
        else
          System.out.println(this.name+",you are already logged in.\n");
      }

      public void logoff(){
        if (this.connection==1)
          this.connection--;
        else
          System.out.println(this.name+",you are already logged off.\n");
      }

      public void LoginMenu(){
          int an;
          while(true){
            System.out.println("1.Borrow book\n2.Return book\n3.Account Status\n4.Logout ");
            an=ChooseOption(1,4);
            switch(an){
              case 1:
                AnazitisiName("Chrisgate7",1);
                this.BorrowB();
                break;
              case 2:
                this.ReturnB();
                break;
              case 3:
                System.out.println(this.toString());
                break;
              case 4:
                this.logoff();
                return;

            }
          }
      }

          public void BorrowB(){
             int an;  //saves the answer from displayBooks
              this.displayBooks();
              while(true){
                an=ChooseOption(1,13)-1;
                if (an==12){
                  return;
                }
                else if(!AvailabilityBooks(biblia[an]))
                      System.out.println(biblia[an]+" is not Available.Borrow attempt failed!\n");
                else{
                    this.borrowBook(biblia[an]);
                    return;
                  }
                }
              }

          public void ReturnB(){//cannot find symbol problima me to books na lithei AMESAA!!!!!!!
              int an=0;
              int i,p=1;
              int btemp=this.books;
              if(btemp!=0){
                System.out.print("Your books: ");
                for (String s: this.titloi){
                    System.out.print((p++)+"."+s+"\n");
                  }
                System.out.print((btemp+1)+".Exit\n");
                an=ChooseOption(1,btemp+1);
                if (an==(btemp+1))
                  return;
                else{
                  this.returnBook(this.titloi.get(an-1));
                }
              }
              else
                System.out.println("You have 0 books borrowed.Return attempt failed.\n");
      }

}

教授班级:

import java.util.ArrayList;
import java.util.List;
public class Professor extends MainLibrary implements LibraryAccess,NetworkAccess{
    private String name;
    public int books=0;
    public int connection=0;
    private List<String> titloi=new ArrayList<String>();

    Professor(String n){
      this.name=n;
    }

    public String GetTittle(int k){
        return  this.titloi.get(k);
    }

    public String GetName(){
      return this.name;
    }

    public String toString(){
        return ("\n\nProfessor Status: \nName:"+this.name+ "\nConnections :"+this.connection+"\nBooks borrowed: "+this.books+" || "+this.titloi);
    }

    public void borrowBook(String tittle){
      if (this.books < 8){
        this.titloi.add(tittle);
        this.books++;
        System.out.println("Book '"+tittle+"' borrowed succesfully!\n");
      }
      else
        System.out.println("Sorry "+this.name+" you have already 8 books.You have to return a book if you want to borrow another one. :)\n");
    }

    public void returnBook(String tittle){
      if (this.books > 0){
        this.titloi.remove(tittle);
        this.books--;
        System.out.println("Book '"+ tittle+ "' returned succesfully! \n");
        }
      else
        System.out.println(this.name+",you have 0 books.What are u supposed to return. >:| \n");
    }

    public void login(){
      if (this.connection<3)
        this.connection++;
      else
        System.out.println("Sorry "+this.name+"you are already 3 active connections.You cant make another one.");
    }

    public void logoff(){
        if (this.connection<3)
          this.connection--;
       else
          System.out.println(this.name+",you are already logged off.");
          }

    public void LoginMenu(){
      int an;
      while(true){
        System.out.println("1.Borrow book\n2.Return book\n3.Account Status\n4.Logig\n5.Logout ");
        an=ChooseOption(1,4);
        switch(an){
          case 1:
            this.BorrowB();
            break;
          case 2:
            this.ReturnB();
            break;
          case 3:
            System.out.println(this.toString());
            break;
          case 4:
            this.logoff();
            return;
          case 5:
            this.logoff();
            if (this.connection==0){
              System.out.println("Logged off successfully");
              return;
            }
            else
              System.out.println("Logged off successfully.Connections: "+Pcurrent.connection);
            break;

              }
            }
        }

    public void BorrowB(){
       int an;  //apothikeuei tin apantisi apo displayBooks
       displayBooks();
       while(true){
          an=ChooseOption(1,13)-1;
            if (an==12){
              return;
            }
          else if(!AvailabiltyBooks(biblia[an]))
              System.out.println(biblia[an]+" is not Available.Borrow attempt failed!");
          else{
              this.borrowBook(biblia[an]);
              return;
            }
          }
      }

    public void ReturnB(){//cannot find symbol problima me to books na lithei AMESAA!!!!!!!
        int an=0;
        int p=0;
        int btemp=this.books;

          if(btemp!=0){
            System.out.print("Your books: ");
            for (String s: titloi){
              System.out.print(p++ +"."+s+"\n");
            }
            System.out.print((btemp+1)+".Exit");
            an=ChooseOption(1,btemp+1);
            if (an==(btemp+1))
              return;
            else{
             this.returnBook(this.titloi.get(an-1));
              System.out.println("Book '"+this.titloi.get(an-1)+"' returned successfully ");
          }
          }
        else
          System.out.println("You have 0 books borrowed.Return attempt failed.");
        }

}

libraryaccess和networkaccess接口:

public interface LibraryAccess{

  public void returnBook(String tittle);
  public void borrowBook(String tittle);
}
public interface NetworkAccess{

  public void login();
  public void logoff();
}
fwzugrvs

fwzugrvs1#

问题

在运行时,当您在availabilitybooks中时,这将引用您当前的对象。你可以检查一下 System.out.println(this) 在你的可用性手册里。
这就是为什么你的学生列表在这里是空的,为什么它不会进入你的for循环。

解决方案

要解决这个问题,您可以使列表独立于mainclass对象,所以只需将其设置为静态。 public static List <Student> mathites=new ArrayList<Student>(); 逻辑上也有问题。
想象一下,第一个书名是不相等的,它会立即返回false,并且在不检查其他书籍的情况下跳出循环。
因此,你比较标题,你可以初步认为它是不可用的,然后当标题是平等的,这意味着它是可用的,所以你可以立即返回真;
如果学生和教授的头衔不相等,则返回false。

public boolean AvailabilityBooks (String tittle){ //true if it's available

  for (Student s : mathites){
      System.out.println("AAA");
      for (int i=0; i<s.books; i++){
        if (s.GetTittle(i).equals(tittle))
          return true;
      }
    }
    for (Professor s : daskaloi){
      for (int j=0; j<s.books; j++){
        if (s.GetTittle(j).equals(tittle))
          return true;
      }
   }

   return false;
}

输出

更改后,如果您借用12,您将收到以下结果。还有10个。项目。

---------Library Books---------
1.2666
AAA
    |Available
2.All About Love
AAA
    |Available
3.Desert Solitaire
AAA
    |Available
4.Disgrace
AAA
    |Available
5.Geek Love
AAA
    |Available
6.Gilead
AAA
    |Available
7.A Good Man Is Hard to Find
AAA
    |Available
8.The Handmaid's Tale
AAA
    |Available
9.The Hitchhiker's Guide to the Galaxy
AAA
    |Available
10.Infinite Jest
AAA
    |Not Available
11.The Left Hand of Darkness
AAA
    |Available
12.Lolita
AAA
    |Not Available
13.exit
-------------------------------
Option:

相关问题