Java Pass an int through Command - java

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.

Related

Need to get a line from a file onto queue and not the whole file text

I'm having trouble properly getting one line of text at a time from a file onto a queue without taking the whole file into the queue. For example, I'd like only Write a program that reads a Java source file as an argument and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity, we will consider each string consisting only of letters, numbers, and underscores an identifier.
Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+") Then each call to next returns an identifier.
public class Main { to get added to the queue but instead the whole file text is put into the queue instead of a line at a time. Sorry if my question is unclear
// Write a program that reads a Java source file as an argument and produces an index of all
// identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity,
// we will consider each string consisting only of letters, numbers, and underscores an identifier.
// Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+").
// Then each call to next returns an identifier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class E_15 {
public static void main(String[] args) throws FileNotFoundException
{
// get scanner input from file
Scanner fileInput = new Scanner(new File ("C:/Users/ramir/IdeaProjects/PA_7/src/Main.java"));
Queue<String> test = new LinkedList<String>();
ArrayList<String> phrase = new ArrayList<String>();
/*
List<String> result = new ArrayList<String>();
Scanner s = new Scanner(is);
s.useDelimiter(delimiter);
*/
// Iterates till end of file
while (fileInput.hasNextLine())
{
// Here is the issue. Data will end up
// containing the whole file instead of only that line
String data = fileInput.nextLine();
Scanner in = new Scanner(data);
in.useDelimiter("[^A-Za-z0-9_]+");
// I believe around here or before is the issue that I'm having.
// It adds all the file instead of only that line
// Also trying to figure out how to display each line that it's displayed on
// What the first one should look like for example
// 0: public occurs in:
// public class Main {
// public static void main(String[] args) {
//System.out.println(data);
test.add(data);
while(in.hasNext())
{
// Getting each phrase/word into ArrayList
String token = in.next();
phrase.add(token);
}
in.close();
}
int index = 0;
// This part works fine
for(String num : phrase)
{
// printing the key
System.out.println(index + ": " + num + " occurs in:");
// printing the values
// This to print out what
for(String line : test)
{
System.out.println(line);
}
System.out.println();
++index;
}
}
}
// Just java class get file front
// This is fine
public class Main {
public static void main(String[] args) {
int a_1 = 100;
System.out.println(a_1);``
}
}
I'd like it to only show System.out.println(a_1) because the line that's it's on See This
. I'm also have trouble printing it in all the lines that occur.
import java.io.*;
import java.util.Scanner;
public class ReadLineByLineExample2
{
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine())
{
System.out.println(sc.nextLine()); //returns the line that was skipped
}
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Try studying the above code. I hope it will help. Otherwise, you might need to open this link for more detail.

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();
//...
}

Change a program to accept command line arguments

I have the following code and would like to modify it to accept command line arguments instead of reading a file using scanner. Can you point me to some change I need to make in the code in order to do so ? Any help is appreciated. I will have a file called prgm.cmd and will execute it on UNIX as follows. prgm.cmd is the actual argument !
java Commander prgm.cmd
right now I am only able to have the program work by using
java Commander < prgm.cmd
CODE
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Commander
{
public static void main(String[] args)
{
Map<String,Integer> expression = new HashMap<String,Integer>();
ArrayList<String> list = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
while(true)
{
list.add(sc.nextLine());
if(!sc.hasNextLine()) break;
}
ArrayList<String> tokens = new ArrayList<String>();
ArrayList<String> PRINT = new ArrayList<String>();
for(String element : list) {
StringTokenizer st = new StringTokenizer(element);
if(!element.startsWith("PRINT")) {
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
expression.put(tokens.get(0),Integer.parseInt(tokens.get(2)));
tokens.clear();
} else {
while(st.hasMoreTokens())
PRINT.add(st.nextToken());
System.out.println(expression.get(PRINT.get(1)));
PRINT.clear();
}
}
}
}
SAMPLE COMMAND FILE: PRGM.CMD
A = 6
C = 14
PRINT C
B = 12
C = 8
PRINT A
OUTPUT
14
6
public static void main(String[] args)
// ^^^^^^^^^^^^^
When you run your program with something like:
java progname arg1 arg2
the arguments appear in the string array handed to main(). You just extract them from there and do what you need.
The following small (but complete) program shows this in action. It will echo back your arguments, one per line:
public class Test {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println (args[i]);
}
}
That's to get the commands as arguments to the program.
If, instead, you want to still have the commands in a file and just supply the file name to the program, you simply need to change your scanner to use a file based reader rather than System.in. The following program accepts a file name argument then echos it to the screen:
import java.io.FileInputStream;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
try {
Scanner sc = new Scanner (new FileInputStream(args[0]));
while (sc.hasNextLine())
System.out.println (sc.nextLine());
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
You can even make it selectable, like UNIX filter programs using - to indicate standard input.
If you want to use a file if provided but revert to standard input if not, you can do something like:
Scanner sc;
if (args.length > 0)
sc = new Scanner (new FileInputStream(args[0]));
else
sc = new Scanner (System.in);
// Now just use scanner as before

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

Java arguments from text file

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.

Categories

Resources