keep tracking of each token

405 views Asked by At

I need to solve the following problem: Write a method named tokenStats that accepts as a parameter a Scanner containing a series of tokens. It should print out the sum of all the tokens that are legal integers, the sum of all the tokens that are legal real numbers but not integers, and the total number of tokens of any kind. For example, if a Scanner called data contains the following tokens:

3 3.14 10 squid 10.x 6.0

Then the call of tokenStats(data); should print the following output:

integers: 13

real numbers: 9.14

total tokens: 6

If the Scanner has no tokens, the method should print:

integers: 0

real numbers: 0.0

total tokens: 0

So, this is my question. I have tried to use

while (input.hasNext()) {

if (input.hasNextInt()) {

and this creates an infinite loop,

but if I use

while (input.hasNext()) {

input.next();

if (input.hasNextInt()) {

I lose my first token if it is an int...

what should I do?

3

There are 3 answers

0
Neha On

I suggest you check this way .. which cover all your scenario

int totalint =0;
float totalfloat=0 ;
int count=0;
while(input.hasNext()) 
{
    String next = input.next();
    int n; float f;
    try{
        if(next.contains(".")
        {
            f= Float.parseFloat(next);
            totalfloat += f;
        }
        else{
            n= Integer.parseInt(next);
            totalint +=n;
        }            
    }
    catch(Exception e){ /*not int nor a float so nothing*/ }
    count++;
}
0
cogle On

In order to determine the amount of Integers in your file I suggest doing something like this

Add the following variables to your code

ArrayList<Integer> list = new ArrayList<Integer>();
int EntryCount = 0;
int IntegerCount =0;

Then when looking through the file inputs try something like this were s is an instance of a scanner

       while (s.hasNext()) {
                if(s.hasNextInt() == true){
                        int add =s.nextInt();
                        System.out.println(add);
                           list.add(add);
                           IntegerCount++;
                    }
                    EntryCount++;
                }

Then in order to figure out the sum of all integers you would loop through the array list.

0
Dylan On
public static void tokenStats(Scanner input) { 
    int integers = 0;
    double real = 0.0;
    int tokens = 0;
    while (input.hasNext()) {
        if (input.hasNextInt()) {
            integers+= input.nextInt();
        } else if (input.hasNextDouble()) {
            real+= input.nextDouble();
        } else {
            input.next();
        }
        tokens++;
    }
    System.out.println("integers: " + integers);
    System.out.println("real numbers: " + real);
    System.out.println("total tokens: " + tokens);
}