java 读取 nextline,读取字符串next()和nextLine()Java

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

{

String input=keyboard.nextLine();

String array[]=input.split(" ");

for (int counter=0;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++;

}

}

}

}

Thanks :)

解决方案

Put keyboard.nextLine() after this line:

int answer=keyboard.nextInt();

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值