簡體   English   中英

Java通過使用數組方法通過忽略其他數字來打印最后一個數字

[英]Java is printing last number using array method, by ignoring other numbers

我試圖讓我的代碼打印輸出但使用數組方法的數字。

package pkg11;

import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int x = 0;

    System.out.println("How many number do you want to put?");
    int b = in.nextInt();

    for (int z = 1; z <= b; z++) {
      System.out.println("Input your" + " " + z + " " + "number");
      x = in.nextInt();
    }

    System.out.println();
    int[] a = new int[x];;

    for (int i = 0; i < a.length; i++) {
      System.out.println(a[i]);
    }
  }
}

問題是,當打印時,它僅打印最后一個值,例如,我想輸入3個數字,第一個是1,第二個是2,第三個是3,它打印第三個而沒有第一個2。

請仔細查看您的以下代碼片段,並嘗試找出錯誤:

for (int z = 1; z <= b ; z++) {
    System.out.println("Input your" +" " +z +" " +"number");
    x = in.nextInt();
}

// here you create the array
int [] a = new int [x];

如果沒有發現,請執行以下操作:從控制台讀取所有值后,創建要保存每個整數的數組。 您無法將用戶輸入存儲在數組中,因為當時尚不知道。

那你到底在做什么

您一直使用相同的變量x x = in.nextInt(); ,覆蓋每個輸入。

我該怎么辦才能解決問題?

Scanner in = new Scanner(System.in);
int x = 0;

System.out.println("How many number do you want to put?");
int b = in.nextInt();

int[] a = new int[b];

for (int z = 0; z < b; z++) {
    System.out.println("Input your" + " " + (z + 1) + " " + "number");
    a[z] = in.nextInt();
}

for (int i = 0; i < a.length; i++) {
    System.out.println(a[i]);
}

首先,聲明int[] a = new int[b]; 在讀取值並為每個輸入分配數組之前,先使用a[z] = in.nextInt(); 另外,我對循環索引進行了一些修改,以使事情變得更容易。

好吧,我還能做什么?

除了用戶輸入非數字外,此代碼還具有防彈功能! 如果您正在尋找更多內容,則可以使用in.nextLine()Integer.valueOf()來防止用戶輸入字符串而不是數字。

Scanner in = new Scanner(System.in);

int amountOfNumers;
System.out.println("How many number do you want to put? Amount: ");

amountOfNumers = in.nextInt();
while (amountOfNumers < 1) {
    System.out.println("Please enter a number greater than one:");
    amountOfNumers = in.nextInt();
}

int[] numbers = new int[amountOfNumers];

for (int i = 0; i < amountOfNumers; i++) {
    System.out.println("Input your " + (i + 1) + " number: ");
    numbers[i] = in.nextInt();
}

System.out.println("Your numbers are:");
Arrays.stream(numbers).forEach(System.out::println);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM