Java arguments from text file - java

I'm trying to pass arguments from a text file and perform the corresponding action on an object in java. I have the following thus far:
public static void main(String[] args) throws FileNotFoundException {
Portfolio portfolio=new Portfolio();
Scanner reader = new Scanner(new FileInputStream(args[0])).useDelimiter("\n");
while(reader.hasNext()){
String arg=reader.next();
if(reader.hasNextInt()){
int cash=reader.nextInt();
portfolio.arg(cash);
}
else if(reader.hasNext()){
String ticker=reader.next();
int shares=reader.nextInt();
float price=reader.nextFloat();
portfolio.arg(ticker,shares,price);
}
portfolio.arg();
}
reader.close();
}
How can I pass the first as a method to the portfolio object, and the remaining as arguments for that method? Having a lot of trouble with this, thanks.

Related

JUnit - NoSuchElementException: No line found

I'm trying to learn unit testing and Maven, to do so I'm using JUnit and writing simple random name generator. I have following class:
public class Database {
public String readRandomName(String url) throws FileNotFoundException {
int sum = calculateFileLines(url);
int lines = (int) (Math.random()*sum);
File file = new File(url);
Scanner scanner = new Scanner(file);
for (int i=0; i<lines;i++){
scanner.nextLine();
}
return scanner.nextLine();
}
public int calculateFileLines(String url) throws FileNotFoundException {
int sum = 0;
try (Scanner scanner = new Scanner(new File(url))){
while(scanner.hasNextLine() && scanner.nextLine().length()!=0){
++sum;
}
}
return sum;
}
}
When I run simple test like this:
public static void main(String[] args) throws FileNotFoundException {
Database database = new Database();
database.readRandomName("names/maleNamesPL.txt");
}
It works perfectly, but when I tried to write JUnit test with assertion there is an unexpected failure which I don't understand. This is test code:
#Test
public void readRandomNameTest() throws FileNotFoundException {
Database database = new Database();
Assert.assertNotNull("Should be some name", database.readRandomName("names/maleNamesPL.txt"));
}
And the results:
Tests in error:
readRandomNameTest(DatabaseTest): No line found
I would appreciate any help, thank you!
You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html
With Scanner you need to check if there is a next line with hasNextLine()
so the loop becomes
while(scanner.hasNextLine()){
String str=scanner.nextline();
//...
}

Java Pass an int through Command

public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new FileReader(args[1]));
String co = sc.next();
coup = Integer.parseInt(co);
I get a FileNotFoundException when I try to pass an int into the second argument in command line. This is only part of the code, a text file is passed as args[0]. However, I can't figure out how to pass a simple integer, only text files.
public static void main(String[] args) throws Exception
{
Scanner scan = new Scanner(new FileReader(args[0]));
int integerFromCM = Integer.parseInt(args[1]);
}
You state that a text file is the first argument (args[0]) so assign that in the scanner and when grabbing the integer all you need to do is send args[1] into Integer.parseInt method. You are getting the exception because you are assigning a FileReader object with the file name of the integer passed in.
You can't pass an int, but you can parse one:
public static void main(String[] args) {
String filename = args[0];
int i = Integer.parseInt(args[1]);
// ...
}
If you are getting a FileNotFoundException, one easy way to debug it is:
File file = new File(filename);
System.out.println(file.getAbsolutePath());
and it will be obvious where the problem lies, which is almost always the current directory of the application is not what you think it is.
Reviewing your code it reads as follows:
Create a Scanner to read the file in the first command line argument
Get the first integer from that Scanner as a String
Parse that String to an int
It is clearly sequenced to require a file from the first argument and that looks like it is intended.
Create a file called number.txt:
42
NumberPrinter.java:
import java.io.Scanner;
import java.io.FileReader;
public final class NumberPrinter {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new FileReader(args[1]));
String numberInFile = scanner.next();
int number = Integer.parseInt(numberInFile);
System.out.println(number);
}
}
Run as follows:
java NumberPrinter number.txt
And it will print:
42
Alternatively if you intend to parse an int directly from the command line parameters try:
public final class NumberPrinterDirect {
public static void main(String[] args) throws Exception {
int number = Integer.parseInt(args[0]);
System.out.println(number);
}
}
NumberOrFilenameAwkward.java:
import java.io.Scanner;
import java.io.FileReader;
public final class NumberOrFilenameAwkward {
public static void main(String[] args) throws Exception {
int number;
try {
number = Integer.parseInt(args[0]);
} catch (NumberFormatException thisIsVeryUgly) {
Scanner scanner = new Scanner(new FileReader(args[1]));
String numberInFile = scanner.next();
number = Integer.parseInt(numberInFile);
}
System.out.println(number);
}
}
That is a terrible solution and screams for using a command line parsing library like JewelCLI or commons-cli to solve it cleanly.

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.

