首页 > 解决方案 > Java 扫描程序类 (System.in)

问题描述

当用户使用 System.in 输入文本时,我有以下代码未读取或无限循环。如果我将文本硬编码到 Scanner 变量中,它可以正常工作,所以我不确定此代码的 System.in 部分有什么问题。任何帮助表示赞赏。

import java.util.Scanner; // needed to use the Scanner class 

public class HW2 { 

    static Scanner in = new Scanner(System.in); 


    public static void main(String [] args) { 

        System.out.println("Enter your line here"); 


        int the =0; 
        int and =0; 
        int is = 0; 
        int was =0; 
        int noword =0; 

        while (in.hasNext()){ 
            String word = in.next(); 

            if (word.equals("the")){ 
                the++; 
            } 
            else if( word.equals("and")){ 
                and ++; 
            } 
            else if (word.equals("is")){ 
                is++; 
            } 
            else if (word.equals("was")){ 
                was++; 
            } 
            else noword++; 

        } 

        System.out.println("The number of occurrences of the was"+ the); 
        System.out.println("The number of occurrences of and was"+ and); 
        System.out.println("The number of occurrences of is was"+ is); 
        System.out.println("The number of occurrences of was was"+ was); 


    } 
}

标签: javajava.util.scanner

解决方案


除非您System.in关闭它,否则程序运行时始终可用。它永远不会退出 while 循环。所以你可以添加else if (word.equals("exit")) { break; }. 这样,每当您键入“退出”时,它都会关闭 while 循环并在 while 循环之后执行代码。


推荐阅读