nextLine().charAt(0) inside a switch statement - java

I'm making a very basic calculator program and ran into a problem that's baffled my mind the entire time.
Code:
switch(operation){
case 'a':
case 'A':
addition(n);
operation = n.nextLine().charAt(0);
break;
When I run the program and enter either characters (proceeding code uses Scanner object n to determine which char I type in), the method addition(n) works as intended. Basically the switch statement is inside a while loop so that it executes until I enter 'E', and the 5th line in the code I have above will change the char operation so that it does not execute the addition switch block over and over. The 5th line operation = n.nextLine().charAt(0); will give me an error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
Why is it giving me this error? What troubles my mind more is my default inside the switch is structured similarily yet the exact same code will work for it.
default:
System.out.println("Invalid entry. Refer to above menu and input"
+ " your choice of operation.");
operation = n.nextLine().charAt(0);
break;
Many thanks for your time.
EDIT: If I comment out the method addition(n), the 5th line will work as fine, allowing me to change my char operation. Why is the 4th line responsible for this?

Please use n.next().charAt(0) instead of n.nextLine().charAt(0). I think beacuse our task is to read the first character why should I consider a whole line of text may contain many words, spaces, special characters etc. , while I can get the first character from the first word and it is efficient, that's why java does not allow. :)
Welcome !

Related

Im looking to ask for user input, but instead, my code returns me back to the beginning without giving the chance to enter input

so, i am looking to write code which firstly asks for user input in order to run the desired operation, this element of my code is working fine, but after selecting one of the options from the first menu i am asking the user for a second string input which i would like to turn to both lower and uppercase, but instead of letting me enter an input, the program just goes back to the original screen showing all options.
this is my code asking for a string input that isnt working:
else if(choice1==1)
{
System.out.println("================================="+"\n"+"You have chosen to convert a given string to upper case and lowercase, please enter your string: "+"\n");
choice2 = sc.nextLine();
System.out.println("Your lowercase string: "+choice2.toLowerCase()+"\n"+"Your uppercase string: "+choice2.toUpperCase);
}
Cheers for the help guys!!
You need to consume the end of line character:
choice1 = sc.nextInt();
sc.nextLine(); // consume the end of line
// Now your program continues as before.
// Probably you have an 'if' here, I don't know, you
// haven't shown it

Java Program skips over user input using the Scanner class and print statements

I have never encountered a problem of this sort before, but three of my latest projects are all having this same problem where, for some reason, Java is skipping over the user's input. Whatever help is offered would be much appreciated!
Note: Just to give some background for this problem, the program is supposed to run a game in a do-while loop. After the first round is complete, the purpose of these lines of code is to allow the user to play more rounds of the game. It stores the user's input in a String and then takes the first character. If the character is 'y' or 'Y', then another round will begin. If the character is not either 'y' or 'Y', the program will end.
int iterations = 0;
do{
System.out.println(result + " Would you like to play again:");
String strHolder = keyboard.nextLine();
char repeatOption = strHolder.charAt(0);
iterations++;
} while(repeatOption == 'y' || repeatOption == 'Y');
So the game itself runs fine, but when I get to this part of the program that asks the user if he would like to play again, this happens in my terminal:
Would you like to play again:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
So, as you can see, the program skips over user input, and there is no "first character" to set the char repeatOption. Again, thanks for taking the time to read this problem, and any support would be much appreciated.
Scanner buffer was not empty (probably new line char was there) and when your programme was trying to get input from user, scanner was insntly getting value from buffer and nextLine() method did not return anything.
Possible solutions:
change nextLine() to other method that not consume the new line char (\n)
flush the buffer before getting value from user

java calculator randomly outputted line

So I've just started java with a tiny bit of experience from a few other languages. I tried to make this basic calculator and had a lot of problems but managed to resolve most of them. The last thing that I can't seem to understand is a randomly triggered "This is an invalid input", every time my program runs once. "..." refers to irrelevant code. Everything else seems to work fine. Thanks in advance!
import java.util.Scanner;
public class Calc {
...
System.out.println("Would you like to use the calculator?(Y/N)");
while(use){
String usage=in.nextLine().toLowerCase();
if(usage.equals("n")){use=false;}
//input
//operations
else if(usage.equals("y")){
...(calculator code)
System.out.println("Continue use? (Y/N)");
}
else {System.out.println("That is not a valid input");}
}
}
}
After running my code a few times, my output is
Would you like to use the calculator?(Y/N)
Y
Please input an operation: +,-,*,/,%, ^, or root
+
Calculator: Please input your first number.
1
Now enter your second number.
2
Calculating
3.0
Continue use? (Y/N)
That is not a valid input <-- right there is the confusing part, why is that triggered?
Y
Please input an operation: +,-,*,/,%, ^, or root
Full code is on pastebin, if you somehow need it. http://pastebin.com/Qee2Hxe3
I checked the full code, and right before the loop first reiterates, there is a call to in.nextDouble(), this method reads a double but does not consume the line end, which makes the next in.readLine() return \n immidiately and the succeeding test fails.
A simple solution is to manually consume the line-end:
System.out.println(ans);
System.out.println("Continue use? (Y/N)");
in.nextLine();
I tested your code and found that a solution is to declare your scanner inside your while loop, like so:
while (use) {
Scanner in = new Scanner(System.in);
String usage = in.nextLine().toLowerCase();
Here's what the problem is: first, you are entering your while loop, and usage is set equal to in.nextLine(). Since there is no next line, it waits for you to enter one. You enter yes, after which you enter your formula. Then it returns the answer, and goes back to the top of the while loop. Once again, usage is set to equal in.nextLine, but there is already a next line (a blank one) and so usage is set to equal an empty String ("") which is neither "y" or "n". Then it immediately goes to the "else" option at the end and prints the "invalid" message.
Re-assigning your scanner through each iteration of your while loop fixes this problem.
The last input you read in your code when calculating is this:
num2=in.nextDouble();
This reads the next characters and convert it to a double. However when you input your number, you also hit enter.
This means that after the double is read, there is still a newline character left in the input buffer.
As the code goes back to the String usage=in.nextLine().toLowerCase(); , you will now read this newline.
You could just ignore empty input, by e.g. doing
String usage=in.nextLine().toLowerCase().trim();
if (usage.isEmpty()) {
continue;
}

Print string up to a certain word - Java

I was wondering in Java how I could print a string until it reaches the word "quit" in that string and then instantly stop printing at that point. For instance if the string value was:
"Hi there this is a random string quit this should not be printed"
All that should be printed is "Hi there this is a random string".
I was trying something like this, but I believe it to be wrong.
if ( input.indexOf( "quit" ) > -1 )
{
//code to stop printing here
}
Instead of thinking about the problem as "how to stop printing" (because once you start printing something in Java it's pretty hard to stop it), think about it in terms of "How can I print only the words up to a certain point?" For example:
int quit_position = input.indexOf("quit");
if (quit_position >= 0) {
System.out.println(input.substring(0, quit_position));
} else {
System.out.println(input);
}
Looks like homework, so this answer is in homework style. :-)
You're on the right track.
Save the value of that indexOf to an integer.
Then it's like you have a finger pointing at the right spot - ie, at the end of the substring you really want to print.
That's a hint anyway...
EDIT: Looks like people are giving it to you anyway. But here are some more thoughts:
You might want to think about upper and lower case as well.
Also consider what you are going to do if 'quit' is not there.
Also the solutions here don't strictly solve your problem - they'll print unnecessary spaces too, after the last word ends, before 'quit' starts. If that is a problem you consider String Tokenization or an adapation of the replaceAll solution above to cover for leading whitespace into `quit'.
This has a one-line solution:
System.out.println(input.replaceAll("quit.*", ""));
String.replaceAll() takes a regex to match, which I've specified to be "the literal 'quit' and everything following", which is to be replaced by a blank "" (ie effectively deleted) from the returned String
If you don't mind trailing spaces in your string
int index = input.indexOf("quit");
if (index == -1) index = input.length();
return input.substring(0, index);

Java - nextLine(); within a switch statement

I have a switch statement acting as a menu, in this I am trying to read the users input. Currently I am using variable=in.next(); and this works. However it will only read one word and at points the user may need to enter more, so I tried using variable=in.nextLine();, which compiles, but when I run the program, I select my choice from the menu, and it skips the reading in and return to the menu.
Any help would be appreciated, thanks :)
Just use:
name=in.nextLine();
and
String choice = in.nextLine();
This should be in the constructor, and at the top of runApp.
That way, you're not leaving the new line in the buffer (where it will be used for e.g. dp).
You should have:
dp=in.nextLine();
as described in your question.
You either have to strip the newline character \n from the user input or assume it's there in your switch statement.
Pretty much because you decided to use nextLine() the user input to the computer will look like this
f\n
So just compare the strings accordingly!
OK I think I am too inept at Java and have put my question badly.
When I take the users input it takes only 1 word, I want it to take everything they put basically, and when I use nextLine, this just skips the reading and takes me back to selecting a choice.
Switch selector can be only integer, short, char or enum. String cannot be used as a switch selector.
If I understood you correctly you would like to control your flow using words entered by user. If you have predefined list of words I'd suggest you to use enum:
enum Words {
start, stop, beep,
}
Now user enters a word beep. You can say:
Words command = Words.valueOf();
///
switch (command) {
case start: /* start something */ break;
case stop: /* stop something */ break;
case beep: /* beep!!! */ break;
default: throw new IllegalArgumentException("Unknown command " + command);
}

Categories