[英]Replacing an Element
我正在編寫顯示數組簡單操作的代碼。 在我創建的數組中重新插入已刪除的元素時,我似乎無法使其工作。 我的目標是將另一個元素放入另一個已刪除的元素中(當我刪除一個元素時,它變為 0)。 我的插入案例只是告訴重復輸入,它不允許我在某個位置的已刪除元素中恢復。
case 2:
{
if (limit1 < 5 || limit1 > 20){
System.out.println("Error: Invalid Array Limit");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
else{
System.out.println("Enter the " + array.length + " numbers now.
Or enter -1 to exit");
int i = 0;
while(i < array.length){
array[i] = in.nextInt();
boolean dups = false;
if(array[i] != -1){
for(int k = 0; k < i; k++)
if(array[k] == array[i])
{
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if(!dups){
i++;}
}
else{
array[i] = 0;
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
System.out.println("You have entered the "+ limit1 + " numbers");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
另一個問題是,如果我輸入一個哨兵值(-1),它只會使當前輸入位置為 0。我只想退出案例而不是在該位置放置 0
我發現您的代碼存在一些問題。 使用沒有任何break
語句的switch
語句不是一個好習慣。 您可以輕松重構您的方法以使用如下所示的 while 循環:
public void e() {
do {
m();
choice1 = in.nextInt();
cls();
if (choice1 > 0) {
processChoice(); // contains switch block for processing input
}
} while (choice1 > 0); // Loop will terminate when user presses 0
}
每當用戶按下0
時,這也應該退出您的程序。
我在您的 Insertion into array 塊中看到了一個問題。 您似乎正在將從輸入接收到的值直接分配給array[i]
。 在將其分配給array[i]
后檢查它是否是重復值有什么意義。 我認為你應該做這樣的事情:
while (i < array.length) {
int currentInput = in.nextInt();
boolean dups = false;
if (array[i] != -1) {
for (int k = 0; k < i; k++)
if (array[k] == currentInput) {
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if (!dups) { // currentInput not a duplicate; assign to array[i]
array[i] = currentInput;
i++;
}
關於退出提供-1
,您可能應該刪除此行array[i] = 0
以便不將0
分配給array[i]
:
if (array[i] != -1) {
// ...
} else {
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new Scanner(System.in).nextLine();
System.out.print('\u000C');
break;
}
以下是我在您的代碼中發現的一些錯誤:
System.out.plintln("Enter the " + array.length + "....");
換行在字符串的中間,你應該做這樣的事情:System.out.println("Enter the " + array.length + " numbers now." + "\nOr enter -1 to exit")
case 1:
//DO THINGS
//....
//...
break;
case 2:
//DO OTHER THINGS
//....
//...
break;
以下是有關如何改進它的一些建議:
if(!dups)
再次檢查我希望這能解決你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.