Home > database >  How can I accept only a specific number of lines from user input using scanner in java
How can I accept only a specific number of lines from user input using scanner in java

Time:10-01

I'm working on an assigment where I accept a 8 lines of text from user specifically and print each word on its own line, I'm struggling with keeping count of the lines and only printing the words if the user input is exactly 8 lines. This is what I have so far

class EightLines{
    public static void main(String[] args){
        System.out.println("Enter 8 lines:");
        Scanner input = new Scanner(System.in);
        
        
        
        
        while (input.hasNextLine()){
        String line = input.nextLine();
        printwords(line);}
        }
        
    
  public static void printwords(String line) {     
            


                //String line = input.nextLine();
                line = line.trim();
                String[] arrofwords = line.split("[;:,.!?' ']");
                for (int j=0;j<arrofwords.length;j  ){
                    String word = arrofwords[j];
                   if (word == " "){System.out.print("");}
                    
                    else{
                    System.out.println(arrofwords[j]);}
                }
            
          
        }
    
}```

CodePudding user response:

You can use an array of size 8 to store the input lines and then print their words.

final int LIMIT =8;
String [] arr = new String[LIMIT];

// Input
for (int i = 0; i < LIMIT; i  ) {
    arr[i] = input.nextLine();
}

// Print
for (int i = 0; i < LIMIT; i  ) {
    printwords(arr[i]);
}

If you want the input and printing to be processed together, you do not need an array.

for (int i = 0; i < 8; i  ) {
    String line = input.nextLine();
    printwords(line);
}
  • Related