【发布时间】:2016-01-10 03:01:09
【问题描述】:
我必须编写一个程序,用 1 到 100 之间的随机数填充数组。用户将输入数组的大小。把数组填满。然后用户将输入他们要查找的数字,程序将返回该数字在数组中的位置,如果它不在数组中,则返回 -1。继续这样做,直到 use 进入 -1。
这是我目前所拥有的:
Scanner kb = new Scanner (System.in);
System.out.println("Please enter row size");
int row = kb.nextInt();
System.out.println("Please enter column size");
int column = kb.nextInt();
int [][] Array = new int [row][column];
System.out.println();
for ( int r = 0; r < Array.length; r++)
{
for (int c = 0; c < Array[r].length ; c++)
{
Array [r][c] = (int) (Math.random()*99+1);
System.out.print(Array[r][c]+ " ");
}
System.out.println();
System.out.println();
}
System.out.println("Please input a number to look for or enter \"-1\" to stop ");
int find = kb.nextInt();
findValue (Array, find);
}
public static int findValue (int [][] Array, int find)
{
if (find !=-1)
{
for ( int x = 0; x < Array.length; x++)
{
for (int y = 0; y < Array[x].length ; y++)
{
if (Array[x][y] == find)
{
System.out.println("The number is located in the "+ (x+1) + " row, and the " + (y+1) + " column");
}
}
}
}
}
}
}
但是,如果用户要求的数字不在数组中,我不知道如何返回“-1”。另外,我不知道如何继续询问“请输入一个数字.. ." 并在用户输入“-1”时停止。
【问题讨论】: