gpt4 book ai didi

java - 为什么我得到 "null"作为输出字符串? java

转载 作者:行者123 更新时间:2023-12-01 18:15:59 24 4
gpt4 key购买 nike

我想要做的是从文件中读取(在本例中该文件包含超过 100,000 行)并将值存储在数组中,然后打印出前 10 行。然而,当我运行该程序时,我得到第一行,然后是 9 行“null”,这显然不是我想要的!这是代码,如有任何提示,我们将不胜感激。

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

public class DawsonZachA5Q2{
public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter a size for the number of letters for words: ");
int size = keyboard.nextInt();//prompts user for input
String[] array = new String[27000];

try {
File file = new File("big-word-list.txt");
Scanner scanner = new Scanner(file);


// Start a line count and declare a string to hold our current line.
int linecount=0;

// Tells user what we're doing
System.out.println("Searching for words with " + size + " letters in file...");
int wordCount=0;

while (scanner.hasNext()){
int i = 0;
String word = scanner.next();

if(size == word.length()){
wordCount++;
array[i]=word;
i++;
//add word to array
// increase the count and find the place of the word
}
}

linecount++;






System.out.println(wordCount);

System.out.println(wordCount+" words were found that have "+size+ " letters.");//final output


for(int o = 0; o<10; o++){
System.out.println(array[o]);
}


scanner.close();
}// our catch just in case of error
catch (IOException e) {
System.out.println("Sorry! File not found!");
}



} // main


} // class

最佳答案

while 循环之外定义 int i = 0;。每次循环运行时它都会设置为零。这就是问题所在。

关于java - 为什么我得到 "null"作为输出字符串? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29483450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com