-6

使用下面的代码,我可以输入代码、名称和描述。但是,进入购买后。问题是它无法使用正确的代码显示我想显示的详细信息。

import java.util.Scanner;
public class array {
    public static void main(String[] args) {
        Scanner a = new Scanner(System.in);
        int x;
        String q;
        String ans;
        String itemCounts = "";
        String name="",descriptions = "";

        do {
            System.out.print("Item code:");
            itemCounts += "" + a.next() + "\n";

            System.out.print("Item name:");
            name += "" + a.next() + "\n";

            System.out.print("des:");
            descriptions += "" + a.next() + "\n";

            System.out.println("Do you want to add more? yes or no:");
            ans = a.next();
        } while (ans.equals("yes"));


        System.out.print("enter 1 to purchase :");
        x = a.nextInt();

        if(x==1){

            System.out.print("enter code:");
            q = a.next();

            if(q==itemCounts){

                String[] b = itemCounts.split("\n");
                String[] nm = name.split("\n");
                String[] des = descriptions.split("\n");

                for (int i = 0; i < b.length; i++) {

                    System.out.println("Item name:" + nm[i]);
                    System.out.println("Item description:" + des[i]);

                }
            }
        }

    }
}
4

1 回答 1

2

q==itemCounts
应该
q.equals(itemCounts)

因为qitemCounts都是String==测试引用相等和.equals()测试值相等。

itemCounts += "" + a.next() + "\n";应该是itemCounts += a.next();

这将有所帮助:如何比较 Java 中的字符串?

于 2013-10-10T14:19:38.033 回答