Java 计算所有数字直到给定数字的完美平方?

Java 计算所有数字直到给定数字的完美平方?,java,methods,Java,Methods,我想写一个程序,找到用户输入的所有数字的平方。例如,如果用户输入5,则程序输出1,4,9,16,25 这就是我尝试过的 import java.util.Scanner; public class PerfectSquares { public void numberInput(){ Scanner sc = new Scanner(System.in); System.out.println("Enter a number"); in

我想写一个程序,找到用户输入的所有数字的平方。例如,如果用户输入5,则程序输出1,4,9,16,25

这就是我尝试过的

import java.util.Scanner;

public class PerfectSquares {

    public void numberInput(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int choice = sc.nextInt();
        for(int i =0;i<choice;i++){
            choice=choice*choice;
        }
        System.out.println("The squares are" + choice);     
    }

    public static void main(String[] args) {
        PerfectSquares input = new PerfectSquares();
        input.numberInput();
    }

}
import java.util.Scanner;
公共类广场{
公共无效号码输入(){
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入一个数字”);
int choice=sc.nextInt();

对于(int i=0;i您非常接近,您的结果的问题是循环正在更新相同的数字

Import java.util.Scanner;
public class PerfectSquares {

public void numberInput(int max){
    List<Integer> squares = new ArrayList<>();
    for(int i =0;i<max;i++) {
        squares.add(i^2);
    }
    System.out.println("The squares are: " +  String.join(squares, ", ");
}
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number");
    int choice = sc.nextInt();
    PerfectSquares input = new PerfectSquares();
    input.numberInput(choice);
}
Import java.util.Scanner;
公共类广场{
公共无效号码输入(整数最大值){
列表方块=新的ArrayList();

for(int i=0;i这是您的println语句吗?它是在for循环内部,在那里它将被重复调用?还是在循环外部,它将只被调用一次?谢谢。请您解释一下什么是(最大值)和什么是列表。您正在创建数组吗?箭头括号是什么?还有什么是String.join(方格,“.”)doing?Into是一个输入错误,应该是int。java.util.List是一个java.util.Collection扩展。它们是一组非常有用的类和接口,处理大量相同类型的数据。在本例中,泛型声明意味着只有该类型的对象才能在列表中。@Nabeel呃,我建议使用t请阅读Java文档中的集合和字符串。