gpt4 book ai didi

java - 如何使用/返回 "public static String [] list={};"(来自amplify第3单元第29课的程序)

转载 作者:行者123 更新时间:2023-12-01 18:21:31 25 4
gpt4 key购买 nike

问题:

“一名学生想要一种算法来查找词汇列表中最难拼写的单词。他们通过最长的单词来定义最难拼写的单词。

编写代码来查找存储在名为 list 的字符串数组中的最长单词。如果几个单词具有相同的长度,则应打印列表中长度最长的第一个单词。

例如,如果声明了以下列表:

String list [] = {"high", "every", "nearing", "checking", "food ", "stand", "value", "best", "energy", "add", "grand", "notation", "abducted", "food ", "stand"};

它会打印:

checking

"

我的解决方案:

import java.util.Scanner;

import java.lang.Math;

class Lesson_29_Activity_One {
public static String [] list={};
{
String list [] = {"high", "every", "nearing", "checking", "food ",
"stand", "value", "best", "energy", "add", "grand", "notation",
"abducted", "food ", "stand"};
}
public static void main(String[] args)
{
Scanner console = new Scanner (System.in);
int longestInt= list[0].length();
String longest= list[0];
for (int x=0; x< list.length; x++)
{
if (list[x].length() > longestInt)
{
longestInt = list[x].length();
longest = list[x];
}
}
System.out.println (longest);
}
}

我的解决方案存在问题:

当我运行程序时,我收到java.lang.ArrayIndexOutOfBoundsException: 0。但是,当我将字符串数组放在 public static void main(String[] args) 下时,整个程序将按预期工作。不幸的是,该网站要求我将字符串数组输入“public static String [] list={};”。我尝试删除所有计算并仅从字符串数组中打印一个随机单词。但我得到了相同的结果,java.lang.ArrayIndexOutOfBoundsException: #(# 是我尝试打印的字符串数组中的随机位置)。我是否应该为 public static String [] list={} 提供某种返回?

最佳答案

看这部分:

public static String [] list={};
{
String list [] = {"high", "every", "nearing", "checking", "food ",
"stand", "value", "best", "energy", "add", "grand", "notation",
"abducted", "food ", "stand"};
}

这是两个独立的部分。首先,声明 String[] 变量并将其初始化为空数组。

public static String[] list = {};

接下来,完全独立地,一个声明局部变量的初始化 block :

{
String list [] = {"high", "every", "nearing", "checking", "food ",
"stand", "value", "best", "energy", "add", "grand", "notation",
"abducted", "food ", "stand"};
}

list 变量与之前声明的变量不同。它对于初始化程序来说是本地的。如果您创建了该类的实例,该代码就会被执行,但无论如何它都是毫无意义的 - 它没有任何作用。

你真正想要的是一个语句 - 只是声明和初始化,但带有数据:

public static String[] list= { "high", "every", "nearing", "checking", "food ",
"stand", "value", "best", "energy", "add", "grand", "notation",
"abducted", "food ", "stand"};

(理想情况下,也将该字段设置为privatefinal...)

关于java - 如何使用/返回 "public static String [] list={};"(来自amplify第3单元第29课的程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27627716/

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