您好我正在为我的一个项目测试此代码:
import java.util.*;
public class Multiply
{
Random randomNumbers = new Random();
int answer; // the correct answer
// ask the user to answer multiplication problems
public void quiz()
{
Scanner input = new Scanner( System.in );
int guess; // the user's guess
createQuestion(); // display the first question
System.out.println( "Enter your answer (-1 to exit):" );
guess = input.nextInt();
while ( guess != -1 )
{
checkResponse( guess );
System.out.println( "Enter your answer (-1 to exit):" );
guess = input.nextInt();
} // end while
} // end method
// prints a new question and stores the corresponding answer
public void createQuestion()
{
// get two random numbers between 0 and 9
int digit1 = randomNumbers.nextInt( 10 );
int digit2 = randomNumbers.nextInt( 10 );
answer = digit1 * digit2;
System.out.printf( "How much is %d times %d?\n",
digit1, digit2 );
} // end method createQuestion
// checks if the user answered correctly
public void checkResponse( int guess )
{
if ( guess != answer )
System.out.println( "No. Please try again." );
else
{
System.out.println( "Very Good!" );
createQuestion();
} // end else
} // end method checkResponse
} // end class Multiply
/**/
当我尝试运行它时,它会询问主要的方法" public static void main(String [] args)&#34 ;,但是当我在开头添加它时它会出现一个吨错误。谁能告诉我哪里出错?
这是我添加主要方法的时候:
import java.util.*;
public class Multiply
{
public static void main(String[] args)
{
Random randomNumbers = new Random();
int answer; // the correct answer
// ask the user to answer multiplication problems
public void quiz()
{
Scanner input = new Scanner( System.in );
int guess; // the user's guess
createQuestion(); // display the first question
System.out.println( "Enter your answer (-1 to exit):" );
guess = input.nextInt();
while ( guess != -1 )
{
checkResponse( guess );
System.out.println( "Enter your answer (-1 to exit):" );
guess = input.nextInt();
} // end while
} // end method
// prints a new question and stores the corresponding answer
public void createQuestion()
{
// get two random numbers between 0 and 9
int digit1 = randomNumbers.nextInt( 10 );
int digit2 = randomNumbers.nextInt( 10 );
answer = digit1 * digit2;
System.out.printf( "How much is %d times %d?\n",
digit1, digit2 );
} // end method createQuestion
// checks if the user answered correctly
public void checkResponse( int guess )
{
if ( guess != answer )
System.out.println( "No. Please try again." );
else
{
System.out.println( "Very Good!" );
createQuestion();
} // end else
} // end method checkResponse
} // end class Multiply
/**/
我添加的错误:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
at multiply.Multiply.main(Multiply.java:23)
答案 0 :(得分:1)
看起来你正在main方法中创建函数,这可能会导致一些问题。尝试将main方法与类的其余部分分开。例如:
public static void main(String[] args)
{
quiz();
}
-Rest of code here
答案 1 :(得分:1)
您在主要方法中定义方法,在添加主要方法时,您的想法是拥有一个" main"从中调用程序其余部分的方法。 而不是将所有内容放在主要内部尝试添加
public static void main(String[] args){
// call some function here or whatnot
}