acm处理输入输出Java

读一个整数: int n = sc.nextInt();
读一个字符串:String s = sc.next();
读一个浮点数:double t = sc.nextDouble();
读一整行: String s = sc.nextLine();
判断是否有下一个输入可以用sc.hasNext()或sc.hasNextInt()或sc.hasNextDouble()或sc.hasNextLine()

1、输入一个int

import java.util.Scanner;

public class cin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 输入单个int
        int i = sc.nextInt();
        System.out.println("读取到的数字是:" + i);
        // 输入多个int
    }
}

2、接收字符串

nextLine 可以接收空格或者 tab 键,其输入以 enter 键结束。
next 不会接收回车符,tab 或者空格键,遇到空格就算结束

public class cin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();//读取的字符串数量
        int index = 0;
        String[] array = new String [i];//存放读取的字符串
        while(index < i) {
            array[index++] = sc.next();
        }
        for (String str : array) {//输出读取的字符串
            System.out.println("输入的字符串:" + str);
        }
    }
}

nextLine:会吞掉 ” 2 ” 后面那个 enter 作为第一个字符串,可以接收空格
2
h e l l o
输入的字符串:
输入的字符串:h e l l o

next :以空格或者enter为结尾
2
h l
输入的字符串:h
输入的字符串:l

3、输入数组

法一:输入字符串,用逗号隔开
注意空格不合法

public class cin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next().toString();
        String[] arr  = str.split(",");
        int[] b = new int[arr.length];
        for(int j = 0; j<b.length;j++) {
            b[j] = Integer.parseInt(arr[j]);
            System.out.print(b[j]+" ");
        }
    }
}

在这里插入图片描述
法二:提前规定个数

public class cin {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] b=new int[3];
        for(int i=0;i<b.length;i++){
            b[i]=in.nextInt();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值