设计Java程序,使得当数组下标越界时提示(如图↓)
1个回答
展开全部
import java.util.Scanner;
/**
* <P>
* have the computer randomly pick a starting spot for the word. <br / >
* then separate the word into letters and put it into the matrix. <br / >
* at least 2 different directions must be used. <br / >
* vertically or horizontally or diagonally or backwards. <br / >
* if more than 2 are used extra credit is earned!! <br / >
* after the words have been placed in the matrix
*/
public class Polly
{
enum DIRECTIONS
{
vertically, horizontally, diagonally, backwards
}
public static void main(String[] args)
{
String[][] matrix = new String[10][10];
int rc = matrix.length;
int cc = matrix[0].length;
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 10; i++)
{
System.out.print("input a word " + (i + 1) + " times: ");
String word = scanner.next();
int r = (int) (Math.random() * rc);
int c = (int) (Math.random() * cc);
while(true)
{
try
{
DIRECTIONS direction = DIRECTIONS.values()[(int) (Math.random() * DIRECTIONS.values().length)];
switch(direction)
{
case vertically:
for(int j = r; j < rc; j++)
{
matrix[j][c] = word.charAt(j - r) + "";
}
break;
case horizontally:
for(int j = c; j < cc; j++)
{
matrix[r][j] = word.charAt(j - c) + "";
}
break;
case diagonally:
for(int j = 0; j < word.length(); j++)
{
matrix[r][c] = word.charAt(j) + "";
r++;
c++;
}
break;
case backwards:
for(int j = c; j >= 0; j--)
{
matrix[r][j] = word.charAt(c - j) + "";
}
break;
}
}
catch(StringIndexOutOfBoundsException | ArrayIndexOutOfBoundsException e)
{
System.err.println("越界");
continue;
}
break;
}
}
scanner.close();
for(int i = 0; i < rc; i++)
{
for(int j = 0; j < cc; j++)
{
if(matrix[i][j] == null)
{
int w = (int) (Math.random() * 26) + 65;
matrix[i][j] = (char) w + "";
}
}
}
System.out.println("the result is: ");
for(int i = 0; i < rc; i++)
{
for(int j = 0; j < cc; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
追问
😂你现编的吗
追答
是的,今天早上写的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询