Getting a NoSuchElementException 33 - java

I don't know why I am getting this error. What should I do to fix it? Any help really appreciated. I excluded code that does not affect the error. Line 33 is String string1 = token.nextToken();
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Exec {
public static void main(String[ ] args){
Scanner input = new Scanner( System.in );
String user_input = " ";
//user gets asked to enter input here...
//...
//tokenize input into 2 strings and method code
user_input = input.next( );
StringTokenizer token = new StringTokenizer(user_input);
String string0 = token.nextToken();
String string1 = token.nextToken();
code = Integer.parseInt(token.nextToken());

You've run out of tokens. You should print out your String before tokenizing it as it is likely not be what you think it is. In other words what you want to do now is some debugging.
Note 1: always check first if more tokens exist with hasMoreTokens() before taking a token with nextToken().
Note 2: most of us avoid use of StringTokenizer and instead use either a Scanner or String#split(...).

You can use hasMoreTokens() method while traversing using StringTokenizer to check that tokens are actually present.This method call returns 'true' if and only if there is at least one token in the string after the current position;
StringTokenizer token = new StringTokenizer(user_input);
// checking tokens
while (token.hasMoreTokens()){
System.out.println("Next token : " + token.nextToken());
}
Also,in your code you are calling nextToken 3 times,so 3 tokens will be traversed.So, if your input string has less than 3 tokens it would fail with the exception you are getting.
It looks like you want to convert one of the tokens to integer in the call
code = Integer.parseInt(token.nextToken());
do you want to say "code = Integer.parseInt(string1)" OR "code = Integer.parseInt(string2)" instead?
Because when you say token.nextToken in integer.parseInt it would again look for next token i.e. 3rd token in this case.hope this helps.

It looks like you don't have as many tokens in user_input as you think you do. By default,
Scanner#next() reads up to the next whitespace character and StringTokenizer uses a smaller subset of whitespace characters as the delimiter, as stated in the API.
Maybe you should read user input using Scanner#nextLine() instead.

Related

How to loop a String ArrayList in java and how to split the elements in it

I have to write a program which prints the String which are inputed from a user and every letter like the first is replaced with "#":
mum -> #u#
dad -> #a#
Swiss -> #wi## //also if it is UpperCase
Albert -> Albert //no letter is like the first
The user can input how many strings he wants. I thought to split the strings with the Split method but it doesn't work with the ArrayList.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
ArrayList <String> Parolecens= new ArrayList <String>();
while (s.hasNextLine()) {
tdc=s.nextLine();
Parolecens.add(tdc);
}
System.out.println(Parolecens);
}
}
If you want to read in single words you can use Scanner.next() instead. It basically gives you every word, so every string without space and without newline. Also works if you put in two words at the same time.
I guess you want to do something like this. Feel free to use and change to your needs.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
while (s.hasNext()) {
tdc=s.next();
char c = tdc.charAt(0);
System.out.print(tdc.replaceAll(Character.toLowerCase(c) +"|"+ Character.toUpperCase(c), "#"));
}
}
}
Edit:
Basically it boils down to this. If you want to read single words with the scanner use .next() instead of .nextLine() it does consider every word seperated by space and newline, even if you put in an entire Line at once.
Tasks calling for replacing characters in a string are often solved with the help of regular expressions in Java. In addition to using regex explicitly through the Pattern class, Java provides a convenience API for using regex capabilities directly on the String class through replaceAll method.
One approach to replacing all occurrences of a specific character with # in a case-insensitive manner is using replaceAll with a regex (?i)x, where x is the initial character of the string s that you are processing:
String result = s.replaceAll("(?i)"+s.charAt(0), "#");
You need to ensure that the string is non-empty before calling s.charAt(0).
Demo.
Assuming that you've successfully created the ArrayList, I'd prefer using the Iterator interface to access each elements in the ArrayList. Then you can use any String variable and assign it the values in ArrayList . Thereafter you can use the split() in the String variable you just created. Something like this:
//after your while loop
Iterator<String> it = Parolecens.iterator();
String myVariable = "";
String mySplitString[];
while(it.hasNext()) {
myVariable = it.next();
mySplitString = myVariable.split(//delimiter of your choice);
//rest of the code
}
I hope this helps :)
Suggestions are always appreciated.

