gpt4 book ai didi

java - System.in.read() 不会阻止读取更多输入字符?

转载 作者:行者123 更新时间:2023-12-01 17:30:39 25 4
gpt4 key购买 nike


谁能解释一下为什么下面的代码表现得很奇怪:

public class UserInputTest {
public static void main(String[] args) throws IOException {
int n=3;
char[] arr = new char[n];
for (int i=0; i<n; i++) {
System.out.println(i+1 + " character :");
arr[i] = ((char)System.in.read());
}

System.out.println("You Entered : ");
for (int i=0; i<n; i++) {
System.out.println(arr[i]);
}
}
}

输出:
1 个字符:

2 个字符:
3 个字符:
您输入:

我预计它会阻止用户输入值三次。有意见吗?



谢谢,
莫希特

最佳答案

从控制台读取字符存在上述输入问题。因此,尝试将其读取为字符串:

public static void main(String args[]){


int n=3;
char[] arr = new char[n];
Scanner in = new Scanner(System.in);
for (int i=0; i<n; i++) {
System.out.println(i+1 + " character :");
String s1 = in.nextLine();
arr[i] = s1.charAt(0);
}

System.out.println("You Entered : ");
for (int i=0; i<n; i++) {
System.out.println(arr[i]);
}
}

关于java - System.in.read() 不会阻止读取更多输入字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11279490/

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