[英]How do I store multiple values (with different types) in an array and print them out?
[英]How do I store positive and negative value (may be separately?) into an array, and print them out?
我的程序將要求用戶輸入10個數字。 正數視為存款,負數視為提款。 完成后,程序應打印出用戶輸入的金額。
我的問題是我無法設置將它們存儲到數組的邏輯。 我不知道如何將正值和負值分成一個數組。
到目前為止,這是我所做的:
package depandwith;
import java.util.*;
public class DepAndWith {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("TO DEPOSIT USE POSITIVE AND, TO WITHDRAW USE NEGATIVE VALUE.\n\n");
for (int i = 0; i < 10; i++) {
System.out.println("Enter amount: ");
int amount[] = new int[10];
amount[i] = input.nextInt();
if (amount[i] >= 0) {
//store it as deposited
} else {//if the amount is negative
//store it as withdrawn
}
}
//Printing the amounts:
for (int i = 0; i < 10; i++) {
System.out.println("Print out Deposited amount");
System.out.println("Print out Withdrawn amount");
}
}
}
首先,您需要在每次迭代中創建一個新數組。 移動線
int amount[] = new int[10];
到循環之外。
其次,您不需要以不同的方式處理它,可以將所需的任何int
編號存儲在int
數組中。
如果您堅持要分隔正負號,請創建兩個數組,然后分隔..我看不出有任何理由要這樣做。
您要做的是正常存儲它們。 在打印時要注意這一點。
package depandwith;
import java.util.*;
public class DepAndWith {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("TO DEPOSIT USE POSITIVE AND, TO WITHDRAW USE NEGATIVE VALUE.\n\n");
int amount[] = new int[10];
for (int i = 0; i < 10; i++) {
System.out.println("Enter amount: ");
amount[i] = input.nextInt();
}
//Printing the deposit amounts:
for (int i = 0; i < 10; i++) {
System.out.print("Print out Deposited amount");
if(amount[i]>0){
System.out.print(amount[i]+", ")
}
}
System.out.println();
//Printing the withdraw amounts:
for (int i = 0; i < 10; i++) {
System.out.println("Print out Withdraw amount");
if(amount[i]<0){
System.out.print(amount[i]+", ")
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.