简体   繁体   English

Java初学者:忽略While循环

[英]Java Beginner: Ignoring While loop

import java.io.*;
import java.util.*;

public class Hellno {
    public static void main(String[] args) {
        try {
            Scanner s = new Scanner(new File("words.txt"));
            findBiggest(s);
            System.out.println(findBiggest(s));
        } catch (IOException e) {
            System.out.println("Can't find that file");
        }
    }

    public static String findBiggest(Scanner scan) {
        int count0 = 0;
        int count1 = 0;
        String srs = "";

        while (scan.hasNext()) { //how do i make this the longest?
            String nsrs = scan.next();
            count0 = nsrs.length();

            if (count0 > count1) { // if the new length is bigger than what was solidified
                count1 = count0; //new solidification of number
                count0 = 0; // count becomes 0  to start again
                srs = nsrs; // nsrs has been solidified as the new biggest String
            }

            else if (count0 <= count1) { // if the new length is smaller than what was solidified
                count0 = 0; //then we start again with dummyCount = 0;
             }   
        }
        return srs;}}

I am trying to read from a text file, find out what is the longest string and return that string. 我正在尝试从文本文件中读取内容,找出最长的字符串,然后返回该字符串。 However, this coding ignores all of while() and seems to jump to return srs. 但是,此编码将忽略所有while()并似乎跳转以返回srs。 Why?? 为什么??

You are calling findBiggest twice on the same Scanner . 您在同一Scanner上两次调用findBiggest The first call presumably finds the biggest word and returns it, but it's ignored. 大概是第一个调用找到了最大的单词并返回了它,但是它被忽略了。 The second call finds no words, and the while loop has no iterations. 第二个调用找不到单词,而while循环没有迭代。

Just call findBiggest once. 只需调用一次findBiggest

Scanner s = new Scanner(new File("words.txt"));
System.out.println(findBiggest(s));

需要在扫描仪上设置定界符

  Scanner s = new Scanner(input).useDelimiter(System.getProperty("line.separator"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM