如何将正值和负值(可能单独?)存储到数组中,然后打印出来?

时间:2015-01-05 16:10:35

标签: java arrays loops for-loop java.util.scanner

我的程序会要求用户输入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");

            }

        }
}

2 个答案:

答案 0 :(得分:4)

首先,您要在每次迭代时创建一个新数组。移动线

int amount[] = new int[10]; 

到循环外面。

其次,您不需要以不同的方式处理它,您可以在int数组中存储所需的任何int个数字。

如果你坚持要分隔pos / neg数字,请创建两个数组,然后分开......我不知道为什么你会在你的情况下这样做。

答案 1 :(得分:0)

您要做的是正常存储它们。打印时要照顾它。

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]+", ")
            }
        }
    }
}