gpt4 book ai didi

java - 尝试纠正简单的数组程序

转载 作者:行者123 更新时间:2023-12-02 03:27:46 25 4
gpt4 key购买 nike

在开始新的编程类(class)之前,我正在尝试进行一些 Java 练习。为此,我决定重新制作我在早期类(class)中制作的旧 Perl 程序。原始 Perl 文件将用户输入的数字输入到一个数组中,并以四种方式输出该数组:输入的数字、升序、降序以及仅最大和最小的数字。

我查看了这里和其他地方的在线示例来排除故障,但在程序编译时,输出是错误的。照原样,该数组被输出几十次,仅输出输入的数字。我认为我的四个循环设置错误,但我仍在学习 Java,所以我可能错过了一些东西。这是现在的 Java 代码:

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayOutPut {

static Scanner input = new Scanner(System.in);

static String convertToString(ArrayList<Integer> numbers) {

StringBuilder builder = new StringBuilder();
for (int i : numbers) {
builder.append(numbers);
builder.append(",");
}
builder.setLength(builder.length() - 1);
return builder.toString();

}

public static void main(String args[]) {

ArrayList<Integer> numbers = new ArrayList<Integer>();

int userInput;
int Largest = 0, Smallest = 0;

System.out.print(
"This program takes a set of integers from the user, and then outputs the results to the screen in four ways:\n");
System.out.print(
"the order they were entered seperated by a comma and a space, in ascending order, in descending order, and as Largest:Smallest.\n\n");
// explain to the user what the program does, needs, etc.
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
while (userInput != -1) {
System.out.print("Please enter a number or -1 to end: ");
numbers.add(userInput);
userInput = input.nextInt();
}

// Prints the array contents as entered
String sort = convertToString(numbers);
System.out.println(sort);
// prints numbers ascending
for (int i = 0; i < numbers.size(); i++) {
System.out.println(sort);
}
// prints numbers descending, largest first
for (int i = numbers.size() - 1; i >= 0; i--) {
System.out.println(sort);
}
for (int i = 0; i < numbers.size(); i++) {
int number = numbers.get(i);
if (i < Smallest) {
Smallest = i;
}
if (i > Largest) {
Largest = i;
}
System.out.println(Largest + Smallest);
}
}
}

作为其他引用,这里是原始 Perl 程序:

#!/usr/bin/perl    
use Modern::Perl;
my (@numbers, $userInput);# declare the array and more than one variable at a time
print("\nThis program takes a set of integers from the user, and
\nthen outputs the results to the screen in four ways:
\nthe ordered they were entered seperated by a comma and a space,
\nin ascending order, in descending order, and as Largest:Smallest.\n\n"); # explain to the user what is does, needs, etc
print "Please enter a number or -1 to end: ";
chomp ($userInput = <>); #loop is primed
if ($userInput == -1) {
say "\nThere's no numbers to process.\n";
}
else{
while($userInput != -1) {
push (@numbers, $userInput);
#Push the variable $userInput into @numbers.
print "Please enter a number or -1 to end: ";
chomp ($userInput = <>);
}
}
#Don't declare the @numbers array again, otherwise that'll clear out the entered numbers.
$" = ", ";
print "@numbers\n";
my @upsorted = sort {$a <=> $b} @numbers;
#prints numbers ascending, smallest first.
#Don't use $a, $b, or any number as a variable because they're reserved.
$" = ", ";
print "@upsorted\n";
my @downsorted = sort {$b <=> $a} @numbers;
#prints numbers descending, largest first
$" = ", ";
print "@downsorted\n";
print "$downsorted[0]:$upsorted[0]\n";
#must be set off with a blank line above and below
##End of program

好的,作为一个快速更新,在tutorialspoint.com 上查找比较器后,我终于让程序运行了。这是代码现在的位置:

import java.util.*;

public class ArrayOutPut {

static String convertToString(ArrayList<Integer> numbers) {
StringBuilder builder = new StringBuilder();
for (int i : numbers){
builder.append(i);
builder.append(",");
}
builder.setLength(builder.length() - 1);
return builder.toString();
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
int userInput, largest = Integer.MIN_VALUE, smallest = Integer.MAX_VALUE;

System.out.println("This program takes a set of integers from the user, and then "
+ "outputs the results to the screen in four ways:");
System.out.println("the order they were entered seperated by a comma and a space, "
+ "in ascending order, in descending order, and as Largest:Smallest.");
System.out.println();

System.out.print("This program takes a set of integers from the user, and then outputs the results to the screen in four ways:\n");
System.out.print("the order they were entered seperated by a comma and a space, in ascending order, in descending order, and as Largest:Smallest.\n\n");
//explain to the user what the program does, needs, etc.
do {
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
if (userInput != -1) {
numbers.add(userInput);
largest = Math.max(largest, userInput);
smallest = Math.min(smallest, userInput);
}
} while (userInput != -1);

//Prints the array contents as entered
String sort = convertToString(numbers);
Comparator cmp = Collections.reverseOrder();
System.out.println(sort);
Collections.sort(numbers);
System.out.println(convertToString(numbers));
Collections.sort(numbers, Comparator.reverseOrder());
System.out.println(convertToString(numbers));
System.out.printf("Smallest = %d, Largest = %d%n", smallest, largest);
}
}

我唯一担心的是,当我编译时,我收到一条注释,指出该程序使用未经检查或不安全的操作,并且我应该使用 -Xlint:unchecked 重新编译以了解详细信息。

最佳答案

首先,如果使用 Java 8+,我会在 convertToString1 中使用 StringJoiner

>
static String convertToString(List<Integer> numbers) {
StringJoiner sj = new StringJoiner(",");
numbers.stream().map(String::valueOf).forEach(sj::add);
return sj.toString();
}

其次,您需要排序并再次调用convertToString来打印结果。优先使用小写名称的变量。您可以使用内置函数消除循环。在将 userInput 添加到您的 List 之前,请检查它是否不是 -1。我更喜欢do-while。比如,

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();

int userInput, largest = Integer.MIN_VALUE, smallest = Integer.MAX_VALUE;

System.out.println("This program takes a set of integers from the user, and then "
+ "outputs the results to the screen in four ways:");
System.out.println("the order they were entered seperated by a comma and a space, "
+ "in ascending order, in descending order, and as Largest:Smallest.");
System.out.println();
// explain to the user what the program does, needs, etc.
do {
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
if (userInput != -1) {
numbers.add(userInput);
largest = Math.max(largest, userInput);
smallest = Math.min(smallest, userInput);
}
} while (userInput != -1);

// Prints the array contents as entered
String sort = convertToString(numbers);
System.out.println(sort);
Collections.sort(numbers);
System.out.println(convertToString(numbers));
Collections.sort(numbers, Comparator.reverseOrder());
System.out.println(convertToString(numbers));
System.out.printf("Smallest = %d, Largest = %d%n", smallest, largest);
}

更新

根据您的编辑,您使用的是 Java 7(而不是 Java 8+)。在这种情况下,您的代码(很高兴听到它正在工作)可以使用类型化 Comparator 进行“纠正”。比如,

Comparator<Integer> cmp = Collections.<Integer> reverseOrder();

这将为您提供一个基于IntegerComparator(按相反顺序)。但是,也可以创建自定义比较器。比如,

Comparator<Integer> cmp = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 == null) {
return (o2 == null) ? 0 : -1;
}
return o1.compareTo(o2);
}
};

然后你可以像这样使用它(并反转它)

System.out.println(sort);
Collections.sort(numbers, cmp);
System.out.println(convertToString(numbers));
Collections.sort(numbers, cmp.reversed());
System.out.println(convertToString(numbers));

1并且,请优先选择 List 接口(interface)而不是 ArrayList 具体类型。

关于java - 尝试纠正简单的数组程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38580391/

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