读取字符串next()和nextLine()Java [英] Reading Strings next() and nextLine() Java

查看:299
本文介绍了读取字符串next()和nextLine()Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是当我尝试拆分(.split)每个空格时,我无法读取带有next()的变量输入,然后数组只得到我输入的前两个单词,所以我不得不使用keyboard.nextLine( )和分裂过程的工作方式应该工作,我得到数组中的所有单词但问题是如果我使用nextLine()然后我必须创建另一个键盘对象来读取第一个变量(答案),这是我能在这里工作的唯一方法是代码

The problem is I cant read the variable input with next() cause when I try to split (.split" ") every whitespace then the array just get the first two words I type so I had to use keyboard.nextLine() and the splitting process works the way it should work and I get all the words in the array but the problem is that If I use nextLine() then I have to create another keyboard object to read the first variable (answer) and that is the only way I can make it work here is the code

    Scanner keyboard=new Scanner(System.in);
    Scanner keyboard2=new Scanner(System.in);//just to make answer word

    int answer=keyboard.nextInt();//if I don't use the keyboard2 here then the program will not work as it should work, but if I use next() instead of nextLine down there this will not be a problem but then the splitting part is a problem(this variable counts number of lines the program will have).

    int current=1;
    int left=0,right=0,forward=0,back=0;

    for(int count=0;count<answer;count++,current++)
    {
        String input=keyboard.nextLine();
        String array[]=input.split(" ");
        for (int counter=0;counter<array.length;counter++)
        {
            if (array[counter].equalsIgnoreCase("left"))
            {
                left++;
            }
            else if (array[counter].equalsIgnoreCase("right"))
            {     
                right++;
            }
            else if (array[counter].equalsIgnoreCase("forward"))
            {
                forward++;   
            }
            else if (array[counter].equalsIgnoreCase("back"))
            {     
                back++;
            }
        }

   }
}

谢谢:)

推荐答案

keyboard.nextLine()在这一行之后:

int answer=keyboard.nextInt();

当您使用 nextLine()时,这是一个常见问题/ code> nextInt() 扫描程序类的方法之后的方法。

This is a common problem that usually happens when you use nextLine() method after nextInt() method of Scanner class.

实际发生的情况是,当用户在 int answer = keyboard.nextInt(); 中输入一个整数时,扫描仪将仅采用数字和保留换行符 \ n 。所以你需要通过调用 keyboard.nextLine(); 来放弃那个新行字符,然后你可以调用 String input = keyboard.nextLine(); 没有任何问题。

What actually happens is that when the user enters an integer at int answer = keyboard.nextInt();, the scanner will take the digits only and leave the new-line character \n. So you need to do a trick by calling keyboard.nextLine(); just to discard that new-line character and then you can call String input = keyboard.nextLine(); without any problem.

这篇关于读取字符串next()和nextLine()Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