Reputation: 23
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 () ^
Upvotes: 0
Views: 100
Reputation: 53
You should move isTriangular
outside of your main method and then call your method in your main method as shown below:
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. 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();
Upvotes: 1
Reputation: 124
you are declaring a function inside another function
move isTriangulaire()
declaration outside the main()
function
you can call isTriangulaire()
inside main after that
Upvotes: 0