退出java中的while循环有条件吗

退出java中的while循环有条件吗

本文介绍了如何使用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(sc.hasNext() && !s1.equals("exit")) {
    // 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循环有条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:15