Java字符串与对象字符串的比较

时间:2015-01-05 12:51:25

标签: java arraylist

所以我有一个我在另一个对象中导入的对象

第一个对象:

package test;
import java.util.*;

public class Eveniment {
    int ziua;
    String luna = new String();

    public void setZiua(int param){
        ziua = param;
    }
    public void setLuna(String param){
        luna = param;
    }
    public int getZiua(){
        return ziua; 
    }
    public String getLuna(){
        return luna;
    }
}

第二个对象:

package test;
import test.*;
import java.util.*;
public class EventPlanner {

    public static void main(String[] args){
        ArrayList<Eveniment> myAr = new ArrayList();
        Scanner sc = new Scanner(System.in);

        System.out.println("Introduceti ziua urmata de luna evenimentului: ");

        int zi = 0;
        String luna;
        zi = sc.nextInt();
        luna = sc.nextLine();

        Eveniment first = new Eveniment();
        first.setZiua(zi);
        first.setLuna(luna);

        myAr.add(first);

        while(luna!=null && zi!=0)
        {
            zi = sc.nextInt();
            luna = sc.nextLine();

            if(zi!=0)
            {
                Eveniment ev = new Eveniment();
                ev.setZiua(zi);
                ev.setLuna(luna);

                myAr.add(ev);
            }

        }

        String l = new String();
        l = "Ianuarie";

        System.out.println(myAr.size());*/

        for(int i = 0; i < myAr.size(); i++){
            if(myAr.get(i).getLuna().equals(l))
                System.out.println(1);
            else
                System.out.println(0);
        }
    }

    public static void afisare(ArrayList<Eveniment> myAr){
        System.out.println("---------Array------------");
        for(Eveniment i : myAr){
            System.out.println(i.getLuna() +" "+i.getZiua());
        }
    }
}

让我烦恼的是,在for里面我检查当前对象是否有luna字符串等于l字符串然后我打印出1其他我打印0 ,但即使字符串相等,算法也打印出0,我做错了什么? 我是Java的新手,所以请不要过于严厉地判断。

给予该计划的输入:

1 Decembrie
2 Ianuarie
3 Februarie
4 Martie
0//to end the input

程序应该写

`Decembrie` 0
`Ianuarie` 1
`Februarie` 0
`Martie` 0

因为l等于Ianuarie

1 个答案:

答案 0 :(得分:4)

这是因为

l = "Ianuarie"

 myAr.get(i).getLuna() =" Ianuarie"
                        ^--->there are space before the Ianuarie

所以你永远不会得到1