[英]how to fix “ illegal start of expression” error while declare method in java
I have declared a simple method inside a class that checks if a number is triangular or not but while declaring the method the compiler shows "illegal start of expression" error. 我在类中声明了一个简单的方法,该方法检查数字是否为三角形,但是在声明该方法时编译器显示“表达式的非法开始”错误。 Given Below is my code
下面给出的是我的代码
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n ;
Scanner in = new Scanner (System.in) ;
n = in.nextInt() ;
static boolean isTriagular ()
{
int tn = 1 ;
while ( n <= tn )
{
if ( tn == n )
{
System.out.println("yes" ) ;
System.exit(0) ;
}
tn += ( tn + 1 ) ;
}
}
// your code goes here
}
}
Main.java:14: error: illegal start of expression static boolean isTriagular () ^ Main.java:14:错误:表达式的非法开头静态布尔值isTriagular()^
You should move isTriangular
outside of your main method and then call your method in your main method as shown below: 您应该将
isTriangular
移动到main方法之外,然后在main方法中调用您的方法,如下所示:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n ;
Scanner in = new Scanner (System.in) ;
n = in.nextInt() ;
// your code goes here
isTriagular();
}
static void isTriagular()
{
int tn = 1 ;
while ( n <= tn )
{
if ( tn == n )
{
System.out.println("yes" ) ;
System.exit(0) ;
}
tn += ( tn + 1 ) ;
}
}
}
I changed the type of isTriangular
to a void
since you are exiting the entire program after printing something to the console. 我将
isTriangular
的类型isTriangular
为void
因为在将某些内容打印到控制台后要退出整个程序。 It would only need to be a boolean if you are returning a result from it to set equal to another variable. 如果您要从中返回结果以将其设置为等于另一个变量,则只需为布尔值即可。
An example of this is: 例如:
boolean myResult = isTriangular();
you are declaring a function inside another function move isTriangulaire()
declaration outside the main()
function 您在另一个函数内部声明一个函数,将
isTriangulaire()
声明移至main()
函数之外
you can call isTriangulaire()
inside main after that 您可以在main之后调用
isTriangulaire()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.