Why doesn't StringTokenizer understand the nextToken function? [duplicate] - java

This question already has answers here:
Odd error in my Java program
(2 answers)
Closed 6 years ago.
I made a calculator and now improving it so that it reads one line of code and turns it into three variables a: first number, b: second number, and function: what it does example: 10 * 10. This is my code:
System.out.println("problem: ");
problem = user_input.next();
StringTokenizer token = new StringTokenizer(problem," ");
a = Integer.parseInt(token.nextToken());
String Menu = (token.nextToken());
b = Integer.parseInt(token.nextToken());
It doesn't understand nextToken at all, it says at Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at mycalc.main(mycalc.java:20),
also I asked a friend that actually showed me how this works and he was confused too. Please help me any possible way you can!

When you do
problem = user_input.next();
this read just one word. e.g. if you input 10 * 10, then this word will be 10
So when you do
String Menu = (token.nextToken());
there is no such element as the error suggests.
Note: you are parsing for words two different ways. It would be simpler to just use the scanner.
System.out.println("problem: ");
a = user_input.nextInt();
String menu = user_input.next();
b = user_input.nextInt();

Related

How to print a line and type input in the same line [duplicate]

This question already has answers here:
How to keep my user input on the same line after an output?
(4 answers)
Closed 3 years ago.
I want to print a line like this:
Result: [the result are input here and after click on Enter to continue]
How can I do that?
EDIT:
This is what I want:
Scanner user1 = new Scanner(System.in);
int x = user1.nextInt();
System.out.println("Result: "+x);
But the last line won't print unless I type my input and press Enter.
Using java, you simply could use System.out.print(); to display it in console and after adding the capture info:
System.out.print("Result: ");
int x = user1.nextInt();
This is a very old thread but since there doesn't seem to be an accepted answer, I am answering. Hope it would help someone else...
Here is what you are looking for
Scanner input = new Scanner (System.in);
System.out.print("Enter a number : ");
int num = input.nextInt();
System.out.println("Hello you entered "+num);
Note that when you use println the cursor moves to next line.
If you use just print the next statement continues on the same line.
Hope this one will work. Please try
Input str =scanner. readLine("Result:" ) ;
Int inp =integer.parseInt(star) ;
The last line will not print unless you type an input and press enter as the code is run line by line. First you have to enter the value. Since it runs on console for the next step to be pressed you have to press enter.
So whatever you said will naturally happen and cannot be avoided.
Based on the code snippet you sent there is nothing wrong with the code and the logic in it and these are basic java steps.

Do while loop in java not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 5 years ago.
I'm pretty new to coding, and I understand how to do a do while for a yes or no answer in C++. But java is giving me a hard time. This code doesn't give me any errors until I run it. When it asks for the yes or no answer it will say:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at midterm.main(midterm.java:40)
Line 40 is the:
ans = s.next();
Maybe I'm doing something wrong with String, I've tried char but had no luck either. Here is my code:
public class midterm
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String ans;
do
{
System.out.println("Welcome to the Menu!\nA)Guessing Game\nB)Calculator\n"
+ "\nEnter Letter: ");
String letter = s.next();
s.nextLine();
if ((letter.equals("A")) || (letter.equals("a")))
{
guessingGame();
}
else
{
calcDecide();
}
System.out.println("\nWould you like to go back to the menu or exit?\n"
+ "Press 'Y' yes or 'E' for exit: ");
ans = s.next();
s.nextLine();
}while (ans == "y" || ans == "y");
s.close();
}
Not sure why this was marked as a duplicate. I feel that people don't read the entire thing and like to assume this. This WAS NOT a simple String mess-up(That's part of the mistake,) but there's a bigger issue here, which I believe to be the scanner

