java输入方法

笔试中头疼的输入测试案例写法,一定要了解几种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]);
    }
}

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值