2

How can i get the value of a java array using Scanner class with a fixed length of 2, and which will iterate until its value is equal to a given value? For example; for the following inputs,

   A G 

   N H

   D F      

I wrote a for loop to take the values of fixed array road, in which the length is 2 using Scanner class.

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

I want to iterate this loop while the user input is {'C','C'}. THat means the array loop shpuld stop if the inputs are as follow;

A G

N H

D F

C C

How can i write the code to take user input values using Scanner class and to iterate the array? And the user input values should be copied without replacing them with newly entered values. Thank you!

4

4 回答 4

2

试试这个方法:

        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);
于 2013-10-26T09:17:41.667 回答
2

假设您的 block 和 input2 变量已经设置并且您的循环如图所示正在工作,将该循环放在控制器循环中

 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' )
于 2013-10-26T09:02:16.747 回答
1

你只需要这个

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);
}
于 2013-10-26T09:02:24.497 回答
0

我从您的问题中假设以下内容

  1. 您有一个固定长度的数组,您想使用 Scanner 读取值
  2. 将值读入数组后,您希望将此数组与另一个数组中的值进行比较,并在输入数组与您的数组匹配时执行某些操作。

这是一个执行此操作的简单程序:

    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();
    }

您可以使用一些 Scanner 方法(例如nextInt()etc)来查找各种类型的值。您还可以将正则表达式传递给 Scanner,例如next("[A-Z]{1}") 但是,如果您使用正则表达式,请注意用户提供的输入之间的不匹配并且您的表达式将导致 InputMismatchException。

于 2013-10-26T10:01:16.627 回答