本文介绍了Java-Convert String在使用BufferedReader时转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用BufferedReader时如何将String转换为int?我记得
,如下所示:

How do you convert a String to int when using BufferedReader?as far as i remember,its something like below:

System.out.println("input a number");

int n=Integer.parseInt(br.readLine(System.in));

但出于某种原因,它无效。

but for some reason,its not working.

错误消息显示:

找不到合适的方法 readLine(java.io.InputStream)

它还说 br.readLine 不适用

推荐答案

需要在 BufferedReader 的构造函数中指定 InputStreamReader InputStreamReader 将字节流转换为字符流。正如其他人所提到的那样,可以认识到可以从这段代码抛出的异常,例如IOException和NumberFormatException。

An InputStreamReader needs to be specified in the constructor for the BufferedReader. The InputStreamReader turns the byte streams to character streams. As others have mentioned be cognizant of the exceptions that can be thrown from this piece of code such as an IOException and a NumberFormatException.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input a number");
int n = Integer.parseInt(br.readLine());

这篇关于Java-Convert String在使用BufferedReader时转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:40