如何使用 Scanner 方法“hasNext"退出 java 中的 while 循环作为条件? [英] How to get out of while loop in java with Scanner method "hasNext" as condition?

查看:37
本文介绍了如何使用 Scanner 方法“hasNext"退出 java 中的 while 循环作为条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 编程的初学者,遇到了一个奇怪的问题.下面是我的代码,它要求用户输入并打印出用户一次输入一个单词的内容.

I am a beginner at java programming and has run into a strange issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.

问题是程序永远不会结束,根据我有限的理解,它似乎卡在了 while 循环中.有人可以帮我一点吗?提前致谢.

The problem is the program never ends, and from my limited understanding, it seem to have stuck inside the while loop. Could anyone help me a little? Thanks in advance.

import java.util.Scanner;

public class Test{
   public static void main(String args[]){
      System.out.print("Enter your sentence: ");
      Scanner sc = new Scanner (System.in);

      while (sc.hasNext() == true ) {
        String s1 = sc.next();
        System.out.println(s1);
      }

      System.out.println("The loop has been ended"); // This somehow never get printed.
   }
}

推荐答案

你不断地得到一个新的字符串,如果它不为空则继续循环.只需在循环中为退出字符串插入一个控件即可.

You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.

while(!s1.equals("exit") && sc.hasNext()) {
    // operate
}

如果你想在循环内声明字符串而不在循环体中执行如果字符串是exit"的操作:

If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":

while(sc.hasNext()) {
    String s1 = sc.next();
    if(s1.equals("exit")) {
        break;
    }
    //operate
}

这篇关于如何使用 Scanner 方法“hasNext"退出 java 中的 while 循环作为条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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