gpt4 book ai didi

java - Java 代码中缓冲区中出现意外值

转载 作者:行者123 更新时间:2023-12-02 14:24:12 25 4
gpt4 key购买 nike

DEITLE 书中的简单程序,读取 5 个整数,程序应打印包含该数量的相邻星号的行,即(如果 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()); }



}
}

编辑:问题已经解决,但程序 - 5 个输入 - 只读取 3 个输入,即读取输入并忽略下一个输入 enter image description here

最佳答案

您正在读取一个字节,它只是第一个可用字符的 ascii 值。 50 在 ascii 中是“2”。您可能想要读取并解析以文本形式输入的数字。

如果您在 String 中使用 readLine() 而不是 read(),则可以使用 Integer.parseInt () 获取真实值。

关于java - Java 代码中缓冲区中出现意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14107106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com