笔试中头疼的输入测试案例写法,一定要了解几种java的输入
首先,Scanner()方法要导包,java.util.Scanner;
常用输入:
Scanner sca = new Scanner(System.in)
//输入整型
int a = sca.nextInt();
//输入字符串
String s = sca.nextLine() //读出完整的一行,输入以回车结束
String b = new sca.next() //空格会影响输出,读到有效字符后才可以结束;不可以得到带有空格的字符串;
//自定一个二维数组
int row = sca.nextInt();
int column = sca.nextInt();
int[][] arr = new int[row][column]; //定义整型二维数组
char[][] arr1 = new char[row][column]; //字符数组
for(int i = 0; i < row;i ++){
String s1 = sca.next();
for(int j = 0;j < column; j ++){
arr[i][j] = sca.nextInt();
arr1[i][j] = s.cahrAt(j);
}
}
根据一些题目要求进行输入,比如:以二维数组为输入,第一行输入二维数组的行列数,以逗号分隔;第二行的元素是二维数组中的值
import java.util.Scanner;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(",");//输入一行字符串以逗号分隔
//将字符串转换成整型
int m = Integer.parseInt(s[0]);
int n = Integer.parseInt(s[1]);
int[][] arr = new int[m][n];
又或者:
输入要求:第一行输入字符串的长度,第行输入数组数值,以逗号分隔
public static void main(String[] args){
Scanner sca = new Scanner(System.in);
int n = sca.nextInt();
if(n < 0 ){
return;
}
//输入换行符
sca.nextLine();
int[] arr = new int[n];
String[] str = sc.nextLine().split(",");
for(int i = 0;i < n;i ++){
arr[i] = Integer.parseInt(str[i]);
}
}