Java之控制台输入值

常见输入方法

  1. Scanner:
    整型:nextInt();
    浮点:nextFloat(),nextDouble();
    字符串:nextLine();next();
    字符:next.charAt(0);
import java.util.Scanner;

/**
 * 
 * @author Cendeal
 * @since  20170301
 * 
 */
public class OperationChar {

    public static void main(String[] args){
        Scanner cin=new Scanner(System.in);
        System.out.print("请输入整型a=");
        int a=cin.nextInt();
        //输入一个字符
        System.out.print("请输入字符ch=");
        char ch=cin.next().charAt(0);
        System.out.print("请输入浮点型b=");
        int b=cin.nextDouble();
        System.out.println(a);
        System.out.println(ch);
        System.out.println(b);
        cin.close();//防止leak
        }

}

输入:

a=5
c=+
b=6.6

输出:

5
+
6.6

2.System.in.read():
返回的是整型。

import java.io.IOException;
import java.util.Scanner;

/**
 * 
 * @author Cendeal
 * @since  20170301
 * 
 */
public class OperationChar {

    public static void main(String[] args) throws IOException {
        Scanner cin=new Scanner(System.in);
        System.out.print("请输入:");

        System.out.println("你输入的是"+System.in.read());

        }

}

输入

abcde f g h

输出

97

技巧:可以将值转换为char:如(char)System.in.read()

3.BufferedReader:
通过缓冲区的方式来获取


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
    //jdk1.4之前的方法,从控制台接收一个字符串,然后将其打印出来。我们需要用到BufferedReader类和InputStreamReader类
       try{     
           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
           String str = null;
        System.out.println("Enter your value:");
        str = bufferedReader.readLine();
        System.out.println("your value is :"+str);
       }
       catch(IOException e){

       }

输入

> 12345678910abc


输出

> 12345678910abc
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cendeal

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值