Java 返回数字平方的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20316129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method to return square of a number
提问by user3050340
I am trying to write a code to return a square of a number
我正在尝试编写一个代码来返回一个数字的平方
I think my method is basically complete but then I have trouble with compiling,
我认为我的方法基本完整,但后来编译有问题,
here is my code
这是我的代码
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;
}
}
采纳答案by Michael Yaworski
Change print square(num);
to System.out.println(square(num));
or to square(num);
Although, what you're doing makes no sense because you actually print the number in your method as well. Try changing your code to this:
更改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;
}
}
回答by joews
There isn't a print
statement in Java - you need to use the method System.out.println(square(num));
print
Java中没有声明-您需要使用该方法System.out.println(square(num));
Although, actually, your square
method is writing the squared number to STDOUT
anyway, so you don't need to do any more printing - just square(num);
would be enough.
尽管实际上,您的square
方法STDOUT
无论如何都将平方数写入其中,因此您无需再进行任何打印 - 就square(num);
足够了。
回答by lcjury
change:
改变:
print square(num);
for:
为了:
square(num);
you're calling a method, "print" does not make any sense there.
你正在调用一个方法,“打印”在那里没有任何意义。