试图纠正简单的数组程序

时间:2016-07-26 03:03:33

标签: java arrays output

我在开始新的编程课之前尝试使用Java进行练习。为此,我决定重新制作我从早期课程中制作的旧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重新编译:未选中以获取详细信息。

2 个答案:

答案 0 :(得分:1)

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

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

其次,您需要sort并再次致电convertToString以打印结果。首选具有小写名称的变量。您可以使用内置函数消除循环。在将userInput添加到-1之前,请检查List是否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); } 。像,

Comparator

更新

根据您的编辑,您使用的是Java 7(不是Java 8+)。在这种情况下,您的代码(很高兴听到它正在工作),可以&#34;纠正&#34;使用类型 Comparator<Integer> cmp = Collections.<Integer> reverseOrder(); 。像,

Integer

这将以反向顺序为您提供基于Comparator的{​​{1}}。但是,也可以创建自定义 Comparator。如,

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具体类型的ArrayList界面。

答案 1 :(得分:1)

由于您已经在使用java.util包的数据结构,因此我可以建议一种简单的方法来排序ArrayList中的元素。如果numbersArrayList持有所有要处理的数字,请执行以下操作:

  • 显示ArrayList numbers中的数字,因为它们是

  • 制作TreeSet numbersTreeSet按升序自动对其元素进行排序注意:TreeSet仅包含唯一元素。因此,如果列表中的元素重复,它们将被删除。每个元素的只有一个副本将存储在Set中。

  • 重新初始化numbers,作为由numbers构成的TreeSet。这是因为TreeSet只能以一个顺序显示。现在,显示numbers的元素从头到尾按升序排列,从最后一个到第一个按降序排列。

  • 最后,将numbers的第一个和最后一个元素分别显示为最小和最大的数字。

这是一个代码。

import java.util.*;
class MyClass{
    public static void main(String[] args){
        ArrayList<Integer> numbers <--- holds all the numbers 
        System.out.println("The numbers are:");
        for(int i=0; i<numbers.size();i++)
        System.out.print(numbers.get(i).intValue()+" ");

        TreeSet<Integer> ts = new TreeSet<Integer>(numbers);
        numbers = new ArrayList<Integer>(ts);
        System.out.println("\nThe numbers in ascending order are:");
        for(int i=0;i<numbers.size();i++)
        System.out.print(numbers.get(i).intValue()+" ");

        System.out.println("\nThe numbers in descending order are:");
        for(int i=numbers.size()-1;i>=0;i--)
        System.out.print(numbers.get(i).intValue()+" ");

        System.out.println("\nThe smallest number is "+numbers.get(0).intValue());

        System.out.println("The largest number is "+numbers.get(numbers.size()-1).intValue());
    }
}

我使用包含元素1 2 5 6 7的ArrayList测试了它,这里是输出

The numbers are:
7 5 6 1 2 
The numbers in ascending order are:
1 2 5 6 7 
The numbers in descending order are:
7 6 5 2 1 
The smallest number is 1
The largest number is 7

我希望这会有所帮助。