ArrayIndexOutOfBoundsException when putting strings split from an array into 3 others [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
Here is my code:
for (int i = 0; i < 99; i++)
{
String inputString = keyboard.next();
String[] inputArray = inputString.split(":");
if (inputString.equals("quit"))
System.out.println("You have quit");
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
So here is my code, I'm trying to test out arrays and I need to get input from the user split using the delimiter ":"
I had to parseInt the last two arrays (as they are taking in integer values) to get the split input from the second and third index of the inputArray.
I have the last part of the code to test if it works, and it does but when I type in "quit" to end the loop it throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
I have searched and understood the issue but don't know how to avoid it. Sorry if I'm not explaining my issue, would appreciate another working solution. Thanks in advance for help
The string "quit" does not contain any ":" characters, so the result of inputString.split(":") is an array with a single element. So as soon as you try to access inputArray[1], you will have the exception, because index 1 refers to the 2nd element in the array, although this array has only one element
if (inputString.equals("quit")) {
System.out.println("You have quit");
return; // add this line
}
Add the return statement (shown above), and this will by pass the code problematic code. It seems like the right thing to do anyways, as the user is asking to quit the program.
Access inputArray only till its length i.e use inputArray.length() first to find array length then access array elements from 0 to length -1.
Most evident case from your code is when you enter quit but other inputs might cause it too since your are not checking length of array i.e. if length of splitted array is less that 3 for whatever input , you will receive this exception.
The issue you are running into is that the code accessing the inputArray variable is run regardless of whether or not the quit command is received. You have two options here.
1) Return on the quit command (recommended)
if (inputString.equals("quit")) {
System.out.println("You have quit");
return; // This will avoid running the code below
}
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
2) Throw the remaining code in an else case
if (inputString.equals("quit")) {
System.out.println("You have quit");
} else {
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
}
I would also recommend adding an error case if the inputArray doesn't end up being the expected length.
if (inputArray.length != 3) {
System.out.println("That's weird. I was expecting 3 parameters, but only found " + inputArray.length);
return;
}
you can use Scanner class to read the input.
Scanner scanner = new Scanner(System.in);
for(int i=0; i<Noofiterations; i++){ //iterations are the no.of times you need to read input.
String[] inputArray = scanner.nextLine().split(":");
//rest of the code is same as yours.
}
Input should be in the form "abc:123:334:wet"
Hope this helps. Let me know if i didn't get your question.

Scanner and for loop [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I'm working on a piece of code and I'm trying to initialize a vector. However, the code somehow skipped through the first one and initialized a blank to my vector. Anyone knows why? Here's a snippet of my code:
public class Test{
private Vector<String> vecStr;
public void run(){
vecStr = new Vector<String>();
System.out.println("How many strings do you want for your string vector?");
int numStr = keyboard.nextInt();
System.out.println("Enter your string values.");
for (int i=0;i<numStr;i++){
System.out.println(i + "Input");
vecStr.add(keyboard.nextLine());}
}
}
}
Let's say I input 4, somehow, the code gives me:
0
1
input:
2
input:
3
input:
It skipped the 0 one. Can someone please tell me why that happened? And if I were to display the Vector, it would give me : [ , blah, blah, blah]. How come there is a blank at the first element?
Scanner doesn't work on a line basis, but token basis. So, after your first nextInt() (for numStr) the scanner's cursor stays at the end of the input line (not start of next line). Therefore, first nextLine() execution right after that results in empty string. Subsequent calls to nextLine() then works correctly.
You can use input stream readers:
Vector<String> vecStr = new Vector<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many strings do you want for your string vector?");
int numStr = Integer.parseInt(reader.readLine());
System.out.println("Enter your string values:");
for (int i=0;i<numStr;i++){
System.out.println(i + " Input: ");
vecStr.add(reader.readLine());
}
System.out.println("vector contains:");
System.out.println(vecStr);

Java is skipping a line (Strings in a Scanner ??) [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am learning Java, and I'm not very far into it, and I don't know why but Java seemed to skip a line. I don't think the code from all my pages is really neccesery so I will just put the first page and the result I get when using it. Thanks!
import java.util.Scanner;
public class First {
public static void main(String args[]){
Scanner scanz = new Scanner(System.in);
System.out.println("Hello, please tell me your birthday!");
System.out.print("Day: ");
int dayz = scanz.nextInt();
System.out.print("Month: ");
int monthz = scanz.nextInt();
System.out.print("Year: ");
int yearz = scanz.nextInt();
System.out.println("Now, tell me your name!");
System.out.print("Name: ");
String namez = scanz.nextLine();
Time timeObject = new Time(dayz,monthz,yearz);
Second secondObject = new Second(namez,timeObject);
System.out.println("\n\n\n\n\n" + secondObject);
}
}
It skips the line
String namez = scanz.nextLine();
Console output: (excuse the birthday bit, it is other stuff)
Hello, please tell me your birthday!
Day: 34
Month: 234
Year: 43
Now, tell me your name!
Name:
My name is and my birthday is 00/00/43
It doesn't give you a chance to give a name, it just skips straight past and takes the name as null. Please, if anyone could, tell me why! I want to learn Java, and this little annoyance is standing in my way.
Thanks!
The problem is that the nextLine gets any characters on the line, and the \n (newline character) is left over from the scanner inputs above.
So instead of letting you enter something new, it takes the \n as the input and continues.
To fix, just put two scanners back to back like this:
System.out.print("Name: ");
scanz.nextLine();
String namez = scanz.nextLine();
Just using:
String namez = scanz.next();
will work too, but will limit the names to be one word. (aka first name only)
I believe the intended use of nextLine is correct. The problem however is that nextInt does not create a newline token, and it's instead reading the rest of that line (which is empty). I believe that if another nextLine statement would be added after that, the code would work. Next on the other hand only recognizes the first word so that might not be the correct solution.

Categories