I am getting an "args cannot be resolved to a variable" error for my picture outline code in Dr.java where I put stars.
public void faceOutline () {
String filename;
**if (args.length > 0)** {
// got a filename passed into program as a runtime parameter
**filename = args[0]**;
System.out.println("Filename passed in: " + filename);
} else {
// ask user for a picture
filename = FileChooser.pickAFile();
System.out.println("User picked file: " + filename);
}
// use the filename to create the picture object
Picture pic = new Picture(filename);
//show picture
pic.show();
//create world and turtle
World w = new World();
Turtle tj = new Turtle(w);
tj.setPenWidth(7);
tj.setPenColor(Color.red);
}
I was wondering how I could resolve this and how args work.
Look at your main method. As you will see, you can use args in your main method because it is passed as a parameter. So you should pass it to your new method too.
public static void main(String[] args) {
Related
I get multiple errors when writing the header of a method that takes an array list and an integer as input.
I have tried several different ways of writing the header for the method. The body is good and gives me what I want but I can't get the header/call name (I don't know what you call the first line of a method) to not throw errors
/**
* Creates Arraylist "list" using prompt user for the input and output file path and sets the file name for the output file to
* p01-runs.txt
*
*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the path to your source file: ");
String inPath = scan.nextLine(); // sets inPath to user supplied path
System.out.println("Please enter the path for your source file: ");
String outPath = scan.nextLine() + "p01-runs.txt"; // sets outPath to user supplied input path
ArrayList<Integer> listRunCount = new ArrayList<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
/**
* Reads data from input file and populates array with integers.
*/
FileReader fileReader = new FileReader(inPath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// file writing buffer
PrintWriter printWriter = new PrintWriter(outPath);
System.out.println("Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts the string to
* an integer and adds the integer to the array
*/
File file = new File(inPath);
Scanner in = new Scanner(file);
String temp=null;
while (in.hasNextLine()) {
temp = in.nextLine();
temp = temp.replaceAll("\\s","");
int num = Integer.parseInt(temp);
list.add(num);
}
listRunCount.findRuns(list, RUN_UP);
//********************************************************************************************************
public ArrayList<Integer> findRuns(ArrayList<Integer> list, int RUN_UP){
returns listRunCount;
}
error messages
Multiple markers at this line
- Syntax error on token "int", delete this token
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Integer cannot be resolved to a variable
- ArrayList cannot be resolved to a variable
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Illegal modifier for parameter findRuns; only final is permitted
- Syntax error, insert ") Expression" to complete CastExpression
- Syntax error on token "findRuns", = expected after this token
- Syntax error, insert "VariableDeclarators" to complete
LocalVariableDeclaration
- Syntax error, insert ";" to complete Statement
This sort of thing removes the need for statics. If you run your code from within the static method main() then all class methods, member variables, etc that are called or referenced from within main() must also be declared as static. By doing:
public class Main {
public static void main(String[] args) {
new Main().run();
}
}
eliminates the need for statics. In my opinion to properly do this the run() method within the class should also be passed the args[] parameter:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
// You project code here
}
}
That way any Command Line arguments passed to the application can also be processed from within the run() method. You will find that most people won't use the method name run for this sort of thing since run() is a method name more related to the running of a Thread. A name like startApp() is more appropriate.
public class Main {
public static void main(String[] args) {
new Main().startApp(args);
}
private void startApp(String[] args) {
// You project code here
}
}
With all this in mind your code might look something like this:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
String runCountFileCreated = createListRunCount();
if (!runCountFileCreated.equals("") {
System.out.println(The count file created was: " + runCountFileCreated);
}
else {
System.out.println(A count file was NOT created!);
}
}
/**
* Creates an ArrayList "list" using prompts for the input and output file
* paths and sets the file name for the output (destination) file to an
* incremental format of p01-runs.txt, p02-runs.txt, p03-runs.txt, etc. If
* p01 exists then the file name is incremented to p02, etc. The file name
* is incremented until it is determined that the file name does not exist.
*
* #return (String) The path and file name of the generated destination
* file.
*/
public String createListRunCount() {
String ls = System.lineSeparator();
File file = null;
Scanner scan = new Scanner(System.in);
// Get the source file path from User...
String sourceFile = "";
while (sourceFile.equals("")) {
System.out.print("Please enter the path to your source file." + ls
+ "Enter nothing to cancel this process:" + ls
+ "Source File Path: --> ");
sourceFile = scan.nextLine().trim(); // User Input
/* If nothing was entered (just the enter key was hit)
then exit this method. */
if (sourceFile.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// See if the supplied file exists...
file = new File(sourceFile);
if (!file.exists()) {
System.out.println("The supplied file Path/Name can not be found!." + ls
+ "[" + sourceFile + "]" + ls + "Please try again...");
sourceFile = "";
}
}
String destinationFile = "";
while (destinationFile.equals("")) {
System.out.print(ls + "Please enter the path to folder where data will be saved." + ls
+ "If the supplied folder path does not exist then an attempt" + ls
+ "will be made to automatically created it. DO NOT supply a" + ls
+ "file name. Enter nothing to cancel this process:" + ls
+ "Destination Folder Path: --> ");
String destinationPath = scan.nextLine();
if (destinationPath.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// Does supplied path exist. If not then create it...
File fldr = new File(destinationPath);
if (fldr.exists() && fldr.isDirectory()) {
/* Supplied folder exists. Now establish a new incremental file name.
Get the list of files already contained within this folder that
start with p and a number (ex: p01-..., p02--..., p03--..., etc)
*/
String[] files = fldr.list(); // Get a list of files in the supplied folder.
// Are there any files in the supplied folder?
if (files.length > 0) {
//Yes, so process them...
List<String> pFiles = new ArrayList<>();
for (String fileNameString : files) {
if (fileNameString.matches("^p\\d+\\-runs\\.txt$")) {
pFiles.add(fileNameString);
}
}
// Get the largest p file increment number
int largestPnumber = 0;
for (int i = 0; i < pFiles.size(); i++) {
int fileNumber = Integer.parseInt(pFiles.get(i).split("-")[0].replace("p", ""));
if (fileNumber > largestPnumber) {
largestPnumber = fileNumber;
}
}
largestPnumber++; // Increment the largest p file number by 1
// Create the new file name...
String fileName = String.format("p%02d-runs.txt", largestPnumber);
//Create the new destination File path and name string
destinationFile = fldr.getAbsolutePath() + "\\" + fileName;
}
else {
// No, so let's start with p01-runs.txt
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
else {
// Supplied folder does not exist so create it.
// User Confirmation of folder creation...
JFrame iFrame = new JFrame();
iFrame.setAlwaysOnTop(true);
iFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFrame.setLocationRelativeTo(null);
int res = JOptionPane.showConfirmDialog(iFrame, "The supplied storage folder does not exist!"
+ ls + "Do you want to create it?", "Create Folder?", JOptionPane.YES_NO_OPTION);
iFrame.dispose();
if (res != 0) {
destinationFile = "";
continue;
}
try {
fldr.mkdirs();
}
catch (Exception ex) {
// Error in folder creation...
System.out.println(ls + "createListRunCount() Method Error! Unable to create path!" + ls
+ "[" + fldr.getAbsolutePath() + "]" + ls + "Please try again..." + ls);
destinationFile = "";
continue;
}
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
ArrayList<Integer> list = new ArrayList<>();
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the writer. */
try (PrintWriter printWriter = new PrintWriter(destinationFile)) {
System.out.println(ls + "Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts
* the string to an integer and adds the integer to the List.
*/
String temp = null;
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the reader. */
try (Scanner reader = new Scanner(file)) {
while (reader.hasNextLine()) {
temp = reader.nextLine().replaceAll("\\s+", "");
/* Make sure the line isn't blank and that the
line actually contains no alpha characters.
The regular expression: "\\d+" is used for
this with the String#matches() method. */
if (temp.equals("") || !temp.matches("\\d+")) {
continue;
}
int num = Integer.parseInt(temp);
list.add(num);
}
// PLACE YOUR WRITER PROCESSING CODE HERE
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
/* return the path and file name of the
destination file auto-created. */
return destinationFile;
}
}
so I want to read in a text file with a bunch of inputs containing strings like this:
abc456
mnjk452
aaliee23345
poitt78
I want to put each of these inputs into an array list and pass that arraylist through one of my methods. How would I go about doing so? Currently in my code, I'm trying to see if i can simply print out what's in my arraylist. Here is what i have in my main:
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("Give me a file!");
}
String fname = args[0];
ArrayList<String> coordinates = new ArrayList<String>();
Scanner grid = new Scanner(fname);
while(grid.hasNext()) {
coordinates.add(grid.nextLine());
}
for(String coordinate : coordinates) {
System.out.println(coordinate);
}
}
How about this:
Path path = Paths.get(args[0]);
List<String> coordinates = Files.readAllLines(path);
System.out.print(coordinates); // [abc456, mnjk452, aaliee23345, poitt78]
Same can be accomplished with the Scanner:
Path path = Paths.get(args[0]);
List<String> result = new ArrayList<>();
Scanner sc = new Scanner(path);
while (sc.hasNextLine()) {
String line = sc.nextLine();
result.add(line);
}
System.out.print(result); // [abc456, mnjk452, aaliee23345, poitt78]
Do not forget to pass your arguments when you run your application (either in your IDE or command line)!
When reading from a file you need to create a File object that you give to the Scanner object. Also you should control your while loop based on grid.hasNextLine() since you are grabbing line by line. Lastly when running the program from terminal you should be doing the following
java "name of your class with main" "file name"
Which will pass that file in as a parameter to args[0]
try
{
Scanner grid = new Scanner(new File(fname));
while(grid.hasNextLine())
{
coordinates.add(grid.nextLine());
}
}catch(FileNotFoundException e)
{
System.err.println("File " + fname + " does not exist/could not be found");
e.printStackTrace();
}
I want to pass a variable to String filename variable below as a parameter. Can anyone help?? I checked the internet but could not find a good tutorial or example.
Thank you in advance...
import java.io.IOException;
public class JavaReadTextFile
{
public static String main(String[] args)
{
// This instantiates from another class
ReadFile rf = new ReadFile();
// The text file location of your choice.
// Here I want to pass a variable as a parameter to the variable filename
String filename = "";
try
{
String[] lines = rf.readLines(filename);
for (String line : lines)
{
//System.out.println(line);
return line;
}
}
catch(IOException e)
{
// Print out the exception that occurred
System.out.println("Unable to create " + filename + ": " + e.getMessage());
}
}
}
I'm assuming you mean "as an argument to my program", so that you can run:
java -jar myProgram.java theStringIWantToPass
If so, that's what main(String[] args) is for. All arguments will be put in there.. So, try using the following:
if (args.length > 0){
filename = args[0];
}
You didn't post a constructor, but you can get the (command line) parameter of your main function:
public static String main(String[] args) {
if (args!=null && args.length > 0) {
String filename = args[0];
}
}
Change your code to
String filename = args[0];
Now you can pass the file name as a program argument.
If you are open to use swing , then you can explore JOptionPane mesageBox , which can take input.
Otherwise the conventional way of reading the arguments while running the program from args array.
I am trying to make a program that will be run from terminal or command line. You will have to supply a file name in the arguments. I want it to be able to get the path in which the program was run and then append the file name to it. It would be something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (args.length > 0) {
if (args[0] instanceof String && !args[0].equals(null)) {
if (args[0].equals("compile")) {
System.out.println("File to compile:");
String fileName = scanner.next();
String path = /*get the path here*/ + fileName;
File textfile = new File(path);
if (textfile.exists()) {
Compiler compiler = new Compiler(textfile);
compiler.compile();
} else {
System.out.println("File doesn't exist");
}
}
}
}
}
This should work for you:
Paths.get("").toAbsolutePath().toString()
You can test by:
System.out.println("" + Paths.get("").toAbsolutePath().toString());
Try this:
String path = System.getProperty("user.dir") + "/" + fileName;
If i understand you correctly you are trying to get the path where the program is located.
if so you can try the following:
URI path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI());
Replacing /*get the path here*/ with Paths.get(".") should get you what you want. If your argument is a filename in the same directory you don't have to provide a path to it to create the File object.
So in your case,
File textfile = new File(fileName);
should work as well.
I'm trying to accept 3 filenames through a command line. This is the code I tried but not working.. ?? Pls help
public class MedicalStudentMatcher {
enum Arguments {
HospitalFile, ResidentFile, OutputFile
};
/**
* #param args
*/
public static void main(String[] args) {
//Retrieve file locations from command line arguments
String hospitalFile = "";
String residentFile = "";
String outFile = "";
if (args.length > 2){
hospitalFile = args[Arguments.HospitalFile.ordinal()];
residentFile = args[Arguments.ResidentFile.ordinal()];
outFile = args[Arguments.OutputFile.ordinal()];
} else {
System.out
.println("Please include names for the preference files and output file when running the application.\n "
+ "Usage: \n\tjava MedicalStudentMatcher hospital.csv student.csv out.txt\n");
return;
}
Do some debugging. Print the length of you command line arguments as well as each argument
something like:
System.out.println(args.length);
for(String arg: args)
{
System.out.println(arg);
}
This way you will see what you are passing to your program as arguments.