java - 扫描仪不工作

标签 java string terminal java.util.scanner

我有这个代码:

byte[] nombre = new byte[20];
                System.out.print("Cuenta a modificar: ");
                cuenta = s.nextInt();
                boolean existe = estaRepetido(cuenta);
                if (existe == false){
                    System.out.println("La cuenta no existe");
                }
                else {
                    String nomCliente;
                    System.out.print("Nombre: ");
                    nomCliente = s.nextLine();
                    System.out.print("Cantidad: ");
                    double cantidad = Double.parseDouble(s.nextLine());
                    for( int i = 0; i < 20 && i < nomCliente.getBytes().length; i++ ){
                        nombre[i] = nomCliente.getBytes()[i];
                    }
                    String nomModificar = new String (nombre);
                    modificar(cuenta, nomModificar, cantidad);
                }

但是当在终端上运行时,它会以某种方式在海外运行 nomCliente = s.nextLine();以这样的方式结尾:

Cuenta a modificar: 0
Nombre: Cantidad: 0

有什么想法吗?这只是一个非常大的方法的一部分,但这是唯一造成麻烦的扫描仪。

最佳答案

nextInt() 方法留下 \n(结束行)符号,并立即被 nextLine() 拾取,跳过下一个输入。您想要做的是对所有内容使用 nextLine() ,并稍后解析它:

String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int

这是迄今为止避免问题的最简单方法——不要混合您的“下一个”方法。仅使用 nextLine(),然后解析 int 或单独的单词。

关于java - 扫描仪不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15626068/

相关文章:

java - Android firebase 最喜欢的按钮更改

java - frontend-maven-plugin 执行两次

c - 需要帮助在 C 中操作字符串/指针

java - 哪个String方法: "contains" or "indexOf > -1"?

python - 为什么我的 Python 脚本在终端中暂停?

android - 无法从 Mac OS X 中的命令行启动 Android 模拟器

java - Kotlin ViewPager2 : Class 'ScreenSlidePagerAdapter' is not abstract and does not implement base class member

java - 使用 setOnItemClickListener 接口(interface)时无法从 ListView 接收值

java - 如何匹配另一个文本中间的模式?

xcode - 如何从 iOS 设备的终端运行 Xcode 项目?