gpt4 book ai didi

java - 当 "' 设置为分隔符时,为什么我的扫描仪读取的是 "B"B' and\n"而不是 "\n"?

转载 作者:行者123 更新时间:2023-12-01 16:43:42 26 4
gpt4 key购买 nike

我创建了一个简单的程序,通过 TCP 与客户端和服务器进行通信。代码很简单,我已经使用套接字完成了(我没有与此相关的问题,我的意思是您不需要了解套接字来帮助我)在突出显示的代码部分中,我需要要求用户写一个字母,代表服务器将执行的操作,但我不知道为什么当我写时,例如,B + Enter,扫描仪会读取B + Enter(我选择 Enter (\n) 作为分隔符)。我已经使用子字符串解决了它,但我不喜欢那样。谁能告诉我为什么扫描仪读取“B +\n”而不是“B”?提前致谢。在这里你可以看到代码: enter image description here

无论如何,我在这里写下有问题的代码部分:

...
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
System.out.println("Por favor especifique el campo opción (letra): ");
//(here I write B and I press enter)
opcion = sc.next();
//(here the scanner reads both B and \n I have to write the next line to solve the problem)
opcion = opcion.substring(0, 1);//(This is what i want to solve)
...

最佳答案

使用 opcion = sc.nextLine();
这样它将忽略\n 并为您提供所需的字符串。

关于java - 当 "' 设置为分隔符时,为什么我的扫描仪读取的是 "B"B' and\n"而不是 "\n"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61815148/

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