0

所以基本上代码是一个解决项链程序的程序(两个数字相加,只返回一个数字。重复这个过程,直到程序返回原来的两个数字。

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

//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");
       }
      }
4

0 回答 0