来自DEITLE的书中的简单程序,读取5个整数,程序应该打印包含该数量的相邻星号.ie的行(如果num = 5则输出*****).我在c ++中测试了相同的解决方案并且工作正常.然而,这里缓冲区保持奇怪的值(50?).我认为问题在于使用缓冲区,但我想知道为什么会发生这种情况?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
import java.io.*;
import java.util.Date;
/**
* Program that reads five numbers and print starts equal to each number
*
* @author Hassan
*/
public class JavaApplication1
{
public static void main(String[] args)
{
int num ;
java.io.InputStreamReader ins= new InputStreamReader(System.in);
java.io.BufferedReader bfr = new BufferedReader (ins);
try
{
for(int i=0;i<5;i++)
{
System.out.println("Please Enter a number");
num = bfr.read();
System.out.print(num);
for(int j=0;j<num;j++)
{ System.out.print("* "); }
System.out.println("\n");
}
}
catch(Exception E )
{System.out.println(E.getMessage()); }
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:问题已经解决了,但是5个输入的程序输出 - 仅读取3,即读取输入而忽略下一个输入

你正在读一个字节,它只是第一个可用字符的ascii值.ascii中50是'2'.您可能希望阅读并解析以文本形式输入的数字.
如果您使用readLine()而不是read(),String则可以使用它Integer.parseInt()来获得真正的价值.
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |