Displaying the First 100 Words Of a Program that Contains a File - Java [closed]

StackOverflow https://stackoverflow.com/questions/23581381

  •  19-07-2023
  •  | 
  •  

Domanda

I have a program that reads a file in order to sort the file alphabetically. So the output of the program is displayed in an ascending order (From A-Z if applies). However, I want my program to just output the first 100 words by ignoring the rest of it. Is there a Unix command that allows me to carry out this function? or do I have to implement a code/algorithm within my program in order to accomplish it?

È stato utile?

Soluzione

It should be something like:

Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("file.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }
    int numberword=100;
    int count=0;
    while (sc2.hasNextLine() && count<numberword) {
            Scanner s2 = new Scanner(sc2.nextLine());
        boolean b;
        while (b = s2.hasNext() && count<numberword) {
            String s = s2.next();
            count++;
            System.out.println(s);
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top