gpt4 book ai didi

java - 如何让一维数组接受多个字符串值?

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

对于我的项目,我必须获得一个一维数组来接受 10 个不同的美国州,然后为该数组实现多个操作。我需要使用插入排序算法按字母顺序 A 到 Z 对状态名称进行排序,不区分大小写,并实现二进制搜索算法。

我的问题是,首先我是否需要将每个状态的名称插入到单个数组中以供其引用?我正在创建数组,但我对如何开始创建数组感到困惑。我的出发点正确吗?

 public class ten_states
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);

String firststate, secondstate, thirdstate, fourthstate, fifthstate, sixthstate, seventhstate, eighthstate, ninthstate,tenstate;
String states[]= new String[10];








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

最佳答案

您可以将字符串放入数组中,如下所示:

String states[] = new String[10];
list[0] = "firststate";
list[1] = "secondstate";
list[2] = "thirdstate";

或者你也可以像这样初始化字符串:

String[] states = {"firststate", "secondstate", "thirdstate"};

这是一个更高级的解决方案:
从这里复制粘贴:https://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/

import java.util.*;
public class Details {

public static void main(String args[]){
ArrayList<String> listofcountries = new ArrayList<String>();
listofcountries.add("India");
listofcountries.add("US");
listofcountries.add("China");
listofcountries.add("Denmark");

/*Unsorted List*/
System.out.println("Before Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}

/* Sort statement*/
Collections.sort(listofcountries);

/* Sorted List*/
System.out.println("After Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
}
}

关于java - 如何让一维数组接受多个字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141573/

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