【问题标题】:how to parse or read Int from BufferedReader?如何从 BufferedReader 解析或读取 Int?
【发布时间】:2021-12-06 23:14:43
【问题描述】:

我正在尝试使用 BufferedReader 读取 int。我知道我的类型 (string, int) 不匹配,但我不确定我需要对代码进行哪些更改才能使其正常工作。

我知道如何将它用于字符串读取和打印,但不知道如何用于 int 并使用一些运算符

import java.io.*;
public class tmetodoI {

    public static void main(String[] args) {
        
    BufferedReader dataIn = new BufferedReader 
            (new InputStreamReader(System.in));
    
    String num = "";    
        
        System.out.print("Ingrese un valor entero para determinar si es multiplo de 6");
        
        try {
        num = dataIn.readLine();        
        } catch(IOException e) {
            System.out.print("Error!");
        }
        
        if (num%6>0)
        
    }
}

【问题讨论】:

  • 为什么不使用Scanner

标签: java string integer


【解决方案1】:

BufferedReader 类不提供任何直接方法来从用户那里读取整数,您需要依赖 readLine() 方法来读取整数。即最初您需要以字符串格式读取整数。

Integer 类的parseInt() 方法接受一个String 值,将其解析为有符号十进制整数,然后返回。

 BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
 int value = Integer.parseInt(reader.readLine());

您也可以使用Scanner class,它提供了一种预定义的整数输入方法

Scanner myInput = new Scanner( System.in );
int value=myInput.nextInt();      

【讨论】:

    【解决方案2】:

    您将字符串转换为 int 使用 Integer.parseInt(num);

    要转换成其他原始数据类型看看

    parseInt()

    parseFloat()

    parseLong()

    parseDouble()

    【讨论】:

      【解决方案3】:

      您可以使用Integer.parseInt(String)String 转换为int,使用以下代码:

      public static void main(String[] args) {
      
          BufferedReader dataIn = new BufferedReader
                  (new InputStreamReader(System.in));
      
          String num = "";
      
          System.out.print("Ingrese un valor entero para determinar si es multiplo de 6");
      
          try {
              num = dataIn.readLine();
      
              if (Integer.parseInt(num)%6 > 0) {
                  System.out.println("inside condition");
              } else {
                  System.out.println("out of the condition");
              }
          } catch(IOException e) {
              System.out.print("Error!");
          }
      
      }
      

      【讨论】:

      • 捕获异常然后像没有发生一样继续处理是不正确或不可接受的。不要写这样的代码。
      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 2019-01-01
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多