0

我的代码工作正常。但是,当我从姓名或年龄输入中输入 -1 时,输出似乎不正确。如何删除空值和“-1”并显示现有数组?

import java.util.Scanner;

public class quizLoop {
    private static Scanner key = new Scanner(System.in);
    private static Scanner keyNum = new Scanner(System.in);

    public final static int arrayLoop = 5;
    public static String[] nameList = new String[arrayLoop];
    public static int[] age = new int[arrayLoop];

    public static void main(String[] args) {
        System.out.println("NAME & AGE SYSTEM\n-----------------\n");
        for(int i=0; i<arrayLoop; i++) {
            System.out.print("Name: ");
            nameList[i] = key.nextLine();
            if(nameList[i].equals("-1"))
                break;

            System.out.print("Age: ");
            age[i] = keyNum.nextInt();
            if(age[i] < 0)
                break;
        }

        System.out.println("----------");
        for(int i=0; i<nameList.length; i++) {
            System.out.println(nameList[i] + " " + age[i]);
        }
    }
}
4

2 回答 2

0

目前,当您输入 时-1,循环退出。也就是说,只要您输入-1,循环就不会再次运行。这是因为您使用了break语句。

如果您想让-1用户重新开始当前条目,您需要做两件事:

if (nameList[i].equals("-1")) {
    // Take the loop variable down one.
    i--;
    // Instead of break, continue to the next iteration.
    continue;
}

如果您想保持循环不变,但只打印null值,请修改您的打印代码:

for(int i=0; i<nameList.length; i++) {
    if (nameList[i] == null || nameList[i].equals("-1") || age[i] < 0) {
        // Invalid; go to the next one.
        continue;
    } else { // (not strictly necessary)
        System.out.println(nameList[i] + " " + age[i]);
    }
}
于 2013-05-03T02:44:09.473 回答
0

尝试使用 List 而不是 Array,如下所示:

import java.util.Scanner;

public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);

public final static int arrayLoop = 5;
public static List<String> nameList = new ArrayList<String>();
public static List<Integer> ages = new ArrayList<Integer>();

public static void main(String[] args) {
    System.out.println("NAME & AGE SYSTEM\n-----------------\n");

    while (true){
        System.out.print("Name: ");
        String name = key.nextLine();
        if(name.equals("-1"))
            break;

        System.out.print("Age: ");
        Integer age = keyNum.nextInt();
        if(age < 0)
            break;
        nameList.add(name);
        ages.add(age);
    }

    System.out.println("----------");
    for(int i=0; i<nameList.length; i++) {
        System.out.println(nameList[i] + " " + age[i]);
    }
}
}
于 2013-05-03T02:53:40.583 回答