Removing Spaces from Scanner (System.in) Input

Right now I'm working on taking an equation, in "infix" notation and remove any spaces within that string prior to performing the rest of my program. Right now, without any spaces in the string, I receive the correct "Postfix" equation in return. But for some reason I can't seem to remove the spaces of a string that was entered using new Scanner(System.in); prior to performing my "Postfix" method(s). Here is the main method of my file:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the equation you'd like to evaluate: ");
InfixToPostFix postFixString = new InfixToPostFix();
String infix = keyboard.next();
String newInfix = infix;
//String newInfix = "9 * 5.3";
//String deleteSpaceInInfix = newInfix.replace(" ", "");
//System.out.println("deleteSpaceInInfix: " + deleteSpaceInInfix);
System.out.println("Postfix representation: " + postFixString.InfixToPostfix(infix));
}
Now I've noted out three lines that I tried to test while noting out the lines using the scanner information. In doing so, the result of the lines commented out is: 9*5.3 as expected. So I believe that it is something with the Scanner String object.
The way that you see this method now, when 9 * 5.3 is entered produces only 9. Everything after the first space is dropped.
I've tried to look up possible causes for this problem I'm not understanding and looked it up in the API documentation but haven't seen anything.
I'd appreciate any information in helping me better understand why my Scanner object (String infix = keyboard.next(); in this instance) is being treated differently than a normal String newInfix = "9 * 5.3; object is?
The default delimiter of Scanner is whitespace. Use nextLine() if you want to read an entire line:
Scanner keyboard = new Scanner(System.in);
String infix = keyboard.nextLine();
infix = infix.replace(" ", "");
System.out.println(infix);
Note: There's also hasNextLine() to check if there is another line in the input.

Printing a string backwards

I'm trying to print a string in reverse. i.e.
hello world
should come out as:
dlrow olleh
But the outcome only shows the reverse of the first word. i.e.
olleh
Any thoughts?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Input a string:");
String s;
s = input.next();
String original, reverse = "";
original = s;
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
input.close();
}
}
Using input.next() only stores the next word in the variable (only "hello"). Try this:
System.out.println("Input a string:");
String s;
s = input.nextLine();
System.out.println("entered: " + s);
The line
s=input.next()
will only take one word.
So to get the whole line 'hello world', you've to use the nextLine() function.
s = input.nextLine();
Your scanner object returns only the next complete token through the input.next() method. A token is considered complete when there is a whitespace character. Use the nextLine() method of the scanner to get the complete input if you are using multiple words.
new StringBuilder("hello world").reverse().toString();
Maybe much more simpler.
use s.nextline() instead of s.next() as s.next() read only first token string
Scanner sc= new Scanner(System.in);
String s = sc.nextLine();
System.out.println(new StringBuilder(s).reverse().toString());
From Scanner javadoc:
public String next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
What happens is that the token delimiter may not be what you're expecting (newline, for instance).
If you wish your program to read the entire line input by the user, you might want to use Scanner.nextLine(), which will read the entire line input by the user, or maybe Scanner.next(String delimiter), which will allow you to enter the desired token delimiter.
Change s = input.next() to s = input.nextLine()
I can't really write some source code but maybe try using two different inputs. After that add each string to it's own variable. After that, reverse them both and add them together as an output.

How can i split the user's input with tokens?

