Java Iterate array with a fixed length and take values with Scanner class

白昼怎懂夜的黑 提交于 2019-12-06 16:01:15

assuming that your block and input2 variables are already set up and your loop as shown is working, put that loop inside a controller loop

 do {
    for(int i = 0; i<block.length; i++){
        System.out.println("enter number");
        block[i]=input2.next().charAt(0);
    }

 } while (block[0] != 'C" && block[1] != 'C' )

Try this way:

        Scanner input2 = new Scanner(System.in);
        char[] block = new char[2];
        ArrayList<String> arrayList = new ArrayList<String>();
        int i = 0;
        o:
        while (block[0] != 'C' && block[1] != 'C') {
            System.out.println("enter character");
            block[i % 2] = input2.next().charAt(0);
            i++;
            arrayList.add(input2.next());
            if(arrayList.size()>=2){
            if(arrayList.get(arrayList.size()-1).equals("C") && arrayList.get(arrayList.size()-2).equals("C"))
            {
                break o;
            }
            }
        }
   System.out.println(arrayList);

All you need is this

char[] block = new char[2];

while (block[0] != 'C' && block[1] != 'C') {
    System.out.println("enter number");
    block[0]=input2.next().charAt(0);
    System.out.println("enter number");
    block[1]=input2.next().charAt(0);
}

I assume the following from your question

  1. You have an array of fixed length into which you would like to read values using a Scanner
  2. Once you read values into the array,you would like to compare this array with values from another array and do something if the input array matches your array.

This is a simple program that does this:

    String[] scannedValues=new String[2];
    String[] matchValue={"X","Y"};
    boolean isMatched=false;
    Scanner s=new Scanner(System.in);
    while(!isMatched)
    {

        for(int i=0;i<scannedValues.length;i++)
        {
            scannedValues[i]=s.nextLine();
        }
        for(int i=0;i<scannedValues.length;i++)
        {
            if(matchValue[i].equals(scannedValues[i]))
                isMatched=true;
            else
                isMatched=false;
        }
            if(isMatched)
                s.close();
    }

You can use some of the Scanner methods such as nextInt() etc for finding various types of values.You can also pass regular expressions to the Scanner such as next("[A-Z]{1}") However,in case you use a regular expression be aware that a mismatch between the input provided by the user and your expression will cause an InputMismatchException.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!