how to pass a variable through a constructor in java - java

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.

Related

Args cannot be resolved to a variable

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) {

while loop won't read file, or print out line java

I have a with the hentAntall method in my code below. It's supposed to find the search word inside a txt file. I don't get any sort of error. It just won't print out any of the two possible lines.
This method has to access a constructor first to get the search word, and then it has to find that search word in the txt file and add to count. The constructor gets the search word from another class. Like this new lolz("searchword").hentAntall();
(I apologize for the stupid naming in this program, but it's just a copy of one of my programs, and I'm just trying to correct it without screwing up the original.)
import java.io.File;
import java.util.Scanner;
public class lolz {
private String sokeord=null;
private int antall = 0;
// Constructor
lolz(String searchword) throws Exception{
this.sokeord = searchword;
}
//toString method, to print in the same format.
#Override
public String toString(){
return "\nSokeordet er: " + sokeord+ "\n";
}
// Gets the ammount of the searchword
public int hentAntall() throws Exception{
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()){
String nextline = readfile.nextLine();
if (nextline.equalsIgnoreCase(sokeord)) {
antall ++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
}
else {System.out.println("Error no such search word in the given text");}
}
return antall;
}
// void methode to increase the count of a searcheword.
void oekAntall() {
antall++;
}
}
This is the other class that calls on this method, and also give information to the constructor.
public class Main {
public static void main(String[] args) throws Exception {
new lolz("fungerer").hentAntall();
}}
Also tried some of the suggestions and they did not work, I only get a the message Process finished with exit code 0.
Your Issue:
You are trying to compare a Scanner variable with a String Variable?!!!
Explanation:
you try to compare content of Scanner which is
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=true][need input=false][source
closed=false][skipped=false][group separator=\,][decimal
separator=.][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
with content of a String variable.
You do not read the each line with following
if (readfile.equals(sokeord)) {
You Should have
if (readfile.nextLine().equals(sokeord)) {
Instead of:
readfile.equals(sokeord)
Which is comparing an instance of type Scanner with a String (never going to be true). You need to read a line and compare that.
String line = readfile.nextLine();
if(line.equals(sokeord)){
Add a main method to your class:
public static void main(String[] args)
{
hentAntall();
}
You will have to make hentAntall() static or create an instance of lolz class and call it that way.
Also change:
while (readfile.hasNext()){
if (readfile.nextLine().contains(sokeord)) {
You need to actually read the input and then check if sokeord exists in the line or not.
Your hentAntall method should be like this:
public int hentAntall() throws Exception {
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()) {
String word = readfile.next();
if (word.contains(sokeord)) {
antall++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
} else {
System.out
.println("Error no such search word in the given text: ");
}
}
readfile.close();
return antall;
}
Don't forget to close the Scanner resource to avoid leaks.

putty command line arguments acting strangely with java

I need my code to read in a file pathway and analyze the file at the end of it, and according to the assignment it has to exit if no valid pathway is given. when I type in something like "java ClassName pathway/file" though it just goes to accepting more input. If I then put in the exact same pathway it does what I want it to but it need to do it in the former format. should I not be using a Scanner?
(TextFileAnalyzer is another class I wrote that does the file analysis, obviously)
import java.util.Scanner;
public class Assignment8 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String path = null;
TextFileAnalyzer analysis = null;
if (args.length == 0 || java.lang.Character.isWhitespace(args[0].charAt(0)))
System.exit(1);
try {
path = stdin.next();
analysis = new TextFileAnalyzer(path);
} catch (Exception e) {
System.err.println(path + ": No such file or directory");
System.exit(2);
}
System.out.println(analysis);
stdin.close();
System.exit(0);
}
}
Arguments specified on the command line are not the same as information entered via standard input at the console. Reading from System.in will let you read input, and this is not related to command line parameters.
The problem with your current, non-working code is that while you are checking to see if the argument was specified, you aren't actually using args[0] as the pathname, you're just going on to read user input regardless.
Command line parameters are passed in via the String[] parameter to main. In your case it's the first parameter, so it would be in args[0]:
public static void main (String[] args) {
String pathname;
if (args.length > 0) {
pathname = args[0]; // from the command line
} else {
// get pathname from somewhere else, e.g. read from System.in
}
}
Or, more strict:
public static void main (String[] args) {
String pathname;
if (args.length > 1) {
System.err.println("Error: Too many command line parameters.");
System.exit(1);
} else if (args.length > 0) {
pathname = args[0]; // from the command line
} else {
// get pathname from somewhere else, e.g. read from System.in
}
}
Check out the official tutorial on command-line arguments for more information.
By the way, I noticed you have this in your if condition:
java.lang.Character.isWhitespace(args[0].charAt(0))
Leading and trailing whitespace is automatically trimmed off of unquoted command line parameters, so that will always be false unless the user explicitly uses quotes and does something like:
java ClassName " something"
And even in that case, you may want to just accept it and use args[0].trim() to be more lenient.

acccepting file names using command line in java

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.

Java scanner + sort

Okay, first post, yay!
Now I know this topic has been beaten to death already. But here's the question :
Write a program that reads words separated by spaces from a text file
and displays words in ascending order. (If two words are the same,
display only one). Pass the text filename from the command line.
Assume that the text file contains only words separated by spaces.
Now I have the reading from the file part figured out. But how do I "pass the filename from the command line"? And then there's the uniqueness factor.
Help?
Edit:
Thanks guys for your help. Here's where I stand now:
import java.io.*;
import java.util.*;
public class Splittext {
public static void main(String[] args) {
String fileName = args[0];
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader(fileName)));
while (s.hasNext()) {
System.out.println(s.next());
}
} catch (FileNotFoundException fnfe) {
System.exit(0);
} finally {
if (s != null) {
s.close();
}
}
TreeSet<String> ts = new TreeSet<String>();
ts.add(s);
Iterator it = ts.iterator();
while(it.hasNext()) {
String value = (String)it.next();
System.out.println("Result :" + result);
}
}
}
But this yields : No suitable method for add (java.util.Scanner); method java.util.TreeSet.add(java.lang.String) is not applicable.
Sorry for the noob questions! Really appreaciate the help :)
Do like this.
public static void main(String args[]) {
String fileName = args[0];
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader(fileName));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
Run this like
java classname readthisfile.txt
Your main function has String[] args passed into to it when you kick off your application, this is where you access you input arguments.
e.g.:
java -cp . my.class.Example Happy Days
Would see the Example class receiving this:
public static void main(String[] args) {
// args.length == 2
// args[0] = "Happy"
// args[1] = "Days"
}
But how do I "pass the filename from the command line"?
public static void main(String args[])
{
final String filename = args[0];
// ...
}
And then there's the uniqueness factor.
And sorting factor.
Insert all the words into TreeSet.
Iterate through it and print values. They will be sorted and unique.

Categories

Resources