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");
}
}
Related
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.
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 ...)
I've some tags in a word file which looks like <tag>.
Now I get the content of the Word file with docx4j and loop through every line and search for this tag. When I find one, then i replace it with a String. But this code i tried doesn't work and now i really don't know how i can realise it!
Here's the code i've already tried:
WordprocessingMLPackage wpml = WordprocessingMLPackage.load(new File(path));
MainDocumentPart mdp = wpml.getMainDocumentPart();
List<Object> content = mdp.getContent();
String line;
for (Object object : content) {
line = object.toString();
if (line.contains("<tag>")) {
line.replace("<tag>", "<newTag>");
}
}
Any tips or solutions how i can achieve it?
One of your problems is that you modify String line which has no effect on anything. line.replace("<tag>", "<newTag>"); result of this operation is ignored. you would definitely want to do sth with that, right?
Also, if object in your loop is not an instaneOf String, then line and object are pointing to different objects.
You need to modify contents but not the way you're doing this. Please read getting started
Also there are lots of examples (sample code) in source code download section
If you have any concrete problems after reading the getting started, we'll be happy to help you.
The things in your List will be org.docx4j.wml.P (paragraphs), or Tbl (tables) or other block level content.
Paragraphs contain runs, which in turn contain the actual text.
For the suggested way of doing what you want to do, see the VariableReplace sample.
Better yet, consider content control data binding.
Otherwise, if you want to roll your own approach, see the Getting Started guide for how to traverse, or use JAXB-level XPath.
First you should use replaceAll() instead of replace().
Then you should store this String into an object you can serialize back after modification to the Word file.
Furthermore I think that it would also be good to handle closing tags (if there some) ...
String (line) is immutable, therefore replace("<tag>", "<newTag>") does not modify your line it creates a new modified one.
Your code shoudl do something like this:
for (Object object : content) {
line = object.toString();
if (line.contains("<tag>")) {
line= line.replaceAll("<tag>", "<newTag>");
}
writeLineToNewFile(line);
}
or shorter:
for (Object object : content) {
writeLineToNewFile(object.toString().replace("<tag>", "<newTag>");
}
I'm trying to implement a tool for merging different versions of some source code. Given two versions of the same source code, the idea would be to parse them, generate the respective Abstract Source Trees (AST), and finally merge them into a single output source keeping grammatical consistency - the lexer and parser are those of question ANTLR: How to skip multiline comments.
I know there is class ParserRuleReturnScope that helps... but getStop() and getStart() always return null :-(
Here is a snippet that illustrates how I modified my perser to get rules printed:
parser grammar CodeTableParser;
options {
tokenVocab = CodeTableLexer;
backtrack = true;
output = AST;
}
#header {
package ch.bsource.ice.parsers;
}
#members {
private void log(ParserRuleReturnScope rule) {
System.out.println("Rule: " + rule.getClass().getName());
System.out.println(" getStart(): " + rule.getStart());
System.out.println(" getStop(): " + rule.getStop());
System.out.println(" getTree(): " + rule.getTree());
}
}
parse
: codeTabHeader codeTable endCodeTable eof { log(retval); }
;
codeTabHeader
: comment CodeTabHeader^ { log(retval); }
;
...
Assuming you have the ASTs (often difficult to get in the first place, parsing real languages is often harder than it looks), you first have to determine what they have in common, and build a mapping collecting that information. That's not as easy as it looks; do you count a block of code that has moved, but is the same exact subtree, as "common"? What about two subtrees that are the same except for consistent renaming of an identifier? What about changed comments? (most ASTs lose the comments; most programmers will think this is a really bad idea).
You can build a variation of the "Longest Common Substring" algorithm to compare trees. I've used that in tools that I have built.
Finally, after you've merged the trees, now you need to regenerate the text, ideally preserving most of the layout of the original code. (Programmers hate when you change the layout they so loving produced). So your ASTs need to capture position information, and your regeneration has to honor that where it can.
The call to log(retval) in your parser code looks like it's going to happen at the end of the rule, but it's not. You'll want to move the call into an #after block.
I changed log to spit out a message as well as the scope information and added calls to it to my own grammar like so:
script
#init {log("#init", retval);}
#after {log("#after", retval);}
: statement* EOF {log("after last rule reference", retval);}
-> ^(STMTS statement*)
;
Parsing test input produced the following output:
Logging from #init
getStart(): [#0,0:4='Print',<10>,1:0]
getStop(): null
getTree(): null
Logging from after last rule reference
getStart(): [#0,0:4='Print',<10>,1:0]
getStop(): null
getTree(): null
Logging from #after
getStart(): [#0,0:4='Print',<10>,1:0]
getStop(): [#4,15:15='<EOF>',<-1>,1:15]
getTree(): STMTS
The call in the after block has both the stop and tree fields populated.
I can't say whether this will help you with your merging tool, but I think this will at least get you past the problem with the half-populated scope object.