1

I don't know why it keeps saying this Error in Title My question is "why my StringTokenizer Not working ?" Though it works in the first input "when user input X" , but at "a[i] = Integer.parseInt(st.nextToken());" it doesn't work. The program function is to declare a group which is a no of friends and those friends give each other money and in the end we see from 0 how each one of them have got benefited "+sign result "MONEY"" or if he loses ie: that he gives more than he recieves so it's "-sign Result"money""

package test2;
/*
ID: toti5821
TASK: gift1
LANG: JAVA                 
*/
    import java.util.*;
    import java.io.*;
    import java.util.StringTokenizer;
public class test2 {

public static void main(String[]args) throws IOException{

BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new FileWriter("gift1.out"));
Scanner scan = new Scanner(System.in);
StringTokenizer st = new StringTokenizer(f.readLine());
int x = Integer.parseInt(st.nextToken());
 HashMap<String,Integer> nameandmoney = new HashMap<String, Integer>();
for(int i=0;i < x;i++){
    String name = f.readLine();
    nameandmoney.put(name, 0);
}


for(int i=0;i<=x;i++) {
    String thisname = f.readLine();
    int size = 2;
    int[] a= new int[size];
    for (int j = 0; j < size; j++) {
        a[i] = Integer.parseInt(st.nextToken());
    }
    System.out.println(a[1]);
    nameandmoney.put(thisname,nameandmoney.get(thisname) - a[0]);
    int leftover =a[0]%a[1];
    nameandmoney.put(thisname,nameandmoney.get(thisname) + leftover);
    int gift1 = a[0]/a[1];
    if(a[1]==0) {
        gift1=0;
    }


    for(int k=0;k<a[1];k++) {
        String reciever = f.readLine();
        nameandmoney.put(reciever,nameandmoney.get(reciever) - gift1);
    }

} for(String names: nameandmoney.keySet()) {
    out.println(names+" "+nameandmoney.get(names));
}   } }
  • You need to use `hasNextToken()` to ensure that it does indeed have another token before calling `nextToken()` – GBlodgett Jul 25 '18 at 23:23
  • GBlodgett please can you clarify more the concept behind it how it will work like that – Mahmoud Sharshera Jul 26 '18 at 08:40
  • If `f.readLine()` doesn't have any more tokens, and you call `nextToken()` it will throw an `NoSuchElementException`. You need to ensure that what you are reading with `st` will have another token. Otherwise it is very prone to this error – GBlodgett Jul 26 '18 at 13:41

0 Answers0