0

I'm trying to put together a triangle program using methods that will bring results like this with a user input of 4 lines with a character string of "[]" but I keep getting the exception in thread main error:

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:855) at java.util.Scanner.next(Scanner.java:1364) at RecursiveTriangle.getCharacterInputFromUser(RecursiveTriangle.java:28) at RecursiveTriangle.main(RecursiveTriangle.java:56)

Can someone assist?

import java.util.*;

public class RecursiveTriangle{
   //Scanner sc= null;

   //method to take the line number input from the user
   int getLinesInputFromUser(){
       int numLines;
       Scanner sc = new Scanner(System.in);
       do{
           System.out.println("Enter the number of lines between 1 to 10");
           sc= new Scanner(System.in);
           numLines=sc.nextInt();
       }while(!(numLines>0 && numLines<=10));


       return numLines;

   }

   //method to take the pattern input from the user
   String getCharacterInputFromUser(){
       String pattern;
       Scanner sc = new Scanner(System.in);
       do{
           System.out.println("Enter the pattern");
           pattern=sc.next();
       }while(pattern==null || pattern.length()==0);

       sc.close();
       return pattern;
   }

   //method to print the triangle recursively
   void printTriangle(int numLines, String pattern){
       if(numLines != 0){
           int loopCount=numLines;
           while(loopCount>0) {    // loop for printing the pattern numLines times
               System.out.print(pattern);
               loopCount--;
           }
           System.out.println("");// to take the cursor on next line
           printTriangle(--numLines,pattern);
            }
   }





public static void main (String args []){
   RecursiveTriangle recursiveTriangle=new RecursiveTriangle();
   int numLines=recursiveTriangle.getLinesInputFromUser();
   String pattern=recursiveTriangle.getCharacterInputFromUser();
   recursiveTriangle.printTriangle(numLines, pattern);
}
}
marbles
  • 1
  • 2

0 Answers0