Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   need help with arrays (http://www.go4expert.com/forums/help-arrays-t24523/)

debz480 14Jan2011 06:32

need help with arrays
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.in);
                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);

All times are GMT +5.5. The time now is 11:04.