停止询问用户输入的循环

时间:2013-03-14 05:33:59

标签: java

这里的问题是我们希望程序在用户输入“-1”时不要获取数组的最大长度时停止循环/停止询问整数

import java.util.Scanner;
public class DELETE DUPLICATES {
public static void main(String[] args) {
        UserInput();
        getCopies(maxInput);
        removeDuplicates(maxInput);
}
static int[] maxInput= new int[20];
static int[] copies = new int[20];
static int[] duplicate = new int[20];
//get user's input/s    
public static void UserInput() {
  Scanner scan = new Scanner(System.in);
        int integer = 0;
        int i = 0;
  System.out.println("Enter Numbers:  ");
        while(i < maxInput.length)
        {
                integer = scan.nextInt();         
                maxInput[i] = integer;
                        i++; 
                        if (integer == -1) 
                            break;  
        }
                  int j = 0;
        for(int allInteger : maxInput) {
                System.out.print(allInteger+ "  ");
                j++;
        }
}
//to get value/number of copies of the duplicate number/s
public static void getCopies(int[] Array) {
   for(int allCopies : Array) {
    copies[allCopies]++;
}

for(int k = 0; k < copies.length; k++) {
    if(copies[k] > 1) {
        System.out.print("\nValue " + k  + " : " +  copies[k] + " copies are detected");

    }
        }
        }
//remove duplicates
public static void removeDuplicates(int[] Array) {
 for(int removeCopies : Array) {
     duplicate[removeCopies]++;
    }

    for(int a = 0; a < duplicate.length; a++) {
        if(duplicate[a] >= 1) {
            System.out.print("\n"+a);

        }
            }
  }
 }

实施例: 如果我们输入: 1 2 3 3 4 五 -1

 The result of our program is : 1  2  3  3  4  5  -1  0  0  0  0  0  0  0  0  0  0  0  0  0
 We want the result to be like: 1  2  3  3  4  5

我们需要你的帮助。练习我们的编程1主题希望我们能在这里得到一些帮助

3 个答案:

答案 0 :(得分:1)

您可以执行以下更改以打印所需的值:

for(int allInteger : maxInput)  
{
    if(allInteger == -1)
        break;

    System.out.print(allInteger+ "  ");
    j++;
}

但是,更好的改变是重新考虑您的数据结构的设计和使用。

答案 1 :(得分:0)

maxInput数组的指定大小为20,因此它将为no。元素并打印默认值int。

您可以使用List代替并检查最大输入和退出循环的大小

答案 2 :(得分:0)

如果你不需要来使用数组,那么Collection有很多优点。我们使用List

static int maxInputCount = 20;
static ArrayList<Integer> input= new ArrayList<>();

...

    for (int i = 0; i < maxInputCount; i++)
    {
            integer = scan.nextInt();
            if (integer == -1)
                break;
            input.add(integer);
    }
    for(int integer : input) {
            System.out.print(integer+ "  ");
    }
相关问题