【问题标题】:loop of objects does not work in only on method- java对象循环仅适用于方法-java
【发布时间】:2021-01-06 08:20:18
【问题描述】:

Thr 程序似乎可以编译并正常工作,唯一的问题是 AvailabilityBooks(String tittle) 方法甚至不遍历列表“mathites”并且无法正常工作。我不明白为什么会出现这个问题。我是编程新手,任何帮助将不胜感激。谢谢。 :)

主类:

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

【问题讨论】:

  • 问题似乎是你的 for 循环中的 return 语句。这将退出该方法,并且不会进行进一步的循环迭代。这发生在AvailabilityBooks 方法中。我认为您想迭代那里的所有教授、学生和书籍。
  • 另外,你应该重新检查你的逻辑。退出 checkStudentOrProfessor 的唯一方法是输入无效输入。这没有任何意义
  • @Sebastian 我知道,这就是我想要的,但它似乎甚至没有循环遍历 if 语句......
  • 你的可用性书籍的逻辑是什么让学生和教授都可以使用?如果标题相等,为什么返回 false?
  • @Alex 它正在检查这本书是否已经被借阅。如果有人(教授或学生)借过这本书,那么它应该是不可用的。

标签: java loops object


【解决方案1】:

问题

在运行时,当您在 AvailabilityBooks 中时,这将引用您 Scurrent 对象。您可以在执行System.out.println(this) 时检查此内容 在您的 AvailabilityBooks 中。

这就是为什么你的 StudentList 在这里是空的以及为什么它不会进入你的 for 循环的原因。

解决方案

要解决此问题,您可以使列表独立于 MainClass 对象,因此只需将其设为静态即可。

public static List &lt;Student&gt; mathites=new ArrayList&lt;Student&gt;();

逻辑也有问题。

假设第一个标题不相等,它会立即返回 false 并退出循环而不检查其他书籍。

因此,您比较最初认为不可用的标题,然后当标题相同时,这意味着它可用,因此您可以立即返回 true;

如果 student 和 prof 中没有相同的职称,则返回 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: 

【讨论】:

  • 作为参数给出的标题是图书馆中的一本书,如果其他人拥有它,正在检查它。对于您所说的,如果我想检查所有书籍,我将通过一个循环来检查图书馆拥有的每一本书。(检查 displayBooks 方法)。想象一下,如果我运行程序命令 System.out.println(" AAA") 甚至不会被打印出来..
  • 好的,我会检查一下,但显然您的列表中没有学生。
  • 未收到错误。如果您创建帐户正在创建学生并进入列表。并且您无法在没有帐户的情况下登录,因此要访问方法可用性手册,列表中必须至少有一个学生对象.
  • 在其他方法中,相同的循环工作正常。(例如 printmath())。
  • 我尝试在索引 0 处打印 mathites,结果超出范围,因为 index0 处没有元素
猜你喜欢
  • 2013-04-11
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
相关资源
最近更新 更多