Home > Blockchain >  How do I print both Strings and Ints from a single text file?
How do I print both Strings and Ints from a single text file?

Time:11-29

I have a file pretty much as follows, but for a couple more names (each word and number is on a separate line) : James 123 343 355 Kyle 136 689 680

I’ve been trying to read all these in as strings, and use parseInt to convert them to ints, as I need to find the avgs of the numbers following the names. It hasn’t worked though, and I’m curious as to how to print this file inside of Java. Thank you

CodePudding user response:

Is this you are looking for?

    import java.util.*;

    public class Main
    {
        public static void main(String[] args) {
            //System.in is a standard input stream
            Scanner sc= new Scanner(System.in);    
            String name=sc.next();
            int a= sc.nextInt();
            int b= sc.nextInt();
            int c= sc.nextInt();
            int d=(a b c)/3;
            System.out.println("Average= "  d);
        }
    }

CodePudding user response:

Let's assume for a second that under each name they can be a variable number of numerical values. What we want to do is, while each line is number, keep adding them together and keep track of the number of lines we've read and when the line becomes a String probably print it out and setup for the next sequence.

I honestly think that people think that Scanner is only useful for reading user input or a file and forget that they can use multiple Scanners to parse the same content (or help with it)

For example. I set up Scanner to read each line of the file (as a String). I then setup a second Scanner (for each line) and test to see if it's an int or not and take appropriate action, for example...

import java.util.Scanner;

public class Test {

    public static void main(String[] arg) {
        // Just beware, I'm reading from an embedded resource here
        Scanner input = new Scanner(Test.class.getResourceAsStream("/resources/Test.txt"));
        String name = null;
        int tally = 0;
        int count = 0;
        while (input.hasNextLine()) {
            String line = input.nextLine();
            Scanner parser = new Scanner(line);
            if (parser.hasNextInt()) {
                tally  = parser.nextInt();
                count  ;
            } else {
                if (name != null) {
                    System.out.println(name   "; tally = "   tally   "; average = "   (tally / (double) count));
                }

                name = parser.nextLine();
                tally = 0;
                count = 0;
            }
        }
        if (name != null) {
            System.out.println(name   "; tally = "   tally   "; average = "   (tally / (double) count));
        }
    }
}

which based on your example data, prints something like...

James; tally = 821; average = 273.6666666666667
Kyle; tally = 1505; average = 501.6666666666667
  • Related