I just finished an assignment for class and uploaded it to a website desgined to give the program the argument when uploaded and run. Since the site just shows your output and the coding goes "behind the scenes" just for the professor to read I cant see it actually running. I was wondering how I woud input an Args.txt file into netbeans so that I may know how to do it and test projects on my own in the future. Here is the output code for my file :
public static void main(String[] args){
In in = new In(args[0]);
Graph G = new Graph(in);
GraphProperties gp = new GraphProperties(G);
System.out.println("diameter: " + gp.diameter());
System.out.println("radius: " + gp.radius());
System.out.println("center: " + gp.center());
}
I tried putting it into properties but didn't get anywhere.
Thanks in advance!
Related
I have finished developing a big project I have been working on. I have usually done my own tests without Junit but my requirement is to use it now. All of my methods that I want to test are void and do not return anything, but print information depending on certain factors. So, I need to test these using the assertEquals method for Junit.
For example:
public void addContact(String firstName,String lastName,Person p) {
String key = firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase() + " ".concat(lastName.substring(0,1).toUpperCase() + lastName.substring(1).toLowerCase());
if(hasContact(key)){
System.out.println("\nCannot add user. User already exists. Try adding distinct name to diffentiate between users with the same name");
}
else{
this.contacts.put(key,p);
System.out.println("\nUser: " + key + " Successfully added");
}
}
This is one of the void methods I want to test from my AddressBook class, for now, I am testing to see if the user can be added so it should print \nUser: " + key + " Successfully added which it does.
Here in my JUNIT test class, I am trying to check this like so...
#Test
public void addContact(){
final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
Address a1 = new Address("grove","Waterford","Waterford","x9123r","0987654321");
Person p1 = new Person("Charlie","Ansell",a1);
System.setOut(new PrintStream(outContent));
ad1.addContact("Charlie","Ansell", p1);
assertEquals("User: Charlie Ansell Successfully added", outContent.toString());
}
The output from Junit is: expected:<[User: Charlie Ansell Successfully added]> but was <[User: Charlie Ansell Successfully added]>
My question is, why is this failing if they are showing the same output?
have you tried debugging it and looking at the difference?
My guess - missing \n both at the beginning (from your code) and the end (you are using println).
this should work:
assertEquals("\nUser: Charlie Ansell Successfully added\n", outContent.toString());
Despite content looks similar you have extra line breaks (\n) in your program that your did not include in your test.
Replace:
assertEquals("User: Charlie Ansell Successfully added", outContent.toString());
with:
assertEquals("\nUser: Charlie Ansell Successfully added\n", outContent.toString());
Okay, so I have just discovered the answer.
I added the .trim() function at the end of the expected object and actual object. so my new code looks like this:
#Test
public void addContact(){
final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
Address a1 = new Address("grove","Waterford","Waterford","x9123r","0987654321");
Person p1 = new Person("Charlie","Ansell",a1);
System.setOut(new PrintStream(outContent));
ad1.addContact("Charlie","Ansell", p1);
assertEquals("\nUser: Charlie Ansell Successfully added\n".trim(), outContent.toString().trim());
}
My assumption from this is that there were blank spaces in both of the outputs, thanks to all who commented, I appreciate the help
public class ScriptCreator {
public static void main(String[] args) throws IOException {
#Choose the CSV file that I am importing the data from
String fName = "C:\\Users\\MyUser\\Downloads\\CurrentApplications (1).csv";
String thisLine;
int count = 0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i = 0;
#Prints the List of names in the CSV file
while((thisLine = myInput.readLine()) != null){
String strar[] = thisLine.split(",");
Printer(strar[0]);
}
}
public static void Printer(String arg) throws IOException{
#Want to pull from the String strar[0] from above
#Says that it cannot be resolved to a variable
String name = arg;
String direc = "C:/Users/MyUser/Documents/";
String path = "C:/Users/MyUser/Documents";
Iterable<String> lines = Arrays.asList("LOGIN -acceptssl ServerName","N " + name + " " + direc ,"cd " + name,"import " + path + "*.ppf" + " true","scan", "publishassessase -aseapplication " + name,"removeassess *","del " + name );
Path file = Paths.get(name + ".txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
}
Hello everyone and thank you in advance for any help that you may be able to give me. I am trying to create a java program that will pull names from a CSV file and take those names to generate custom outputs for text files. I am having a hard time being able to set a variable that I can use to grab the names that are being printed and using them to generate a text file by setting the name variable.
I am also going to need some help in making sure that it creates the amount of scripts for the amount of names in the CSV file. Ex. 7 names in CSV makes 7 custom .txt files, each with its appropriate name.
Any help is greatly appreciated!
Edit: I have updated my code to match the correction that was needed to make the code work.
It looks like you have some scoping issues. Whenever you declare a variable, it only exists within the boundaries of its closest set of braces. By declaring strar in your main method, the only place you can explicitly use it is within your main method. Your Printer() method doesn't have any previous mention of strar, and the only way it can know about it is by passing it as an argument to the function.
i.e.
Printer(String[] args)
Or, better yet:
Printer(String arg)
and then call it in your while loop with
Printer(strar[0]);
Also, your Printer method begins with a "for each" loop called on strar[0], which is not a valid target for a foreach loop anyway, because if I recall correctly, String isn't an Iterable object. If you implemented the Printer function in the way I recommended, you won't need a for each loop anyway, as there will only be one name passed at a time.
I have this problem using smartXLS library for Java
I try to export the sheets of a workbook as .png images using the method
workbook.sheetRangeToImage(row1,col1,row2,col2,file)
The code I use is as follows:
private static void takeValuePics() throws Exception {
WorkBook w = new WorkBook();
w.read(XLS_PATH + DIF_FILE_NAME);
int numSheets = w.getNumSheets();
String out;
for(int i=0;i<numSheets;i++) {
w.setSheet(i);
System.out.println(w.getNumber(1,1));
w.setPrintGridLines(true);
out = VAL_PATH + "values_" + w.getSheetName(i) + ".png";
w.sheetRangeToImage(0,0,LOOPS,3,out);
}
The constants are configured correctly and the file is read correctly.
(The println() prints correct values)
The .png files are created but they are completely empty! Just white rectangles.
Does anybody know what's wrong?
Problem solved by the fantastic SmartXLS support team!
I forward their answer:
You need set the print scale,it use the print scale value when exporting range to image
workBook.setPrintScale(100);
That was all!
Hope this helps people in the future.
Following code gets stuck(which I think is blocking I/O) many times (works some time).
def static executeCurlCommand(URL){
def url = "curl " + URL;
def proc = url.execute();
def output = proc.in.text;
return output;
}
But when I changes the code to
def static executeCurlCommand(URL){
def url = "curl " + URL;
def proc = url.execute();
def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
return outputStream.toString();
}
it works fine every time. I am not able to understand why does the 1st way i.e taking input by proc.in.text hangs some time? Does not look an environment specific problem as I tried it on Windows as well as cygwin.
To test/run the above method I have tried -
public static void main(def args){
def url = 'http://mail.google.com';
println("Output : " + executeCurlCommand(url));
}
I have seen multiple questions on SO and all provide the 2nd approach. Although it works good I wish I could know whats wrong with 1st approach ? Has anyone has encountered this scenario before?
The first approach fills a buffer up and then blocks waiting for more room to write output to.
The second approach streams output from the buffer via a separate thread as the process is running, so the process doesn't block.
There are several resources already available for training and executing the grammatical dependency parser, MaltParser; most notably is the project's homepage: http://www.maltparser.org/userguide.html#startusing). And looking at the NLTK code that uses MaltParser, I see how I could write equivalent Java code to start up a separate child process to run MaltParser: http://nltk.org/_modules/nltk/parse/malt.html. However, what I am asking, or rather looking for, is code that clearly and cleanly shows how to integrate MaltParser as a library into a Java program.
To be specific, I want to write Java code to do the following:
Train a parsing model.
Load a trained model and parse sentences in an online fashion (i.e. stream sentences and use a MaltParser object to parse each one).
To whomever has the knowledge, patience, and willingness: please to help me answer 1 and 2!
I found a rudimentary solution to 2. I noticed that on http://www.maltparser.org/userguide.html#api it directs one to a listing of example files. I took this snippet out of one of those files:
/**
* #author Johan Hall
*/
public static void main(String[] args) {
try {
MaltParserService service = new MaltParserService();
// Inititalize the parser model 'model0' and sets the working directory to '.' and sets the logging file to 'parser.log'
service.initializeParserModel("-c model0 -m parse -w . -lfi parser.log");
// Creates an array of tokens, which contains the Swedish sentence 'Grundavdraget upphör alltså vid en taxerad inkomst på 52500 kr.'
// in the CoNLL data format.
String[] tokens = new String[11];
tokens[0] = "1\tGrundavdraget\t_\tN\tNN\tDD|SS";
tokens[1] = "2\tupphör\t_\tV\tVV\tPS|SM";
tokens[2] = "3\talltså\t_\tAB\tAB\tKS";
tokens[3] = "4\tvid\t_\tPR\tPR\t_";
tokens[4] = "5\ten\t_\tN\tEN\t_";
tokens[5] = "6\ttaxerad\t_\tP\tTP\tPA";
tokens[6] = "7\tinkomst\t_\tN\tNN\t_";
tokens[7] = "8\tpå\t_\tPR\tPR\t_";
tokens[8] = "9\t52500\t_\tR\tRO\t_";
tokens[9] = "10\tkr\t_\tN\tNN\t_";
tokens[10] = "11\t.\t_\tP\tIP\t_";
// Parses the Swedish sentence above
DependencyStructure graph = service.parse(tokens);
// Outputs the dependency graph created by MaltParser.
System.out.println(graph);
// Terminates the parser model
service.terminateParserModel();
} catch (MaltChainedException e) {
System.err.println("MaltParser exception: " + e.getMessage());
}
}