-2

When I run my code using BufferedReader class as well as util class and initialising the variables outside the StringTokenizer using BufferedReader class then it works but when I use this it breaks and I get java.util.NoSuchElementException error as I input the first String s(in the code).

import java.util.*;

class spamclas
{
public static void main() 
{

    Scanner sc=new Scanner(System.in);
    int a=0,b=0;
    int t=sc.nextInt();
    while(t>0)
    {
        String s=sc.next();
        StringTokenizer st=new StringTokenizer(s);
        while(st.hasMoreTokens())
        {
            a = Integer.parseInt(st.nextToken());
            b = Integer.parseInt(st.nextToken());
        }

        System.out.println("a   b"+a+"   "+b);
        t--;
    }
}
}
azro
  • 53,056
  • 7
  • 34
  • 70

2 Answers2

2

The condition st.hasMoreTokens() look if there is at least one more element next and you call st.nextToken() twice


So in case there is only one more element, the condition will be true but the second st.nextToken() will find anything

Because you give 1 1 to sc.next(), you String s will be only 1 (default separator of next() is space), so there is only one digit, and second nextToken() will faill

Youd better use sc.nextLine() and check for each digit with 2 if :

int t = Integer.parseInt(sc.nextLine());        // nextLine here too to consume return char
while (t > 0) {
  String s = sc.nextLine();
  StringTokenizer st = new StringTokenizer(s);
  a = b = 0;
  if (st.hasMoreTokens()) { a = Integer.parseInt(st.nextToken()); }else{ a=0; }  //line 18
  if (st.hasMoreTokens()) { b = Integer.parseInt(st.nextToken()); }else{ b=0; }  //line 19
  System.out.println("a : " + a + ", b : " + b);
  t--;
}

Tips : line 18&19 can be written with ternary operator :

a = st.hasMoreTokens() ? Integer.parseInt(st.nextToken()) : 0;
b = st.hasMoreTokens() ? Integer.parseInt(st.nextToken()) : 0;
azro
  • 53,056
  • 7
  • 34
  • 70
  • Now when I ran the code the program takes no input for the first time when the loop works but for the second time it asks for String s, What can I do to solve that ? – amethyst stan Jan 27 '18 at 10:59
  • @amethyststan Did you change the line for init of `int t ` as I give ? – azro Jan 27 '18 at 11:36
1

First of all, Don´t worry

The problem is that when it reaches this line.

b = Integer.parseInt(st.nextToken());

It is empty.

Because you put the .nextToken() in a it is now empty.

Rawmouse
  • 77
  • 8