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.
Related
This is my current error handling function:
public void yyerror(String error) {
System.err.println("Error: "+ error);
}
This is the default error function I found on the BYACC/J homepage. I can't find any way to add the line number. My question is similar to this question. But the solution to it doesn't work here.
For my lexer I am using a JFlex file.
It's not that different from the bison/flex solution proposed in the question you link. At least, the principle is the same. Only the details differ.
The key fact is that it is the scanner, not the parser, which needs to count lines, because it is the scanner which converts the input text into tokens. The parser knows nothing about the original text; it just receives a sequence of nicely-processed tokens.
So we have to scour the documentation for JFlex to figure out how to get it to track line numbers, and then we find the following in the section on options and declarations:
%line
Turns line counting on. The int member variable yyline contains the number of lines (starting with 0) from the beginning of input to the beginning of the current token.
The JFlex manual doesn't mention that yyline is a private member variable, so in order to get at it from the parser you need to add something like the following to your JFlex file:
%line
{
public int GetLine() { return yyline + 1; }
// ...
}
You can then add a call to GetLine in the error function:
public void yyerror (String error) {
System.err.println ("Error at line " + lexer.GetLine() + ": " + error);
}
That will sometimes produce confusing error messages, because by the time yyerror is called, the parser has already requested the lookahead token, which may be on the line following the error or even separated from the error by several lines of comments. (This problem often shows up when the error is a missing statement terminator.) But it's a good start.
I have hit a road block in a program I am writing in Java. The program basically copies folders and files from multiple locations into one folder to make backing up code from multiple locations on my computer easier. The problem I have is that I don't want to copy specific folders, in this case "workspace/.metadata". The start of the code I am having issues with is below:
public void copyFolder(File in, File out, String loc)
throws IOException{
String check = in.getName().substring(1);
System.out.println("loc:"+loc+"check: "+check);
if(loc.equals("java")){
if(check.equals("metadata")){
System.out.println("failboat");
//statusBox.append("failboat");
}
}
And this is the result I see:
loc:java
check: orkspace2
loc:java
check: metadata
loc:java
check: lock
I've had other's look at the code and they agree it should work. I've even created a replica of the code in a test file:
String test = "fmetadata";
String loc = "java";
String check = test.substring(1);
if(loc.equals("java")){
if(check.equals("metadata")){
System.out.print("failboat");
}else{
System.out.println("WTF");
System.out.print(test+ ": :"+check);
}
}
And the result?
failboat
There is a dent in my desk the size of my forehead from trying to figure this out.
If that output you posted is the actual output:
loc:java
check: orkspace2
loc:java
check: metadata
loc:java
check: lock
It does not match the code you've pasted, as you do not print a newline between the two items:
System.out.println("loc:"+loc+"check: "+check);
If this is truly what you are seeing with that code then I would say the problem is that loc has a stray newline at the end, and is actually "java\n" rather than "java" as you expect. So you should go back and examine how you generate the value you pass through loc to begin with before calling that function.
If this is the case, some suggestions for diagnostics improvements that could help you notice these kinds of issues sooner (in addition to stepping through with a debugger):
// quote your strings to spot whitespace, print length to spot unexpected
// unprintable characters.
System.out.println("loc: \""+loc+"\" "+loc.length());
System.out.println("check: \""+check+"\" "+check.length());
And:
if(loc.equals("java")){
// make sure you're getting to this point, don't assume that the first
// if condition was satisfied:
System.out.println("grumpycat"); // <----
if(check.equals("metadata")){
System.out.println("failboat");
}
}
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"));
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 ...)
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.