Home > Software design >  How to find the perfect square of a series of numbers in java?
How to find the perfect square of a series of numbers in java?

Time:02-17

Good evening, I am having trouble with a classroom assignment(new to java):

N is read from the input, and will be an integer in the range 1 to 20. Your program should print out the squares of the numbers from 1 up to and including N, all on a single line, with one space between the numbers. You can use System.out.print() rather than System.out.println() for this.

For example, if 5 is the input, then your output would be:
1 4 9 16 25

Here is my code so far:

import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;

public class Code {
    
  static Scanner scanner = new Scanner(System.in);
  
  public static void main(String[] args){
    int N = scanner.nextInt();
    
    // Your code here.
    for(int i = 1; i <= N; i =1) {           
      int s = (i * i);
      List<String>  answer = Arrays.asList(
          
    NumberFormat.getNumberInstance(Locale.US).format(s).split(""));    

      System.out.print(answer);
  }
}
}

My output:

[1][4][9][1, 6][2, 5]

How can I format my answer to look like the one in the example?

CodePudding user response:

What about just print them in loop without using List

 for(int i = 1; i <= N; i =1) {           
      System.out.printf("%d ", i*i);
}

or

 for(int i = 1; i <= N; i =1) {           
      System.out.print(i*i   " ");
}

CodePudding user response:

public class Code {

    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int N = scanner.nextInt();

        // Your code here.
        for (int i = 1; i <= N; i  = 1) {
            System.out.print( i * i  " ");
        }
    }
}
  • Related