ArrayList Student Ошибка входа в систему

У меня проблема с моим кодом. Я пытаюсь создать журнал учащегося, в котором при правильном вводе пользователь получит доступ к части memberEnter(), и, если она не верна, система должна выйти.

Я пытался скомпилировать код, и он дает мне ошибку, может кто-нибудь помочь мне исправить это?

Я получаю ошибку:

не может найти символ - переменная studentidlogin

Строка, где происходит ошибка

if(mem.studentidlogin = ("\n Not a member "))

в main метод MainSystem (также отмечено в самом коде).

Основной системный код:

import java.io.*;//imports the io package
import java.util.Scanner;//imports scanner
import java.util.*;//imports the util package

public class MainSystem {

    static String fileName = null;
    static Library lib = new Library();
    static Scanner in = new Scanner(System.in);
    static Boolean running = true;
    static Member mem = new Member();//static variables that can be initialised at compile time, but can be modified at run time

    public static void main(String[] args) throws IOException {// there has to be an input/output
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));//allows the user to type in the script.
        String user, password;
        while (running) {
            System.out.println("\nEnter 0 To login as a Librarian"
                + "\nEnter 1 to Login"
                + "\nEnter 2 to Sign Up");//first display screen in the interface.

            int answer = in.nextInt();
            switch (answer) {
                case 0:

                System.out.println("\nEnter Username: ");
                user = br.readLine();

                System.out.println("\nEnter Password: ");
                password = br.readLine();//if '0' is selected this is displayed.

                if (user.matches("enter") && (password.matches("Password")))// if 0 is entered this has to be entered.
                {
                    librairanEnter();
                    break;
                }
                else
                {
                    System.exit(0);
                }  

                case 1:
                String studentidlogin;
                System.out.println("\nEnter Student ID: ");
                studentidlogin = br.readLine();//if '1' is pressed this is displayed           
                System.out.println(mem.studentidlogin(studentidlogin));

                /************* ERROR OCCURS HERE **************/
                if(mem.studentidlogin = ("\n Not a member "))
                {
                    System.exit(0);
                }else
                {
                    memberEnter();
                    break;
                }

                case 2:
                newMember();//if '2' is selected this is displayed.
                break;

            }
        }

    }

    private static void newMember() throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        int libraryNumber;
        String StudentID, Username, FullName, Address, email, PhoneNumber;

        System.out.println("\nEnter Library Number: ");
        libraryNumber= Integer.parseInt(br.readLine());;//prompts user to enter library number.

        System.out.println("\nEnter Student ID: ");//prompts user to enter student id.
        StudentID = br.readLine();

        System.out.println("\nEnter Full Name: ");//prompts user to enter full name
        FullName = br.readLine();

        System.out.println("\nEnter Username: ");//prompts user to enter username
        Username = br.readLine();

        System.out.println("\nEnter E-Mail Address: ");//prompts user to enter an email address
        email = br.readLine();

        System.out.println("\nEnter Home Address: ");//prompts user to enter home address
        Address = br.readLine();

        System.out.println("\nEnter Phone Number: ");//prompts user to enter phone number
        PhoneNumber = br.readLine();

        StudentSignUp b = new StudentSignUp(libraryNumber, FullName, StudentID, Username, Address, email, PhoneNumber);
        mem.newMember(b);

        System.out.println("\nThankyou. You can now Login.: ");// prompts user that they can now sign in.
    }

    private static void memberEnter() throws IOException {
        while (running) {
            System.out.println("\nEnter 0 for load a library."
                + "\nEnter 1 for save and quit"
                + "\nEnter 2 for list all books in library"
                + "\nEnter 3 for Search For A Book");//options available if member is enters.

            int answer = in.nextInt();
            switch (answer) {
                case 0:
                System.out.println("Enter the file name to load");
                loadScript(in.next());//loads previously saved script
                break;
                case 1:
                saveAndQuit();//saves and quits from the system
                break;
                case 2:
                System.out.println(lib.toString());//lists all the books in the library
                break;
                case 3:
                searchBook();//searches for a book
                break;

            }
        }
        System.exit(0);
    }

    private static void librairanEnter() throws IOException {
        while (running) {
            System.out.println("\nEnter 0 for load a library."
                + "\nEnter 1 for save and quit"
                + "\nEnter 2 for list all books in library"
                + "\nEnter 3 for add book to library"
                + "\nEnter 4 for Search For A Book"
                + "\nEnter 5 for list of current members"
                + "\nEnter 6 to borrow a book"
                + "\nEnter 7 to return a book");//options available if the librarian logs in.

            int answer = in.nextInt();
            switch (answer) {
                case 0:
                System.out.println("Enter the file name to load");
                loadScript(in.next());//loads previously saved libraries
                break;
                case 1:
                saveAndQuit();//saves and quits
                break;
                case 2:
                System.out.println(lib.toString());//prints current books in library
                break;
                case 3:
                addBook();//adds a book to the system
                break;
                case 4:
                searchBook();//searches for a book in the system
                case 5:
                System.out.println(mem.toString());//list of current members
                break;
                case 6:
                borrowBook();//allows to borrow a book.
                case 7:
                returnBook();//allows to return a book.

            }
        }
        System.exit(0);//exits from the system/
    }

    private static void addBook() throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int isbn, numcopies;
        String author, title, genre;// initializes the variables

        System.out.println("\nEnter ISBN: ");
        isbn = Integer.parseInt(br.readLine());//prompts user to enter isbn

        System.out.println("\nEnter Author: ");//prompts user to enter the auth
        author = br.readLine();

        System.out.println("\nEnter Title: ");//prompts user to enter title
        title = br.readLine();

        System.out.println("\nEnter Genre: ");//prompts user to enter genre
        genre = br.readLine();

        System.out.println("\nEnter Number Of Copies: ");//prompts user to enter number of copies
        numcopies = Integer.parseInt(br.readLine());

        Book b = new Book(isbn, author, title, genre, numcopies);//Creates the new book and adds it to the library
        lib.addBook(b);
    }

    private static void saveAndQuit() {//saves and quits
        // TODO Auto-generated method stub
        System.out.println("Enter file name: ");//prompts the user to enter the file name.
        fileName = in.next() + ".ser";//saves the file name
        running = false;
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        try {
            fos = new FileOutputStream(fileName);
            out = new ObjectOutputStream(fos);
            out.writeObject(lib);
            fos.close();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static void loadScript(String name) {//loads a previously saved script
        // TODO Auto-generated method stub
        FileInputStream fis = null;
        ObjectInputStream in = null;
        File file = new File(name + ".ser");
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
                in = new ObjectInputStream(fis);
                lib = (Library) in.readObject();
                fis.close();
                in.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            System.out.println("\nThe file does not exist!");
        }
    }

    private static void searchBook() throws IOException//allows searching for a book
    {
        String titleSearch;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        while(running) {
            System.out.println("\nEnter 0 to search on title."////prompts the user to answer 0
                + "\nEnter 3 to go back");//promts the user to enter 3

            int answer = in.nextInt();
            switch (answer) {
                case 0:
                System.out.println("Enter the book Title");//promts the user to enter the title of the book
                titleSearch = br.readLine();
                System.out.println(lib.searchTitle( titleSearch));

                break;
                case 3:
                librairanEnter();//takes the user back to the librarian home page.

            }
        }
    }

    private static void borrowBook() throws IOException
    {
        String titleBorrow;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        while(running) {
            System.out.println("\nEnter 0 to search on title."//prompts the user to answer 0
                + "\nEnter 3 to go back");//prompt the user to answer 3

            int answer = in.nextInt();
            switch (answer) {
                case 0:
                System.out.println("Enter the book Title");//promts the user ot enter the book title
                titleBorrow = br.readLine();
                System.out.println(lib.borrowBook( titleBorrow));

                break;
                case 3:
                librairanEnter();//takes the user back to the librarian home page.

            }
        }
    }

    private static void returnBook() throws IOException
    {
        String returnedBook;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        while(running) {
            System.out.println("\nEnter 0 to retrun a book."//promts the user to enter 0
                + "\nEnter 3 to go back");//prompts the user to enter 3

            int answer = in.nextInt();
            switch (answer) {
                case 0:
                System.out.println("Enter the book Title");//promts the user to enter the book title.
                returnedBook = br.readLine();
                System.out.println(lib.returnBook( returnedBook));

                break;
                case 3:
                librairanEnter();//takes the user back to the librarian home page.

            }
        }
    }

}

