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.
Related
Write a program that asks a user to input a string. Then asks a user to type in an index value(integer). You will use the charAt( ) method from the string class to find and output the character referenced by that index. Allow the user to repeat these actions by placing this in a loop until the user gives you an empty string. Now realize that If we call the charAt method with a bad value (a negative value or a integer larger than the size of the string) an exception will be thrown. Add the code to catch this exception, output a warning message and then continue with the loop
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
System.out.println("");
String s;
int ind;
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
s=sc.next();
if(s.length()==0)
break;
ind=sc.nextInt();
try {
char ch=s.charAt(ind);
System.out.println("Character is "+ch);
}
catch(Exception e) {
System.out.println("Bad index Error!");
}
}
}
}
Yes. You could rely on assignment evaluating to the assigned value. Also, call Scanner.hasNextInt() before calling Scanner.nextInt(). Like,
System.out.println();
String s;
Scanner sc = new Scanner(System.in);
while (sc.hasNext() && !(s = sc.next()).isEmpty()) {
if (sc.hasNextInt()) {
int ind = sc.nextInt();
try {
char ch = s.charAt(ind);
System.out.println("Character is " + ch);
} catch (Exception e) {
System.out.println("Bad index Error!");
}
}
}
There is a bug; sc.next() cannot return an empty string in this code. Try editing it this way:
while(sc.hasNext()) {
s = sc.next();
if(s.length() == 0) {
System.out.println("Woah, Nelly!");
break;
}
// ...
}
See if you can get the program to print "Woah, Nelly!" by entering a blank line, or anything else. I can't, and assuming I understand the documentation correctly, it is impossible for the if condition to ever be true here (emphasis mine):
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\s" could return empty tokens since it only passes one space at a time.
This pattern "\\s+" is the default one, and you haven't set a different one, so your scanner should never return an empty token. So the strict answer to "is there a way to write this program without the break statement?" is: yes, you can just delete the if(...) break; code and it doesn't change the behaviour in any way.
However, that's not really a solution to your problem because it doesn't give the user a way to exit the program. You should use nextLine() instead of next() to allow reading a blank line from the user.
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"
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.
I've been trying different methods for converting a user string input into an int I could compare and build an "if-then" statement. Every time I tried testing it, it just threw exception. Can anyone look at my Java code and help me find the way? I'm clueless about it (also a noob in programming). If I'm breaking any rules please let me know I'm new here. Thank you.
Anyway, here is the code:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
It seems like you are trying to convert the string (which should be a single character, Y or N) into its character value, and then retrieve the numerical representation of the character.
If you want to turn Y or N into their decimal representation, you have to perform a cast to int:
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i; //The important part
System.out.println(integerChar);
This will return the integer representation of the character that the user input. It may also be useful to call the String.toUpperCase() method in order to ensure that different inputs of Y/N or y/n do not give different values.
However, you could also do an if-else based upon the character itself, rather than converting it to an integer.
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
//Handle yes
} else if (i == 'N') {
//Handle no
} else {
System.out.println("You've mistyped the answer.");
}
I think you meant to ask them to Enter 0 for yes and 1 for No ? Maybe?
You're asking the user to type Y or N and then you're trying to parse that to an integer. That will always throw an exception.
EDIT -- As others have pointed out, if you want to continue to use Y or N, you should do something along the lines of
String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}
parseInt is just for converting text numbers into integers: everything else gets a NumberFormatException.
If you want the decimal ASCII value of a character, just cast it to an int.
Use if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) { instead.
Or (as Mark pointed) if (addNewUser.toLowerCase().startsWith("y")) {.
BTW maybe look at Apache Commons CLI?
You cannot convert String to int, unless you know the String contains a valid integer.
Firstly, using the Scanner class for input is better, since its faster
and you don't need to get into the hassle of using streams, if you're
a beginner. This is how Scanner will be used to take input:
import java.util.Scanner; // this is where the Scanner class resides
...
Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y')
{ } // do something
else if(choice == 'N')
{ } // do something
else
System.err.println("Wrong choice!");
This code could also be shortened to one line (however you won't be
able to check a third "wrong choice" condition):
if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
{ } // do something
else // for 'N'
{ } // do something
Secondly, char to int conversion just requires an explicit type
cast:
char ch = 'A';
int i = (int)ch; // explicit type casting, 'i' is now 65 (ascii code of 'A')
Thirdly, even if you take input from a buffered input stream, you
will take input in a String. So extracting the first character from
the string and checking it, simply requires a call to the charAt()
function with 0 as a parameter. It returns a character, which can
then be compared to a single character in single quotes like this:
String s = in.readLine();
if(s.charAt(0) == 'Y') { } // do something
Fourthly, its a very bad idea to put the whole program in a try
block and catch Exception at the end. An IOException can be
thrown by the readline() function, and parseInt() could throw a
NumberFormatException, so you won't be able to handle the 2
exceptions separately. In this question, the code is small enough for
this to be ignored, but in practice, there will be many functions
that can throw exceptions, hence it becomes easy to lose track of exactly which function threw what exception and proper exception handling becomes quite difficult.