输出应该是数组中的内容

时间:2015-07-05 10:46:42

标签: java

我正在做一个图书馆系统,一旦我输入一个图书名称,并在数组中找到,输出就会是#34;这本书被退回" 。但每当我输入数组中列出的书籍的名称时,它仍然会说#34;这本书出了问题"。我该如何解决这个问题?

import java.util.Scanner;
public class NewClass {
    public static void main (String args[]){
        Scanner book = new Scanner(System.in);
        String [] library = new String [4];
        library [0] = "Brazil";
        library [1] = "Japan";
        library [2] = "China";
        library [3] = "India";       

        String bookEntry = " ";
        int day;
        int x = 2;
        int penalty;
         for (int i = 0; i < library.length; i++){
        System.out.println("Insert name of the book: ");
        bookEntry= book.next();

           if (bookEntry == library[i]){
               System.out.println("The book was returned");
           }else if (bookEntry != library[i]){ 
               System.out.println("The book is out of order");

System.out.println("\n" + bookEntry.toUpperCase()+ " " + "is out since: ");
day = book.nextInt();

if (day > x){
    penalty = day*20;
    System.out.println("Total fine: " + penalty);
}else{
    System.out.println("Not yet due.");
}
       }


    }
    }
}

1 个答案:

答案 0 :(得分:1)

在Java中,您不会按==比较2个字符串。

相反,您使用.equals()String方法。

  • == - &gt; 是参考比较,即两个对象都指向相同的内存位置
  • .equals() - &gt; 评估值的比较 对象

有关此here

的更多信息

更正了以下代码:

import java.util.Scanner;

public class NewClass {

public static void main(String args[]) {
    Scanner book = new Scanner(System.in);
    String[] library = new String[4];
    library[0] = "Brazil";
    library[1] = "Japan";
    library[2] = "China";
    library[3] = "India";
    String bookEntry = " ";
    int day;
    int x = 2;
    int penalty;
    System.out.println("Insert name of the book: ");
    bookEntry = book.next();
    boolean present = false;
    for (int i = 0; i < library.length; i++) {
        if (bookEntry.equals(library[i])) {
            present = true;
            break;
        }
    }
    if (present) {
        System.out.println("The book was returned");
    } else {
        System.out.println("The book is out of order");
        System.out.println("\n" + bookEntry.toUpperCase() + " " + "is out since: ");
        day = book.nextInt();
        if (day > x) {
            penalty = day * 20;
            System.out.println("Total fine: " + penalty);
        } else {
            System.out.println("Not yet due.");
        }
    }
}
}

工作代码here

更新:我更改了代码。