NULL数组 - 如何在while循环中链接它

时间:2015-11-14 05:05:01

标签: java arrays string while-loop

基本上我必须提示用户输入10个字符串值,然后在另一个循环中按升序打印它们,然后在最后一个循环中,按降序打印它们。我的数组带回null,显然是因为我没有提示用户将实际信息输入到数组对象中。我真的很困惑。我知道我需要在我的第一个while循环中以某种方式引用“userStrings []”数组。我一直在研究并不断得到整数循环问题和For循环。这必须是一个循环。我无法弄清楚当用户输入值时如何让userStrings []实际填满。如何在循环中将其链接起来?

public class HomeWork10
{

    public static void main(String[] args)
    {
        String[] userStrings = new String[10];

        int count = 0;
        int count2 = 0;

        while (count < 10)
        {
            System.out.println("Please enter a string value ");

            Scanner input = new Scanner(System.in);
            String userInput = input.next();

            count++;
        }

        while (count2 < 1)
        {
            System.out.println(Arrays.asList(userStrings));
            count2++;
        }      
    }
}

3 个答案:

答案 0 :(得分:1)

您没有将值放在String[]

这样做:

 while (count < 10) {
    System.out.println("Please enter a string value ");

    Scanner input = new Scanner(System.in);
    String userInput = input.next();
    userStrings[count] = userInput;
    count++;
}

另外,在Scanner input = new Scanner(System.in)

之外宣布while() {...}

答案 1 :(得分:1)

请参阅下面的代码段可能会解决您的问题。

package com.suresh;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class HomeWork10 {

public static void main(String[] args) {
    String[] userStrings = new String[10];
    int count = 0;
    System.out.println("\t Reading Array Elements ");
    while (count < 10) {
        System.out.print("\t Please enter a string value : ");
        Scanner input = new Scanner(System.in);
        userStrings[count] = input.next();
        count++;
    }
    System.out.println("\t PRINTING ORIGINAL ARRAY OF ELEMENTS ");
    count = 0;
    while (count < userStrings.length) {
        System.out.println("\t " + userStrings[count]);
        count++;
    }

    Collections.sort(Arrays.asList(userStrings), new StringAscComparator());
    System.out.println("\t ASCENDING ORDER ");
    count = 0;
    while (count < userStrings.length) {
        System.out.println("\t " + userStrings[count]);
        count++;
    }

    System.out.println("\t DESCENDING ORDER ");
    Collections.sort(Arrays.asList(userStrings), new StringDescComparator());

    count = 0;
    while (count < userStrings.length) {
        System.out.println("\t " + userStrings[count]);
        count++;
    }
}

static class StringAscComparator implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
}

static class StringDescComparator implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }
}

}

答案 2 :(得分:0)

您使用'String [] userStrings = new String [10]创建了数组;'在你的while循环中访问它你需要做这样的事情'userStrings [0] = input.next()'这表示数组userStrings中的第一项将被设置为input.next()。我不擅长java,所以我不确定input.next()会做什么。