简体   繁体   中英

java reverse a string of numbers

I need to be able to input a list of numbers the last being -1 and have it print the reverse(not including -1) and then find the average. I have to use a function for finding the reverse. Im stuck because it cannot resolve my average which means I cannot run the program to see if there are other problems.

import java.util.Scanner;

public class Reverse {
public static void inReverse (int a) {
    int number;
    int[] value;

    for (a = number - 2; a >= 0; a--) {
        System.out.print(value[a] + " ");
    }
}

public static double findAverage (int p, double average) {
    int number;
    for (p = number - 2; p >= 0; p--) {
        average += value[p];
    }
    average = average / (number - 1);
    return average;
}

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] value;
    int i, number, size;        
    size = 20;  
    System.out.println("Please enter the integers: ");
    while (value[i - 1] != -1 && number < size) {
        value[i] = input.nextInt();
        i += 1;
        number = i;
    }
    System.out.println("The values in reverse order are: ");
    inReverse(i);
    System.out.println(" ");
    System.out.println("The average is " + average);
}
}

Your problem is that you have confused "local variables" with "fields".

Local variables are variables that you declare inside the body of a method. They can't be used before the declaration, and they can't be used once the method stops running - their values have ceased to exist.

Fields are variables that you declare inside your class, but outside any methods. These live inside each object of the class (or inside the class itself if you declare them as static), which means they keep their values from one method call to the next.

You have int number; and int[] value; declared inside different methods, which means they are local variables, and they are recreated each time those methods run. This isn't what you want. You either want to pass them from one method to the next, as parameters; or to have them as fields of your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM