Java use Scanner to count words and lines from user input

16,029

you can calculate the words,lines with the following code

 public static void printWordsOfLines(Scanner x){
 Scanner line=x;
 Scanner word=x;
int lines = 0;
System.out.println("Enter q to quite input");
int words=0;

while(line.hasNextLine()){
   String xx=line.next();

   String w[]=xx.split("  ");
   String l[]=xx.split("\n");

   words+=w.length;
   lines+=l.length;

   if(xx.equals("q"))
       break;
  else   
      x.nextLine();
    }
  System.out.println("lines: " + lines);
  System.out.println("words: " + words);
}
Share:
16,029
yhsdygdyusgdysgdsudsd
Author by

yhsdygdyusgdysgdsudsd

Updated on June 04, 2022

Comments

  • yhsdygdyusgdysgdsudsd
    yhsdygdyusgdysgdsudsd almost 2 years

    I'm trying to use the Scanner class to calculate the number of words and lines from a user input, and this is my attempt:

    import java.util.Scanner;
    
    public class newCounter{
      public static void main(String [ ] args){
    
        Scanner input = new Scanner(System.in);
    
        printWords(input);
        printLines(input);
    
      }
    
      public static void printWords(Scanner x){
        int words = 0;
        while(x.hasNext()){
          words++;
          x.next();
        }
        System.out.println("words: " + words);
      }
    
    
    
      public static void printLines(Scanner x){
        int lines = 0;
        while(x.hasNextLine()){
          lines++;
          x.nextLine();
        }
        System.out.println("lines: " + lines);
    
      }
    }
    

    I've found that both methods work 100% fine individually, but only the first one called works when together (The printWords method in this situation). Is there any way of combining these methods so that it might work as one loop?

  • yhsdygdyusgdysgdsudsd
    yhsdygdyusgdysgdsudsd about 9 years
    Thanks for the answer, although i'm still not sure I understand. These scanners line & word still refer to the same single input scanner, so again only the line loop works and the word loop has nothing left to loop through?