Scanner input accepting Strings skipping every other input inside a while loop. [duplicate]

佐手、 提交于 2019-11-28 14:51:52

The reason is, you're calling input.nextLine() twice:

do {

    set1.add(input.nextLine());

}
while (!"EXIT".equals(input.nextLine()));

A much easier way than do-while is while:

while (!(String in = input.nextLine()).equals("EXIT")) {
    set1.add(in);
}

You ask for input twice

do {

    set1.add(input.nextLine()); // you enter a number

}
while (!"EXIT".equals(input.nextLine())); // what if you enter another number? 
// it'll just loop again, skipping that number

You need to ask for input once and use that either to stop or add it to your set.

You loop is doing exactly what you've told it to...

  • Read a line of text and add it to set1
  • Read a line of text and check to see if it equals "EXIT"
  • Repeat as required...

So, every second request is being used to check for the exit state. Instead, you should assign the text from the input to a variable and use it to do you checks, for example...

do {
    String text = input.nextLine();
    if (!"EXIT".equals(text)) {
        set1.add();
    }
} while (!"EXIT".equals(text));

ps- Yes, I know, you could use break ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!