计算所有数字的完美正方形到给定数量?

时间:2017-06-18 20:03:49

标签: java methods

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

这是我尝试过的。

def get_img_filename(self, img):
    return img.path

def get_img_thumb_filename(self, img):
    img_pre, img_ext = os.path.splitext(img.path)
    thumb_name = img_pre + '_thumb' + img_ext
    return thumb_name

输出只给我一个不是我想要的数字。我是JAVA和编程的新手,但我的理解是你应该尝试在main之外创建方法然后创建对象来调用里面的方法主要。所以我试图创建一个名为numberInput的方法,然后在主要的我尝试调用它。如果这是错误的方法,请纠正我。

1 个答案:

答案 0 :(得分:0)

你非常接近,结果的问题是循环正在更新相同的数字。

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);
}
相关问题