Java 阻止循环询问用户输入
这里的问题是,当用户输入'-1'时,我们希望程序停止循环/停止询问整数,这样就不必获取数组的最大长度Java 阻止循环询问用户输入,java,Java,这里的问题是,当用户输入'-1'时,我们希望程序停止循环/停止询问整数,这样就不必获取数组的最大长度 import java.util.Scanner; public class DELETE DUPLICATES { public static void main(String[] args) { UserInput(); getCopies(maxInput); removeDuplicates(maxInput); } static int[
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主题希望我们能在这里得到一些帮助您可以做以下更改来打印所需的值:
for(int allInteger : maxInput)
{
if(allInteger == -1)
break;
System.out.print(allInteger+ " ");
j++;
}
但是,更好的改变是重新考虑数据结构的设计和使用。maxInput数组的指定大小为20,因此它将具有该数量的元素并打印默认值int 您可以改为使用List,并检查max input和exit循环的大小如果不需要使用数组,那么
集合
有很多优点。让我们使用一个列表
:
static int maxInputCount = 20;
static ArrayList<Integer> input= new ArrayList<>();
static int maxInputCount=20;
静态ArrayList输入=新建ArrayList();
for(int i=0;i
阵列具有固定大小。如果您想要一个可以改变大小的列表,请尝试列表。第一课:Java不是JavaScript。公共类删除重复项
这不会编译!!另外,按照Java约定上课的第一个字母是大写的不全谢谢你的帮助:)我们已经拿到了:D
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+ " ");
}