gpt4 book ai didi

java - 按字母顺序对字符串进行排序

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

嗨,我正在尝试按字母顺序获取这些水果,有人可以帮忙吗,因为当我尝试运行程序时,它关闭并显示 NullPointer Exception java Lang 但它编译没有问题,我认为问题出在 .compareTo 行上不太确定

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Write a description of class rigthOrder here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class rigthOrder
{
public static void main (String args []) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i;

String fruit [] = new String[1000];
List<String> fruitsList = Arrays.asList (fruit);

fruit[0] = "orange";
fruit[1] = "bananna";
fruit[2] = "apple";
fruit[3] = "grape";
fruit[4] = "plum";

// for(i = 0; i < fruit.length; i++)
{
// fruit [i] = fruit [i].toUpperCase();
}
Bubble_sort(fruit);
for(i = 0; i < fruit.length; i++)
{
System.out.println(fruit [i]);
}
}
public static void Bubble_sort(String [] fruit)
{
int i, j, size = fruit.length;
String temp;

for(i = 0; i < size-1; i++)
{
for(j = i + 1; j < size; j++)
{
if (fruit[j].compareTo (fruit[i]) < 0)
{
temp = fruit[i];
fruit[i] = fruit [j];
fruit[j] = temp;
}
}
}
}
}

最佳答案

String fruit[] = new String[1000];

String 数组元素的默认值为null。这就是 Arrays.asList(fruit) 抛出 NPE 的原因。

关于java - 按字母顺序对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16907638/

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