返回数字的平方的方法

时间:2013-12-01 19:19:31

标签: java

我正在尝试编写代码以返回数字的正方形

我认为我的方法基本完成,但后来我编译时遇到了麻烦,

这是我的代码

import java.util.Scanner;

public class Number {

    public static void main(String [] args)
    {

        Scanner in = new Scanner(System.in);
        System.out.print("Please enter a number to square: ");
        int num = in.nextInt();
        print square(num); //error here, Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
        //print cannot be resolved to a type
        //Syntax error on token "square", = expected after this token
        //at Number.main(Number.java:11)

    }
    public static int square(int num) 
    {
        System.out.println("You entered: " + num);
        num = num * num;
        System.out.println("Your number squared is: " + num);
        return num;

    }
}

3 个答案:

答案 0 :(得分:2)

Java中没有print语句 - 您需要使用方法System.out.println(square(num));

虽然实际上,您的square方法无论如何都要将平方数写入STDOUT,因此您无需再进行打印 - 只需square(num);即可。< / p>

答案 1 :(得分:1)

print square(num);更改为System.out.println(square(num));或更改为square(num);尽管如此,您所做的事情毫无意义,因为您实际上也会在方法中打印该数字。尝试将代码更改为:

import java.util.Scanner;

public class Number {

    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter a number to square: ");
        int num = in.nextInt();
        System.out.println("Your number squared is: " + square(num));
    }
    public static int square(int num) 
    {
        return num * num;
    }
}

答案 2 :(得分:0)

变化:

print square(num);

有:

square(num);

你正在调用一种方法,“print”在那里没有任何意义。