简体   繁体   English

ArrayList不在Java中添加userinput

[英]Arraylist doesnot add userinput in java

The purpose of this program is to print out a message saying 'you missed' each time a coordinate is entered.However,if a duplicate coordinate is entered,it should say 'This coordinate is already present.' 该程序的目的是在每次输入坐标时打印出一条消息,指出“您错过了”。但是,如果输入了重复的坐标,则应该说“此坐标已存在”。

I used 2 arraylists simultaneously,to independantly store the values of x and yI fail to understand what is wrong with my code.The if statements don't seem to be working at all and the userinput also doesnt seem to be added to the arraylists. 我同时使用2个数组列表来独立存储x和y的值我无法理解我的代码出了什么问题。if语句似乎根本不起作用,并且userinput似乎也没有添加到数组列表中。

Scanner a=new Scanner(System.in);

//Arraylist stores all entered x values.
ArrayList<Integer> XValues=new ArrayList<Integer>();
//Arraylist stores all entered y values.
ArrayList<Integer> YValues=new ArrayList<Integer>();

int Nooftries=0;
int xcoord;
int ycoord;

for(int i=0;i<10;i++)
{
    Nooftries++;
    System.out.println("This is guess #"+Nooftries);

    System.out.print("Please input your x location (0-3) : ");
    xcoord=a.nextInt();
    System.out.print("Please input your y location (0-3) : ");
    ycoord=a.nextInt();

    XValues.add(xcoord);
    YValues.add(ycoord);


    for(int c=0;c<XValues.size();c++)
    {

        if(xcoord==XValues.get(c) && ycoord==YValues.get(c))
        {

            System.out.println("You've already picked that spot.\n");
            break;
        }
        else
        {
            System.out.println("You missed!");
        }
    }
}

You do this: 你做这个:

XValues.add(xcoord);
YValues.add(ycoord);

And then you check. 然后您检查。 Since you've added the most recently input values, of course your arrays will contain those values when you check afterwards. 由于您已添加了最新输入的值,因此,事后检查时,数组将包含这些值。

You'll want to check before adding. 您需要添加之前进行检查。 Alternatively you could just check up to XValues.size() - 1 , but doing the check before adding more clearly reflects your intent. 另外,您最多可以检查XValues.size() - 1 ,但是在添加之前进行检查可以更清楚地反映您的意图。

The if statements are working; if 报表工作; your program is simply doing precisely what you told it to do. 您的程序只是在完全按照您的指示执行。 You just need to tell it to do the right thing! 您只需要告诉它做正确的事即可!

The rest of your logic looks fine at a glance. 其余逻辑一目了然。

You have added xcoord and ycoord into the array lists right before the for loop, so of course the for loop will spot them and show You've already picked that spot . 您已经在for循环之前将xcoordycoord添加到了数组列表中,因此, for循环当然会发现它们并显示You've already picked that spot You should add them after the for loop. 您应该在for循环之后添加它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM