-1

I'm supposed to write a program in java that scans 10 double numbers and then stores them in an array. The numbers are then supposed to be reversed and printed. This is what I've written. The program prints the array in the right order instead of reversed, how can i fix it?

public class ReverseNumbers {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // Fyll i egen kod

        double[] a = new double[10];


        for(int i = a.length - 1; i >=0; i--){
              a[i] = scan.nextDouble();

            System.out.print(" " + a[i]);
        }
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Aslan.H14
  • 21
  • 2

3 Answers3

1

You need to use Arrays.toString or another loop to print the array.

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double[] a = new double[10];
        System.out.println("Enter " + a.length + " numbers: ");
        for (int i = a.length - 1; i >= 0; i--) {
            a[i] = scan.nextDouble();
        }

        // Either print it like this
        System.out.println(Arrays.toString(a));

        // Or like this
        for (double d : a) {
            System.out.print(d + " ");
        }

        System.out.println();

        // Or like this
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }
}

A sample run:

Enter 10 numbers: 
10 20 30 5 15 25 12 22 32 42
[42.0, 32.0, 22.0, 12.0, 25.0, 15.0, 5.0, 30.0, 20.0, 10.0]
42.0 32.0 22.0 12.0 25.0 15.0 5.0 30.0 20.0 10.0 
42.0 32.0 22.0 12.0 25.0 15.0 5.0 30.0 20.0 10.0 
halfer
  • 19,824
  • 17
  • 99
  • 186
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

This line of code worked :), thanks guys!

public class ReverseNumbers {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // Fyll i egen kod

        double[] a = new double[10];


        for(int i=0; i<10; i++){
            a[i] = scan.nextDouble();
        }

        for(int i = a.length - 1; i >=0; i--){


            System.out.print(a[i] + " ");
        }
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Aslan.H14
  • 21
  • 2
-1

See as a beginner I don't know Java language, but I can solve your question using Qbasic easily.

CLS
N = 1
DO
    INPUT "ENTER THE NUMBER"; A(N)
    N = N + 1
LOOP WHILE N <= 10
CLS
DO
    PRINT A(N)
    N = N - 1
LOOP WHILE N > 0
END
halfer
  • 19,824
  • 17
  • 99
  • 186
Rahul_29
  • 1
  • 3
  • 2
    Please do not answer questions in another language, unless the stated question asks about solutions in the language you are wanting to answer in. – halfer Apr 15 '20 at 11:58