Класс участника:

import java.util.*;
import java.io.*;
/**
 * Write a description of class Member here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */

public class Member
{
   private List<StudentSignUp> memberList;//creates the array list


    public Member()
    {
        memberList = new ArrayList<StudentSignUp>(); //makes the 'memberList' the array list. 
    }
    public void newMember(StudentSignUp student)
    {
        memberList.add(student);//adds a student to the array list.
    }
    public String toString()
    {
        String totalmem = "\n ";
        for (int i=0; i<memberList.size(); i++)
        {
            StudentSignUp b = memberList.get(i);
            totalmem = totalmem + b.toString(); //prints out all students
        }

        return totalmem;
    }

        public String studentidlogin(String studentidlogin) {
        if (studentidlogin == null) return "\n Not a member ";
        for(int i = 0; i < memberList.size(); i++){
            if(studentidlogin.equalsIgnoreCase(memberList.get(i).getStudentID())){
                return memberList.get(i).toString();//allows user to search for a book in the system
            }
        }
        return "\n Not a member "; //reachable only if no book found
    }





}

3 ответа

Решение

Ваш код:

        System.out.println(mem.studentidlogin(studentidlogin));

        if(mem.studentidlogin = ("\n Not a member "))

Первое использование mem.studentidlogin, в println() Звоните, это правильно. поскольку studentidlogin это метод Member класс, он должен вызываться как метод - с круглыми скобками и аргументами, которые соответствуют его параметрам.

Второе использование неверно. Вы рассматриваете это, как будто это поле. Я думаю, возможно, вы ожидали, что это будет результат, который был возвращен из предыдущего вызова, но если это так, Java не работает таким образом.

Кроме того, я считаю, что вы пытаетесь сравнить его со строкой "\n Not a member ", Сравнение строк должно быть сделано только с equals() или же equalsIgnoreCase()!

Когда код стоит, похоже, что вы пытаетесь присвоить значение полю (которого не существует) внутри if утверждение, которое ожидает только логическое значение (сравнение будет == который, как я уже сказал, вы не должны использовать в любом случае, но вы используете назначение =).

У вас есть два варианта. Либо позвоните еще раз правильно:

        System.out.println(mem.studentidlogin(studentidlogin));

        if(mem.studentidlogin().equals("\n Not a member "))

Или, желательно, чтобы не выполнять всю работу дважды, определите переменную:

        String loginResult = mem.studentidlogin(studentidlogin);
        System.out.println(loginResult);

        if( loginResult.equals("\n Not a member "))

Это:

public static void main(String[] args) throws IOException {// there has to be an input/output
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));//allows the user to type in the script.
    String user, password;
    while (running) {
        System.out.println("\nEnter 0 To login as a Librarian"
            + "\nEnter 1 to Login"
            + "\nEnter 2 to Sign Up");//first display screen in the interface.

        int answer = in.nextInt();
        switch (answer) {
            case 0:

            System.out.println("\nEnter Username: ");
            user = br.readLine();

            System.out.println("\nEnter Password: ");
            password = br.readLine();//if '0' is selected this is displayed.

            if (user.matches("enter") && (password.matches("Password")))// if 0 is entered this has to be entered.
            {
                librairanEnter();
                break;
            }
            else
            {
                System.exit(0);
            }  

            case 1:
            String studentidlogin;
            System.out.println("\nEnter Student ID: ");
            studentidlogin = br.readLine();//if '1' is pressed this is displayed           
            System.out.println(mem.studentidlogin(studentidlogin));

            if(mem.studentidlogin = ("\n Not a member "))
            {
                System.exit(0);
            }else
            {
                memberEnter();
                break;
            }

            case 2:
            newMember();//if '2' is selected this is displayed.
            break;

        }
    }

}

чтобы вы сделали mem.studentidlogin вместо studentidlogin в операторе if:

public static void main(String[] args) throws IOException {// there has to be an input/output
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));//allows the user to type in the script.
    String user, password;
    while (running) {
        System.out.println("\nEnter 0 To login as a Librarian"
            + "\nEnter 1 to Login"
            + "\nEnter 2 to Sign Up");//first display screen in the interface.

        int answer = in.nextInt();
        switch (answer) {
            case 0:

            System.out.println("\nEnter Username: ");
            user = br.readLine();

            System.out.println("\nEnter Password: ");
            password = br.readLine();//if '0' is selected this is displayed.

            if (user.matches("enter") && (password.matches("Password")))// if 0 is entered this has to be entered.
            {
                librairanEnter();
                break;
            }
            else
            {
                System.exit(0);
            }  

            case 1:
            String studentidlogin;
            System.out.println("\nEnter Student ID: ");
            studentidlogin = br.readLine();//if '1' is pressed this is displayed           
            System.out.println(mem.studentidlogin(studentidlogin));

            if(studentidlogin.equals("\n Not a member "))
            {
                System.exit(0);
            }else
            {
                memberEnter();
                break;
            }

            case 2:
            newMember();//if '2' is selected this is displayed.
            break;

        }
    }

}

Ваша функция

 public String studentidlogin(String studentidlogin)

принимает строковый аргумент, но вы вызываете его так:

mem.studentidlogin = ("\n Not a member ")

редактировать: просто чтобы расширить мои ответы. вам нужно решить еще несколько проблем. возможно, чтение по основам Java поможет.

например

 if(studentidlogin = ("\n Not a member "))

Вы хотите сравнить две строки и использовать оператор присваивания (=), но в вашем случае вам нужен метод equals.

String str = "anything";
if (str.equals("anything")) {
//do something
}

Я думаю, что вы имели в виду использование оператора ==, но это сравнивает только две области памяти.

Другие вопросы по тегам