题目描述
编写一个Java 程序,从键盘输入一个规则二维数组数组,输出数组中最大整数值和最小整数值。
输入
首先输入非负整数 m, n,分别代表代表数组的行数和列数,然后再按行优先的规则,依次输入m*n个整数
输出
输入不合法(输入值m,n不为非负整数,或者接下来的m*n值包含非整数),则输出“error input”
输入合法,则不换行输出最大值与最小值
注意:
本题要求对所有的输入的整数进行合法性检查,有以下两种处理方法。
方法1: 每一次调用nextInt()前都要进行进行hasNextInt()的预读。
方法2.:也可以用java异常处理机制统一处理,参考代码为:
public static void main(String[]args)
{
try
{
//可以把原 main方法中 的所有代码放这里。
//这里可以直接用Scanner类的nextInt读取键盘输入,不需要做预读处理。
//一旦try子句中的语句nextInt() 用户输入非整数,则程序则抛出InputMismatchExcception 异常出去,在catch中捕获后,输出error input
}
catch(InputMismatchException e)
{
System.out.println("error input");
}
}
样例输入
3 4 32 65 98 14 58 67 928 99 22 -3 44 6
样例输出
928 -3
方法一:hasNextInt函数判断输入合法性
import java.util.*;
public class Main {
public static void main(String[]args){
int m,n;
Scanner reader = new Scanner(System.in);
//判断整形
if(reader.hasNextInt()){
m = reader.nextInt();
n = reader.nextInt();
//判断正负
if(m>=0 && n>=0){
int [][]a = new int [m][n];
//输入数组内容
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(reader.hasNextInt()){
a[i][j] = reader.nextInt();
}
else{
System.out.print("error input");
return;
}
}
}
//判断最大最小值
int max = a[0][0];
int min = a[0][0];
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(a[i][j]>max){
max = a[i][j];
}
if(a[i][j]<min){
min = a[i][j];
}
}
}
System.out.println(max+" "+min);
}
else{
System.out.print("error input");
}
}
else{
System.out.print("error input");
}
}
}
方法二:java异常处理机制(try{}catch{})
import java.util.*;
public class Main {
public static void main(String[]args){
try{
int m,n;
Scanner reader = new Scanner(System.in);
//判断整形
m = reader.nextInt();
n = reader.nextInt();
//判断m、n是否为整数
if(m%1==0 && n%1==0){
//判断正负
if(m>=0 && n>=0){
int [][]a = new int [m][n];
//输入数组内容
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
a[i][j] = reader.nextInt();
}
}
//判断最大最小值
int max = a[0][0];
int min = a[0][0];
for(int i=0; i<a.length; i++){
for(int j=0; j<a[i].length; j++){
if(a[i][j]>max){
max = a[i][j];
}
if(a[i][j]<min){
min = a[i][j];
}
}
}
System.out.println(max+" "+min);
}
else{
System.out.print("error input");
}
}
else{
System.out.print("error input");
}
}
catch(InputMismatchException e){
System.out.println("error input");
}
}
}
注意:
遍历数组的时候,for循环内 i 和 j 要从0开始,不然就会忽略了首行或首列内容。