i need your advise in order to do something ... i want to take the user's input line as i already do in my program with scanner ... but i want to split each command(word) to tokens .... i do not know how to do that , till now i was playing with substring but if the users for example press twice the space-bar button everything is wrong !!!!!
For example :
Please insert a command : I am 20 years old
with substring or .split(" ") , it runs but think about having :
Please insert a command : I am 20 years old
That is why i need your advice .... The question is how can i split the user's input with tokens.
Well, you need to normalize you string line before splitting it to tokens. A simplest way is to remove repeated whitespace characters:
line = line.replaceAll("\\s+", " ");
(this will also replace all tabs to a single " ").
Use the StringTokenizer class. From the API :
"[It] allows an application to break a string into tokens... A
StringTokenizer object internally maintains a current position within
the string to be tokenized."
The following sample code from the API will give you an idea:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
It produces the following result:
this
is
a
test
Okay, so the code that I have made is going to ask you for to insert a command, it is then going to take your command and then split it around any number of spaces (due to the Regex). It then saves these words, numbers, speech marks etc. as tokens. You can then manipulate each word in the for loop.
import java.util.Scanner;
public class CommandReaderProgram{
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.println("Please insert a command:");
String temp = userInput.nextLine();
while(temp != null){
String [] tokens = temp.split("\\s+");
for(String word : tokens){
System.out.print(word);
System.out.print(" ");
}
break;
}
System.out.print("\n");
}
}
To test that each word, number and speech mark has actually been saved as a token, change the character in the System.out.print(" "); code to anything. e.g System.out.print(""); or
System.out.print("abcdefg"); and it will put this data between each token, to prove that the tokens are indeed separate.
Unfortunately I am unable to call the token array outside of the for loop at the moment, but will let you know when I figure it out.
I'd like to hear what type of program you are trying to make as I think we are both trying to make something very similar.
Hope this is what you are looking for.
Regards.

How do I change the delimiter from a text file?

Let's say I got a textfile.txt that I want to read from. This is the text in the file:
23:years:old
15:years:young
Using the useDelimiter method, how can I tell my program that : and newlines are delimiters? Putting the text in one line and using useDelimter(":"); works. The problem is when I got several lines of text.
Scanner input = new Scanner(new File("textfile.txt));
input.useDelimiter(:);
while(data.hasNextLine()) {
int age = input.nextInt();
String something = input.next();
String somethingelse = input.next();
}
Using this code I will get an inputMisMatch error.
Try
scanner.useDelimiter("[:]+");
The complete code is
Scanner scanner = new Scanner(new File("C:/temp/text.txt"));
scanner.useDelimiter("[:]+");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
The output is
23
years
old
15
years
young
Use this code
Scanner input;
String tokenizer[];
try {
input = new Scanner(new File("D:\\textfile.txt"));
input.useDelimiter("\\n");
while(input.hasNextLine()) {
tokenizer = input.next().split(":");
System.out.println(tokenizer[0]+" |"+tokenizer[1]+" | "+tokenizer[2]);
}
}catch(Exception e){}
It will give you output like
23 |years | old
15 |years | young
You have two ways to do this:
Concatenate the string to make it one line.
delimit "newline" first, then delimit ":" each return string token.
If all you want is to get everything split up all at once then I guess you can use
useDelimiter(":\\n")
That should split on both : and newspace but it is not the most efficient way of processing data, especially if each line of text is set out in the same format and represents a complete entry. If that is the case then my suggestion would be to only split on a new line to begin with, like this;
s.useDelimiter("\\n");
while(s.hasNext()){
String[] result = s.next.split(":");
//do whatever you need to with the data and store it somewhere
}
This will allow you to process the data line by line and will also split it at the required places. However if you do plan on going through line by line I recommend you look at BufferedReader as it has a readLine() function that makes things a lot easier.
As long as all the lines have all three fields you can just use input.useDelimiter(":\n");
you probably wants to create a delimiter pattern which includes both ':' and newline
I didn't test it, but [\s|:]+ is a regular expression that matches one or more whitespace characters, and also ':'.
Try put:
input.useDelimiter("[\\s|:]+");

Categories