'String Index out of Range' Error Message in Java using charAt - java

Recently, while coding I came upon the following error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(String.java:686)
at TestAssign2.main(TestAssign2.java:119)
The error appears when I add the line - firstLetter=userName.charAt(0); to the code and program displays the error message after the user enters all the values asked. Before this line was entered, it all worked fine.
while(uProgStart.equals(PROGSTART))
{
System.out.println("What is your name?");
userName=sc.nextLine();
junk = sc.nextLine();
System.out.println("What is the year of your birth?");
birthYear = sc.nextInt();
junk = sc.nextLine();
System.out.println("What is the date of your birth? (dd.mm)");
birthDDMM = sc.nextDouble();
junk = sc.nextLine();
day=(int)birthDDMM;
month=(int)Math.round(100*birthDDMM)%100;
//Begins calculation of Dss Score
if(birthYear%CYCLE_LENGTH!=SNAKE_YEAR)
{
DssScore=DssScore+1;
}
if(month<SPRING_BEGINNING||month>SPRING_END)
{
DssScore=DssScore+2;
}
firstLetter=userName.charAt(0);
if(firstLetter==(LOWER_S)||firstLetter==(UPPER_S))
{
DssScore=DssScore+4;
}
The idea of the line was to see if the name entered by the user begins with either the letter 's' or 'S'.
All the variables have been declared, I just haven't included them for the sake of keeping this post a little succinct.

I think you are pressing enter key by mistake without giving a chance to enter any input and it forces username variable be empty. I reproduced this error like mentioned above.Sometime when you deal with scanner, it happens like that.
So in your code, check whether the username is null or not before doing any operation.

The call to sc.nextLine() for assigning userName prior to the charAt call likely returns an empty string (eg. if you scan a blank line).

You may want to use if to make sure that the next line really exists.
Something like this:
if(sc.hasNextLine()) {
userName = sc.nextLine()
} else {
System.out.println("OMG... Where is my line?")
}
This most likely not a good fix for your problem, but based on the limited information we have it's difficult to suggest anything better.
The real problem is most likely elsewhere in your logic.

Related

Java console input length limit

I have an interview task where I was given a text file with file.in format, the task said that my program should be using standard data input and output (I assume console). The input file goes something like this:
249089
439506849 989399339
773359725 989399094
33290819 989399230
771114928 989399164
823133180 989399164
615096154 989399094
340750872 989399164
41881535 989399230
637599407 989399339
510268939 989399506
46219619 989399544
221332387 989399659
236968778 989399824
902942034 989399945
936095694 989400101
**end to the line 249090**
The first number is the number of objects
The second is two numbers, but for the purpose of the task I only use the second one
For the purpose of parsing the numbers I use for loop and code below:
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)))
String line = bufferedReader.readLine();
System.out.println(line);
StringTokenizer stringTokenizer = new StringTokenizer(line, " ");//
stringTokenizer.nextToken();
int height = Integer.parseInt(stringTokenizer.nextToken());
I use IntelliJ build in console and when I paste into console i get like a couple thousands results in starting from the end, so the first number is wrong, and when i run my program i get Runtime Error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "84 995058150"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at pl.artur.Main.getNumberOfBuildings(Main.java:23)
at pl.artur.Main.main(Main.java:14)
Is there a way to get around it using standard input?
This has nothing to do with where the input comes from; as the stack trace shows, the exception is thrown by the Integer.parseInt method on the string "84 995058150". This string clearly does not represent a (singular) integer. If the StringTokenizer.nextToken method returns this string, then it is StringTokenizer that's the problem. As David Conrad notes in the comments, the documentation says:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
The String.split method will split line into the two parts, so you can then call Integer.parseInt on the part you want:
String line = bufferedReader.readLine();
String[] parts = line.split(" ");
int height = Integer.parseInt(parts[1]);
Ok, I resolved the issue.
The solution was to set the bigger buffer size for the console in IntelliJ settings:
I think you cannot convert or parse string including empty spaces between them to Integer.
// This string cannot be parsed to Integer directly.
// Because an empty space is included between `84` and `995058150`.
String s = "84 995058150";
If you want to parse this, you should use trim() method. example:
int intValue= Integer.parseInt(s.trim());
I hope this answer will be helpful for you.

Having an issue with exceptions regarding input from a .txt file

