need help with arrays

Discussion in 'Java' started by debz480, Jan 14, 2011.

  1. debz480

    debz480 New Member

    Jan 14, 2011
    Likes Received:
    Trophy Points:
    the program below is suppose to give you a choice of adding, sum, and exit.
    the use can choose 1 to add another number until the array memory runs out (4 inputs will be used in this case). if and when the user chooses 2 then the numbers inputted by the user would be added and then printed out. 0 is used to exit the program. the problem is that the first input gets stored in the first array, but when we enter an input for the second array, the first array changes back to zero. you can run it to see what i mean. i hope im clear enough. any help would be apprechiated.
    package clsa2;
    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
            int index = 0;
            do {
                Scanner input = new Scanner(;
                    System.out.println("index: "+index);
                double num[] = new double[4];
                System.out.println("Enter 1 for Add or 2 for SUM or 0 for exit");
                int choice = input.nextInt();
                if (choice == 1) {
                    System.out.println("Enter the expense associated:  ");
                    double choice1 = input.nextDouble();
                    num[index] = choice1;
                        for (int i = 0; i < num.length; i++) {
                        System.out.println("number stored in arrays: "+num[i]);
                if (choice == 2) {
                    double sum = 0;
                    for (int i = 0; i < num.length; i++) {
                        sum += num[i];
                    System.out.println("Answer is " + sum);
                if (choice == 0){
                    System.out.println("Thank you for calculating.");
                    System.out.println("Good Bye!");
                       } while (true);
    Last edited by a moderator: Jan 14, 2011

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice