Ok, so I can't seem to get this to work, though many people have told me the syntax and logic is correct. Can anyone reveal for me what I could possibly be doing wrong?
public Scanner in = new Scanner(System.in);
public void movePlayer() {
System.out.print("move: ");
String str = in.nextLine();
in.nextLine();
char c = str.charAt(0);
if (c == 'l' || c == 'L') {
player.moveLeft();
}
}
The program gets caught at char c = str.charAt(0);
And I am being returned this error:
java.lang.StringIndexOutOfBoundsException:
String index out of range: 0 (in java.lang.String)
you did not input anything though the console, so str is empty. this is the reason why chatAt(0) throw an exception
You don't want to use nextLine(). You want to use next().
String str = in.next();
This is the Javadoc for nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
You want next() instead:
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.
This will stop you from consuming the empty line and raising an exception.
This means that str is empty. You should check if it is not null and not empty.
if (str != null && !str.isEmpty()) {
...
}
Add a check for Empty String and Null as well . You will avoid a lot of headaches.
If you press Enter key in console, Scanner will be considered a complete line, regardless of whether or not there is text entered.
Press Enter at the beginning of a line, returns a String "" to the method Scanner.nextLine().
Add a check with str.lenght () > 0 before str.charAt(0).
Use in.next() instead. For whatever reason, nextLine() doesn't work with CharAt() sometimes.
Related
try {
string = scan.nextLine().charAt(0);
} catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}
I am trying to use this code for handling exception for the string that i am getting from a text file. But i get an error saying try to change the actual string declaration to character. I am not sure how to handle this ?
But i get an error saying try to change the actual string declaration to character.
scan.nextLine().charAt(0) is a char so if string is a String (as implied by the compilation error you got), you can't assign a char to it.
If you need just the first character of the input line, you should store it in a char variable.
char first;
try {
first = scan.nextLine().charAt(0);
} catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}
Of course you can avoid the need to catch this exception if you test the length of the String before getting its first character :
char first;
String line = scan.nextLine();
if (line.length() > 0)
first = line.charAt(0);
else
System.out.println("invalid input");
Your compilation error is because String.charAt() returns a char, not a String. They're different types - and you need to be very clear about the difference between them. You could just change the variable to a char variable, renaming it at the same time - but that's a really bad way of checking whether or not a string is empty. Deliberately provoking an exception like this when you can just test it directly is a bad idea - any time you find yourself catching a specific RuntimeException, you should ask yourself whether there's a better way of avoiding it.
You should use String.isEmpty() or String.length() before trying to take the first character of it. For example:
String line = scan.nextLine();
if (line.isEmpty()) { // Or line.length() == 0
// Whatever you want to do for invalid input.
} else {
char firstChar = line.charAt(0);
// Use firstChar
}
Of course, if you don't actually need the first character, and you were just trying to detect empty strings, you can just use the first part of this, without the else.
The method charAt() as the name indicates returns character. So the compilation error was because you are trying to assign a character to the variable (in your case, string) of type String.
If your objective is to retrieve the next line from scanner object and check it's 0th index for character to look for exception, you can do something like below:
String string = null;
..
char c;
string = scan.nextLine();
try {
c = string.charAt(0);
} catch (StringIndexOutOfBoundsException siobe) {
//Exception handling
}
This way, you can continue to use the string that was read using nextLine() prior to the exception happened due to the call of charAt().
Hope this helps.
I want to make a command line, just to run basic commands. So far, I've made it so that people can tell the program their name. When I don't enter a name, however, it treats it as if I did. Here is my class:
public static void main(String args[])
throws IOException
{
int a = 1;
do
{
System.out.print("$$: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String wtt = null; // wtt = what they typed!
wtt = br.readLine();
if(wtt == null)
{
System.out.println("Why wont you tell me your name!");
}
else
{
System.out.println("Thanks for the name, " + wtt);
}
}
while(a == 1);
}
Here is the output
$$: well
Thanks for the name, well
$$: hole
Thanks for the name, hole
$$:
Thanks for the name,
Why does it not work?
Calling readLine() on a BufferedReader will only return null on end of input. Here, the input hasn't ended, you've just entered an empty line, so "" (the empty string) is the result.
You will need to end the input stream, usually with Ctrl-C. Then you'll get "Why wont you tell me your name!". But then you'll need to break out of your infinite loop.
use this
if (wtt == null || wtt.trim().length() == 0)
Try
wtt.length()==0
instead of checking for null
It's because although you set the string to null at first, you are then setting it to br.readLine() which will have a line to read even though the user didn't type anything before hitting enter, so it will set the string to an empty string.
You should also (or instead) compare your string to "" (an empty string) to see if they entered anything.
You should compare wtt to "" as well to make sure the line isn't empty.
if (wtt == null) {
becomes
if (wtt == null && !!("".equals(wtt))) {
Instead of comparing wtt to null, compare it to empty string:
if ("".equals(wtt))
{
System.out.....
}
readLine method doesn't give you end of line characters (e.g. \n, \r). So, you cannot expect the loop to exit when you press just enter without entering anything. You can use read method instead to read characters and determine if there was a new line character or use Scanner class which seems to me better suitable in your situation.
Sorry if the title made no sense but I did not know how to word it.
The problem:
I'm making a multiple choice quiz game that gets either a, b, c or d from the user. This is no problem if they do as they are told, however if they don't type anything and just hit enter I get a StringIndexOutOfBoundsException. I understand why this is happening, but I'm new to Java and can't think of a way to fix it.
What I have so far:
System.out.println("Enter the Answer.");
response = input.nextLine().charAt(0);
if(response == 'a')
{
System.out.println("Correct");
}
else if(response == 'b' || response == 'c' || response == 'd')
{
System.out.println("Wrong");
}
else
{
System.out.println("Invalid");
}
Of course the program will never make it past the second line of code if the user types nothing, because you can't take the charAt(0) value of an empty String. What I'm looking for is something that will check if the response is null, and if so ask go back and ask the question to the user again.
Thanks in advance for any answers.
You can use a do-while loop. Just replace
response = input.nextLine().charAt(0);
with
String line;
do {
line = input.nextLine();
} while (line.length() < 1);
response = line.charAt(0);
This will continue to call input.nextLine() as many times as the user enters a blank line, but as soon as they enter a non-blank line it will continue and set response equal to the first character of that non-blank line. If you want to re-prompt the user for the answer, then you could add the prompt to the inside of the loop. If you want to check that the user entered a letter a–d you could also add that logic to the loop condition.
Either handle the exception(StringIndexOutOfBoundsException) or break this statement
response = input.nextLine().charAt(0);
as
String line = input.nextLine();
if(line.length()>0){
response = line.charAt(0);
}
Exception Handling:
try{
response = input.nextLine().charAt(0);
}catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}
Simple:
Get the input initially as a String, and put it into a temporary String variable.
Then check the String's length.
then if > 0 extract the first char and use it.
In addition #HovercraftFullOfEels' (perfectly valid) answer, I'd like to point out that you can "catch" these exceptions. For example:
try {
response = input.nextLine().charAt(0);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("You didn't enter a valid input!");
// or do anything else to hander invalid input
}
i.e. if a StringIndexOutOfBoundsException is encountered when executing the try-block, the code in the catch-block will be executed. You can read more about catching and handling exceptions here.
StringIndexOutofBoundException will occur in the following situation also.
Searching a string which is not available
Match with the string which is not available
for ex:
List ans=new ArrayList();
temp="and";
String arr[]={"android","jellybean","kitkat","ax"};
for(int index=0;index < arr.length;index++ )
if(temp.length()<=arr[index].length())
if(temp.equlsIgnoreCase((String)arr[``index].subSequence(0,temp.length())));
ans.add(arr[index]);
the following code is required to avoid indexoutofboundexception
if(temp.length()<=arr[index].length())
because here we are cheking the length of src string is equal or greater than temp .
if the src string length is less than it will through "arrayindexoutof boundexception"
Im trying to go on a loop while the input file has a string on the following line but im getting an error. Any idea why?
while( !((input = in.nextLine()).equals(""))){
...
}
Output:
Enter file name: input1.txt
evil live
Exception in thread "main" This is a palindrome
level
This is a palindrome
dog
Not a palindrome
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at Palindrome.main(Palindrome.java:41)
Your code is not correct, because it is possible that the input would end without providing an empty line. You should check if a line is available before checking it for being empty:
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){
...
}
There is no line after the end of file. When the last line is read the next call to nextLine() will fail. Use hasNextLine() to protect against this.
in.nextLine() is probably returning a null, which is being assigned to input, which you are trying to invoke equals on.
Use hasNextLine (documentation here) to make sure you can get the next line.
The way your loop is setup, it will never reach a "" string because it will hit the end of the file before doing so. it should be something like
while (input.hasNextLine()) {
...
}
This means that it will continue until the file has no next line.
Compare against null as well to check against End-Of-File
as
while(((input = in.nextLine())!= null) && !(input.equals(""))){
Or try:
while(in.hasNextLine(){
input = in.nextLine();
if(input != null && !(input.equals(""))){
........
}
}
Try to use this type of thing, catching the exception if needed:
input = in.nextLine();
while( !(input.equals(""))){
...
}
and if it throws an error, then set up a try...catch loop
May be you need,
while(in.hasNextLine()){
input = in.nextLine();
}
Scanner throws an exception when it runs out of input. You seem to be thinking that it will return a zero-length string.
Are you using Scanner to read a file a line at a time? That's not what it's for. You may want to look at BufferedReader.
I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?
I tried:
while (scanner.hasNext()) {
// process input
}
But that will get me stuck in the loop
Here's a way:
Scanner keyboard = new Scanner(System.in);
String line = null;
while(!(line = keyboard.nextLine()).isEmpty()) {
String[] values = line.split("\\s+");
System.out.print("entered: " + Arrays.toString(values) + "\n");
}
System.out.print("Bye!");
From http://www.java-made-easy.com/java-scanner-help.html:
Q: What happens if I scan a blank line with Java's Scanner?
A: It depends. If you're using nextLine(), a blank line will be read
in as an empty String. This means that if you were to store the blank
line in a String variable, the variable would hold "". It will NOT
store " " or however many spaces were placed. If you're using next(),
then it will not read blank lines at all. They are completely skipped.
My guess is that nextLine() will still trigger on a blank line, since technically the Scanner will have the empty String "". So, you could check if s.nextLine().equals("")
The problem with the suggestions to use scanner.nextLine() is that it actually returns the next line as a String. That means that any text that is there gets consumed. If you are interested in scanning the contents of that line… well, too bad! You would have to parse the contents of the returned String yourself.
A better way would be to use
while (scanner.findInLine("(?=\\S)") != null) {
// Process the line here…
…
// After processing this line, advance to the next line (unless at EOF)
if (scanner.hasNextLine()) {
scanner.nextLine();
} else {
break;
}
}
Since (?=\S) is a zero-width lookahead assertion, it will never consume any input. If it finds any non-whitespace text in the current line, it will execute the loop body.
You could omit the else break; if you are certain that the loop body will have consumed all non-whitespace text in that line already.
Scanner key = new Scanner(new File("data.txt"));
String data = "";
while(key.hasNextLine()){
String nextLine = key.nextLine();
data += nextLine.equals("") ? "\n" :nextLine;
}
System.out.println(data);
AlexFZ is right, scanner.hasNext() will always be true and loop doesn't end, because there is always string input even though it is empty "".
I had a same problem and i solved it like this:
do{
// process input
}while(line.length()!=0);
I think do-while will fit here better becasue you have to evaluate input after user has entered it.