Hi I'm currently creating a program which will allow me to input the path of a .txt file with a format of:
Home Name : Away Name : Home Score : Away Score
Liverpool : Chelsea : 2 : 1
Spurs : Fulham : 1 : 1
and it should output into the console in order. However, I am having trouble with my exceptions. I am trying to get it to display so that if either parameter is missing such as the delimiter, team name/score is missing it will output an error to the console. I want it so that it will display all missing parameters and not just one. For example, Home team name is missing. Away team name is missing. No field delimiter. Invalid home score, check it is a whole number.
Any help is highly appreciated. Thanks!
The current code which I have now is:
The error is cause the first line of your file is a header
Home Name : Away Name : Home Score : Away Score
And when you will try to parse the splitted text into int, it will failed to parse and will throw an error at the following line in your code
int homeScore = Integer.parseInt(splitText[2].trim());
I hope this gives you a direction to find a solution to your question. Although it's quite difficult to 'guess' the issue as there isn't any error stacktrace.
If you want to display all errors you shouldn't use exceptions. Those are meant to be used in case something unexpected happens. Instead you should do checks like that splitText[0].length() == 0 etc. and collect all the errors. That being said, the ArrayIndexOutOfBoundsException could be replaced by a check for splitText.length < 4 (and of course the following checks need to take that into consideration as well).
That NumberFormatException could be an exception for that rule because you'd either have to check whether the string is a number and then try to parse it or just try it and catch the exception to know it isn't a number.
Your code could then look like this:
List<String> errors = new LinkedList<>();
if( splitText.length < 4) {
errors.add("Fields might be missing")
}
//do other checks here
//if all fields are present, check the numbers (this could be done in some method)
int homeScore = -1;
try {
homeScore = Integer.parseInt(splitText[2].trim());
} catch( NumberFormatException e) {
errors.add("Homescore is not an integer");
}
//other checks and then finally:
if( errors.isEmpty() ) {
//everything ok
} else {
//print the collected errors
}
Note that some checks don't make sense if others already failed, i.e. parsing away score doesn't make sense if the length of the array is smaller than 4 or if the 4th element is an empty string (at least after trimming). That would have to be taken into account.

Java Code User Input to System.out

Small programming question here.
I'm trying to get line 43
System.out.print("Please Enter the Manufacturer of Your Doughnut:");
user input to paste directly into line 46
System.out.print("Please Enter the Manufacturer of Your Doughnut:");
but my compiler keeps giving me this error:
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at Torus.main(Torus.java:46)
For example, if the user wanted to input that their doughnuts were from McDonald's, line 46 would automatically spit out McDonald's.
Well with input.nextDouble() the compiler is expecting a Double-Datatype. You need to get a string as manufacturer. I Think input.nextLine() should do it.
Change manufacturer type from double to String and then use:
manufacturer = input.nextLine();
If you need the manufacturer variable to store a name, it should be of type String not double.
Change your declaration to
String manufacturer;
and to accept input use
manufacturer=input.nextLine(); //returns String

Java - SecurityException in Method "printDuplicates"

