如何在 Java 中使用 readline() 方法? [英] How to use readline() method in Java?

查看:19
本文介绍了如何在 Java 中使用 readline() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 初学者,我正在阅读通过键盘上的 readLine() 方法为变量赋值的主题.书中给出的程序如下:

I am beginner in Java, and I was reading the topic of giving values to variables through the readLine() method from the keyboard. The program for that is given in the book is as follows:

import java.io.DataInputStream
class Reading
{
    public static void main(String args[])
    {
        DataInputStream in = new DataInputStream(System.in);
        int intnumber=0;
        float floatnumber=0.0f;
        try {
            system.out.println("enter an integer: ");
            intnumber = Integer.parseInt(in.readline());

            system.out.println("enter a float number: ");
            floatnumber = Float.valueOf(in.readline()).floatvalue();
        }

        // Rest of code

我想问以下问题:

  1. 下面的语句做了什么?

  1. What is done in the following statement?

DataInputStream in = new DataInputStream(System.in);

如果inDataInputStream 的对象,那么什么是新的,上面语句右边的语句是做什么的?

If in is an object of DataInputStream then what is new and what do the statement on the right-hand side of above statement do?

为什么使用不同的方法将整数值放入 intnumber 和将浮点值放入 floatnumber 中?

Why have different methods been used for putting the integer value into intnumber and float value into floatnumber?

推荐答案

我建议你使用 Scanner 而不是 DataInputStream.Scanner 专门为此目的而设计,并在 Java 5 中引入.请参阅以下链接以了解如何使用 Scanner.

I advise you to go with Scanner instead of DataInputStream. Scanner is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner.

示例

Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());

这篇关于如何在 Java 中使用 readline() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