I'm a new programmer and every time I run this block of code I get a null pointer exception in Java

//This Is the Class
private String words;
private File textFile;
private Scanner inputFile;
StringBuilder stringBuilder = new StringBuilder();
public Scramble(String j) throws FileNotFoundException
{
File textFile = new File(j);
Scanner inputFile = new Scanner(textFile);
}
public String getRealWord() throws IOException
{
//Make the loop while !null
//if null close the document
while (inputFile.hasNext())
{
stringBuilder.append(inputFile);
}
inputFile.close();
return stringBuilder.toString();
}
This is the call to the class in the main method
String word = theScramble.getRealWord();
What portion should I change to avoid the null pointer exception
You're re-declaring your variables in the local scope. Within your Scramble constructor:
File textFile = new File(j);
...is declaring a new variable called textFile, which hides the instance member also called textFile.
You'll want to change:
public Scramble(String j) throws FileNotFoundException
{
File textFile = new File(j);
Scanner inputFile = new Scanner(textFile);
}
To:
public Scramble(String j) throws FileNotFoundException
{
textFile = new File(j);
inputFile = new Scanner(textFile);
}
This way, you're referring to the instance variables, not the local variables.

How can I use a command line parameter to access a text file?

I'm trying to use 3 command line parameters such as:
java program textfile.txt test 3
The first one should access a textfile, the second one should print the name, and the third one should be a numeric key that is parsed as an integer.
import java.util.Scanner;
import java.io.*;
public class Program
{
public static void main(String[] args) throws IOException
{
String textfile=null;
String outtextfile=null;
String enteredKey=null;
for(String parameter: args) {
textfile = parameter;
outtextfile = parameter;
enteredKey = parameter;
}
Scanner s = new Scanner(new File(textfile));
//gets a string to encrypt
String str = s.nextLine();
//print outtextfile
System.out.println(outtextfile);
//gets a key
int key = Integer.parseInt(enteredKey);
However, that code yields this error:
-bash-4.1$ java Program sample.txt test 3
Exception in thread "main" java.io.FileNotFoundException: 3 (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:656)
at Program.main(Caesar.java:19)
You're running into a scoping problem:
The textFile variable is only visible within the for loop and is invisible outside of this loop. Are you sure that you even want to have a loop? And if so why? If the text file String is the first parameter, then get rid of the loop and only use the first parameter, args[0]:
public static void main(String[] args) throws IOException {
if (args.length == 0) {
// exit program with an error message
} else {
String textFile = args[0];
Scanner scanner = new Scanner(new File(textFile));
// do work with Scanner
}
You are declaring textfile in your loop, meaning it is only limited to the scope of your loop. You are trying to access it outside the loop. I would offer a suggestion, but I'm not really sure what you are trying to accomplish.
Try this :
String textfile=null;
for(String parameter: args) {
textfile = parameter;
}
Scanner s = new Scanner(new File(textfile));

Categories

Resources