有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

不匹配为什么我得到一个错误,说我的变量在导入java后没有初始化。util。输入不匹配异常;

因此,基本上,代码是一个求解项链程序的程序(两个数字相加,只返回一位数字)。这个过程会重复,直到程序返回原来的两个数字

我需要对其进行错误验证,以便用户可以输入字符串和其他非整数数据。如果你有任何其他可行的方法,请随时提出建议

//import statements
    import java.util.Scanner;
    import java.util.InputMismatchException;


    //class assingment statement
    public class NecklaceProgram  {

    //method assinmgent statement
    public static void main(String [] args)

    {
    //variables used throughout program
    int num1;
    int num2;
    int count;

    //Scanner input statement
    Scanner input = new Scanner (System.in);



    try {

    //user input for first integer
    System.out.print("Enter first single digit integer : "); 
    num1 = input.nextInt(); 

    //user input for second integer
    System.out.print("Enter second single digit integer : "); 
    num2 = input.nextInt(); 



    } catch (InputMismatchException e) 
    {
      System.out.println("Please enter only a single digit integer");
    }



    //variables for next numbers in sequence
    int nextNumber;
    int nextNextNumber;

    //calculation for next two numbers in sequence (third and fourth number)
    nextNumber = (num1 + num2) % 10;
    nextNextNumber = (num2 + nextNumber) % 10;
    count =2;

    //output of first 4 numbers in string
    System.out.print (num1 + " " + num2 + " " + nextNumber + " " + nextNextNumber);

    /*true or false statement stating that the program will be "finished" when the first two integers 
     entered by the user are the last two integers inthe sequence
     */
      boolean finished = (num1 == nextNumber) && (num2 == nextNextNumber);

    //while statement that loops through the production of the sequence until the boolean condition is met
    while (!finished)

      {
           //statements that calculate the next numbers in the sequence
           nextNumber = (nextNumber + nextNextNumber)%10;
           nextNextNumber = (nextNextNumber + nextNumber)%10;

           //java outputs the next two numbers in the seuqence until the boolean condition is met
           System.out.print(" " + nextNumber + " " + nextNextNumber);

           //the program stops running when the boolean condition is met
           //this is when the first two numbers input by the user are equal to the last two numbers in the sequence
           finished = (num1 == nextNumber) && (num2 == nextNextNumber); 

           //this counter is used to determine the number of steps taken to       output the original two numbers
           //this value will be output at the end of the program
           count += 2;

           }

         System.out.println("\nThis process took " + count + " steps to be completed");
       }
      }

共 (0) 个答案