I'm a newcomer to Java trying to submit a working project, in this instance printDuplicates. The instructions are as follows:
Write a method named printDuplicates that accepts as its parameter a Scanner for an input file containing a series of lines. Your method should examine each line looking for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively. Non-repeated tokens are not printed. Repetition across multiple lines (such as if a line ends with a given token and the next line starts with the same token) is not considered in this problem.
For example, if the input file contains the following text:
hello how how are you you you you
I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge
bow wow wow yippee yippee yo yippee yippee yay yay yay
one fish two fish red fish blue fish
It's the Muppet Show, wakka wakka wakka
Your method would produce the following output for the preceding input file:
how*2 you*4
I*3 Jack's*2 smirking*5
wow*2 yippee*2 yippee*2 yay*3
wakka*3
Your code prints only the repeated tokens; the ones that only appear once in a row are not shown. Your code should place a single space between each reported duplicate token and should respect the line breaks in the original file. This is why a blank line appears in the expected output, corresponding to the fourth line of the file that did not contain any consecutively duplicated tokens. You may assume that each line of the file contains at least 1 token of input.
Here is my code, pretty much ready for submitting.
import java.io.*;
import java.util.*;
Scanner input;
public static void printDuplicates(Scanner input) throws Exception {
String word = "";
String word2 = "";
input = new Scanner(new File("idontknowwhattodo.txt"));
while(input.hasNextLine()) {
Scanner line = new Scanner(input.nextLine());
int repeat = 1;
word = line.next();
while(line.hasNext()) {
word2 = line.next();
while(word.equals(word2)) {
repeat++;
if(line.hasNext()){
word2 = line.next();
} else {
break;
}
}
if(repeat!=1) {
System.out.print(word + "*" + repeat + " ");
}
repeat = 1;
word = word2;
}
System.out.println();
}
}
However, whenever I try to submit my project, it throws back this error:
(no output was produced!)
SecurityException on line 5:
You are not allowed to read the file /usr/share/tomcat7/temp/idontknowwhattodo.txt
java.lang.SecurityException: You are not allowed to read the file /usr/share/tomcat7/temp/idontknowwhattodo.txt
at java.io.FileInputStream.<init>(FileInputStream.java:135)
at java.io.FileReader.<init>(FileReader.java:72)
at Scanner.<init>(Scanner.java:330)
at printDuplicates (Line 5)
What does this mean? I have multiple working projects but I can't seem to submit them due to this one error. Any experts that can help me on this one? Thank you.
It looks like you are using Tomcat from your path. Tomcat requires special security permission to read or write files. This is a basic protection to prevent malicious code from accessing sensitive files on the OS. You can configure these directories or stick to reading and writing to the default ones:
https://tomcat.apache.org/tomcat-7.0-doc/security-manager-howto.html
Unable to add a comment because of reputation points so using the Answers section.
Agree with above comments, it is related to permissions.
Do an ls -ltr on /usr/share/tomcat7/temp/idontknowwhattodo.txt
Check whether the user (say myuser) with which you are running you java application has necessary permissions for /usr/share/tomcat7/temp/idontknowwhattodo.txt.
Two options below:
Give the user "myuser" the necessary permissions to the idontknowwhattodo.txt using chmod.
Or copy idontknowwhattodo.txt to a location where "myuser" has the permissions.
Problem description says that you're getting Scanner object as parameter. You don't have to recreate it, you're probably trying to submit your project to some online competition. Program on the server will load your class and call the method printDuplicates() with Scanner object as parameter, you don't have to worry about how it gets created. Just use it, and everything would be fine.
Just comment the scanner assignment line as below
String word = "";
String word2 = "";
/*input = new Scanner(new File("idontknowwhattodo.txt"));*/
while(input.hasNextLine()) {
...
As per instructions, you are already getting the Scanner object(which references the input file) as parameter to your method. So, you should not be re-initializing it.
This line should be removed:
input = new Scanner(new File("idontknowwhattodo.txt"));

how to fix a java.lang.NumberFormatException error where the desire input is string?

i'm using Jframe as my front-end for an inventory system i have developed. I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up
private String Eng_num, Chasis_num, make, model, year_of_car,capacity,description;
private Integer status,Sup_id;
public void actionPerformed(ActionEvent e)
{
Insert I = new Insert();
try
{
Chasis_num = textField_1.getText();
Eng_num = textField_9.getText();
year_of_car = textField_10.getText();
model = textField_11.getText();
make = textField_12.getText();
capacity = textField_14.getText();//error is at this line
description = textField_16.getText();
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
I.insertVehicle(Eng_num, Chasis_num, make, model, year_of_car, capacity, Sup_id, status, description);
}
I even try to put .toString and still getting the same error
capacity = textField_14.getText();
I don't think this is the cause of your exception.
java.lang.NumberFormatExceptionOnly occur when you try to parse String into any kind of Number.
So, i'm guessing, this exception was thrown somewhere you try to convert 6seater to Int or some other number format.
I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up.
The error is happening because you have tried to parse the characters 6seater as an integer. It isn't an integer. An integer consists of the characters 0 through 9, possibly with a - character at the front. Any other character, and the value will be rejected ...
(The problem is nothing to do with the type that getText() returns. The problem is the value that you are giving to the parseInt method. It is not clear where the parseInt call is. A stacktrace would answer that ... but you didn't provide one.)
Also, you say:
capacity = textField_14.getText();//error is at this line
Actually, it isn't. That line cannot possibly throw a NumberFormatException. In reality, the error could be happening at one of these lines:
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
or it could be happening within the the insertVehicle method that you are calling here:
I.insertVehicle(Eng_num, Chasis_num, make, model,
year_of_car, capacity, Sup_id, status, description);
I should also point out that you have made some egregious Java style errors in your code:
Java class, method or variable names should never contain _ as a separator. Use "camel case".
A Java variable name should never start with an uppercase letter.
(If you instructor doesn't deduct "style" marks for this, he/she should. If your code reviewers don't pick this up, they are not doing their job properly. If this code was intended to be delivered to a paying customer, they would have reason to complain about the code quality ...)

Categories

Resources