How to parse the command parameter in java? - java

For example, the user run my programme like this
myprogram -p1 my_name, -p2 my_address, -p3 my_gender
But the user may type this, and it still valid:
myprogram -p2 my_address, -p1 my_name,-p3 my_gender
How can I parse it in Java? Thanks.

You can use something like this:
public static void main (String[] args) {
for(int i = 0; i < args.length; i++) {
if(args[i].equals("-p1")) {
// args[i+1] contains p1 argument
} else if(args[i].equals("-p2")) {
// args[i+1] contains p2 argument
}
}
}
Make sure to check whether the i+1 argument is there, otherwise an exception will be thrown.
There are more advanced methods of going this, you could e.g. use hashing to map the flag to the processing function. But, for this purpose, I guess this will do.
What I do not understand is the use of comma's in your sample. What are they used for?

If you're looking for a DIY, then maybe this might be starting point.
public class Foo
{
private static final String[] acceptedArgs = { "-p1", "-p2", "-p3" };
public void handleCommandArgs(String... args)
{
if (args != null)
{
for (int argIndex = 0; argIndex < args.length; argIndex++)
{
for (int acceptedIndex = 0; acceptedIndex < acceptedArgs.length; acceptedIndex++)
{
if (args[argIndex] != null && args[argIndex].equals(acceptedArgs[acceptedIndex]))
{
String arg = args[argIndex], param = args[argIndex + 1];
performRoutine(arg, param);
}
}
}
}
}
private void performRoutine(String arg, String param)
{
System.out.println(arg + " ->" + param.replace(",", ""));
}
public static void main(String[] args)
{
(new Foo()).handleCommandArgs(args);
}
}

Sample from Java Tutorials #Oracle
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
The params come in a vector of String.

Related

How to add String output to an array within a recursion

I am writing a recursive procedure to return a permutation of a string
I get the desired output printed to the console. However, I would like to add the output to an array to be able to work on it further. How can I achieve it?
import java.util.*;
public class Permutation {
public static void main(String args[]) {
permute("A", "BCD");
}
public static void permute(String FirstElement, String Remainder) {
List<String> mylist_tobuild = new ArrayList<String>();
if (Remainder.length() <= 1) {
FirstElement = FirstElement+Remainder;
// System.out.println(FirstElement);
mylist_tobuild.add(FirstElement);
System.out.println(mylist_tobuild);
}
else
for (int i = 0; i < Remainder.length(); i++) {
try {
String newString = Remainder.substring(0, i) + Remainder.substring(i + 1);
permute(FirstElement + Remainder.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
I get: [ABCD] [ABDC] [ACBD] [ACDB] [ADBC] [ADCB]
I would like to have: [ABCD, ABDC, ACBD, ACDB, ADBC, ADCB,]
You can supply the List as an argument:
public static void main(String args[]) {
List<String> perms = new ArrayList<>();
permute("A", "BCD",perms);
System.out.println(perms);
}
public static void permute(String FirstElement, String Remainder, List<String> perms) {
if (Remainder.length() <= 1) {
FirstElement = FirstElement+Remainder;
perms.add(FirstElement);
} else {
for (int i = 0; i < Remainder.length(); i++) {
try {
String newString = Remainder.substring(0, i) + Remainder.substring(i + 1);
permute(FirstElement + Remainder.charAt(i), newString, perms);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
You are creating a new list every time you go through the permute method. To fix that, you can take your list creation out of the method (e.g. create a static field), so you don't create a new list every time you go through the loop. Then add your print statement after your permutation method in your main class, so you can get the final result.
private static ArrayList<String> mylist_tobuild;
public static void main(String args[]) {
mylist_tobuild = new ArrayList<>(); //initialize list here once
permute("A", "BCD");
System.out.println(mylist_tobuild);
}

Increased cohesion in simple java program

I have a small java program that collects 10 words written by a user and prints them in specified orders. As it stands, the program works, but it is not cohesive.
My issue stems from not knowing enough about the concept of cohesion to work on fixing this, as well as being new to Java/OO languages.
I believe that the class Entry is way way way too cluttered, and that another class should take on some of this class' functions.
Any hint or clue, cryptic or otherwise would be greatly appreciated!
The lack of a input reader in Dialogue.java is intentional, as the original code uses proprietary code.
These are the three classes: entry, dialogue and printer.
Entry.java
public class Entry {
public static void main(String[] args){
String[] wordArray = new String[10];
Dialogue d = new Dialogue();
wordArray = d.read(wordArray);
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
}
Dialogue.java
public class Dialogue {
public String[] read(String[] s){
String[] temp;
temp = new String[s.length];
for(int i=0;i<s.length;i++){
String str = anything that reads input("Enter word number" + " " + (i+1));
temp[i] = str;
}
return temp;
}
}
Printer.java
public class Printer {
public void printForwards(String[] s){
System.out.println("Forwards:");
for(int i=0;i<s.length;i++){
System.out.print(s[i] + " ");
if(i==s.length-1){
System.out.println("");
}
}
}
public void printBackwards(String[] s){
System.out.println("Backwards:");
for(int i=s.length-1;i>=0;i--){
System.out.print(s[i]+ " ");
if(i==0){
System.out.println("");
}
}
}
public void printEveryOther(String[] s){
System.out.println("Every other:");
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
System.out.print(s[i] + " ");
}
}
}
}// /class
It looks okay overall, the truth is it is a very simple task where as OOP is better suited for more complex programs. That being said, here are a few pointers/examples.
You can also do your printing more OOP style.
The purpose of this is build reusable, modular code. We do this by abstracting String array manipulations (which previously existed in the Printer class) to it's own class.
This is also very similar/also known as loose-coupling. We achieve loose-coupling by splitting the string processing functionality and the printing functionality.
Change you Printer class to StringOrderer or something along those lines:
public class StringOrderer {
private String[] array;
public class StringOrderer(String[] array) {
this.array = array;
}
public String[] getArray() {
return array;
}
public String[] everyOther(){
String[] eos = new String[array.length];
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
eos[eos.length] = s[i];
}
return eos;
}
public String[] backwards() {
...
And then in your main class add a method like such:
private static void printStringArray(String[] array) {
for (int i=0; i<array.length; i++) {
System.out.print(array[i]);
}
}
Then call it in your main method:
StringOrderer s = new StringOrderer(wordArray);
System.out.println('Forward:');
printStringArray(s.getArray());
System.out.println('Every other:');
printStringArray(s.everyOther());
System.out.println('Backwards:');
...
Extra tip - You can also add methods in your main class like so:
public class Entry {
public static void main(String[] args){
String[] wordArray = readWordArray()
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
private static String[] readWordArray() {
Dialogue d = new Dialogue();
return d.read(new String[10]);
}
}
to make it more readable.

Show the Java args[] in one line [duplicate]

This question already has answers here:
Print multiple lines output in java without using a new line character
(9 answers)
Closed 7 years ago.
I wrote this
public class Main {
public static void main(String[] args) {
for (int i =0; i < args.length; i++){
System.out.println(args[i]);
}
}
}
in cmd typed:
C:\> javac Main.java
C:\> java Main first second third
The console showed me
first
second
third
Questin is how to make that cmd shows me arguments in one line?
Should be something like this.
public class Main {
public static void main(String[] args) {
for (int i =0; i < args.length; i++){
System.out.print(args[i] + " ");
}
}
}
You are using System.out.println().
The println method will terminate current line by writing the line separator string for you. (Which in your case is the newline character.)
Instead, you want to use System.out.print().
Like so:
System.out.print(args[i] + " ");
This will print your argument, followed by a space instead of a newline character.
Use System.out.print() instead of println().
If you want the printing to continue in the same line, you need to invoke a print() method instead of a println() method.
Also, since this resembles the echo program, if you want it to be perfect, you want to have space between the strings, but not before the first or after the last.
With Java 4 and older:
public class Main {
public static void main(final String[] args) {
for (int i = 0; i < args.length; i++) {
if (i > 0)
System.out.print(" ");
System.out.print(args[i]);
}
System.out.println();
}
}
With Java 5-7 you could use foreach-loops, although in this special case that's not really better, it's just for completeness:
public class Main {
public static void main(final String... args) {
boolean isFirst = true;
for (final String arg : args) {
if (isFirst)
isFirst = false;
else
System.out.print(" ");
System.out.print(arg);
}
System.out.println();
}
}
With Java 8:
public class Main {
public static void main(final String... args) {
System.out.println(String.join(" ", args));
}
}
If you want your program to be fast - which would not be necessary in this case, this again is just for completeness - you would want to first assemble the String and then print it in one go.
With Java 4 and older:
public class Main {
public static void main(final String[] args) {
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) {
if (i > 0)
sb.append(' ');
sb.append(args[i]);
}
System.out.println(sb);
}
}
With Java 5-7:
public class Main {
public static void main(final String... args) {
final StringBuilder sb = new StringBuilder();
for (final String arg : args)
sb.append(arg);
if (args.length > 0)
sb.setLength(sb.getLength() - 1); // skip last space
System.out.println(sb);
}
}
With Java 8 (no difference):
public class Main {
public static void main(final String... args) {
System.out.println(String.join(" ", args));
}
}
The code which I prefer:
import static java.lang.String.join;
import static java.lang.System.out;
public class Main {
public static void main(final String... args) {
out.println(join(" ", args));
}
}
Hope this helps, have fun with Java!

Array won't replace multiples of 2

I want to replace all multiples of 2 in my array with the value 0 and I felt as though this code did this but 4,6 and 8 stay the same in the output.
Am I doing something stupidly wrong?
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
}
}
In mycase your method was working fine,It solely depends how you are invoking your method
You should invoke your method like
public static void main(String[] args)
{
int num[]={2,4,6,11,13,8};
markOfMultiples(num,2);
}
Your method remains the same
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
System.out.println(listOfNumbers[i]);//added by me to track what's going on
}
and its working fine!

Passing System.out.println(); as an argument in a method

I want to pass System.out.println(); as an argument but the compiler won't allow me to return a void type as an argument. here is what I want it for.
public class Array {
public static void main(String args[]) {
a(data());
}
static void a(e) {
System.out.println(e);
}
static void data() {
...
}
}
So What is want a(data()); to look like after it is compiled is something like this.
a(data()) = System.out.println(data(){...});
Eventually I want to shorthand System.out.println().
What you are doing here is not passing System.out.println() as an argument; you are trying to pass an argument to System.out.println()
Try changing the return type of data() to String, or int, or anything other than void, and return something of that type from it.
Also change the parameter type of e in the function definition of a() to match the return type of data().
After you make these changes, calling a(data()); will actually print something out.
Example:
public static void main(String args[]) {
a(data());
}
// shorthand for System.out.println
static void a(String e) {
System.out.println(e);
}
// a method that returns some data
static String data() {
// replace this with whatever actual data you want to return
return "This is some data...";
}
If you just want to shorthand System.out.println, then have a method with return type void that accepts a string argument and inside of the method just do:
System.out.println(argument)
As mentioned by others, you don't want/need to pass System.out.println as a method argument. However, if you would like to do that (one never knows...), you could do that in Java 8 with Lambda expressions.
Create a functional interface:
#FunctionalInterface
public interface Action {
void run(String param);
}
Passing this interface to a method:
public class MyClass {
public void execute(Action action){
action.run("Hello!");
}
}
Use this class:
MyClass c = new MyClass();
c.execute(System.out::println);
Simply save your println statements to String and return it for printing
Your code:
static void data() {
int array[] = {1,5,6};
int alength = array.length;
System.out.println(" Location\tData");
for(int i=0;i<alength;i++) {
System.out.println(" " + i + "\t\t" + array[i]);
}
}
Change to:
static String data() {
int array[] = {1,5,6};
int alength = array.length;
//Note extra \n symbol for new line
String result = " Location\tData\n";
for(int i=0;i<alength;i++) {
result += " " + i + "\t\t" + array[i] + "\n";
}
return result;
}
then modify your a() method to accept String as a parameter:
static void a(String result) {System.out.println(result);}
A working example could look like this:
public class Array {
public static void main(String args[]) {
println(data());
}
// I strongly advise to use understandable naming
// a() is completely uninformative
static void println(String result) {
System.out.println(result);
}
static String data() {
int array[] = { 1, 5, 6 };
int alength = array.length;
// Note extra \n symbol for new line
String result = " Location\tData\n";
for (int i = 0; i < alength; i++) {
result += " " + i + "\t\t" + array[i] + "\n";
}
return result;
}
}
While the compiler may not allow you to pass a function pointer, it should allow you to pass blocks.
In Objective-C; a block as the following syntax:
void (^action)(NSString *s) = ^(NSString *s){ NSLog(s); }
You can then pass your "action" block around as a parameter, and call it whenever required:
action(#"Hello World");
Blocks are available in all recent variations of C, Wikipedia has a nice article on the subject at http://en.wikipedia.org/wiki/Blocks_(C_language_extension).
I want to change this code
package Array;
import java.util.Random;
public class Array {
public static void main(String args[]) {
data();
a();
random();
a();
array();
a();
rows();
a();
System.out.println("average " + average(45,15,15,48,97,45));
}
static String s() {
return "helloWorld";
}
static void a() {System.out.println();}
static void data() {
int array[] = {1,5,6};
int alength = array.length;
System.out.println(" Location\tData");
for(int i=0;i<alength;i++) {
System.out.println(" " + i + "\t\t" + array[i]);
}
}
static void random() {
Random rdm = new Random();
int freq[] = new int[7];
for(int i=1;i<1000;i++) {
++freq[1+rdm.nextInt(6)];
}
System.out.println("Face\tFrequency");
int frequence = freq.length;
for(int face=1;face<frequence;face++) {
System.out.println(face+"\t"+freq[face]);
}
}
static void array() {
String po[] = {"lala","po","tinkiwinki","disty"};
for(String lala: po) {
System.out.print(lala + " ");
}
System.out.println();
}
static void rows() {
int arrays[][]= {{1,5,78,15},{45,67},{875,15687,158,4515,23,2,2}};
for(int i=0;i<arrays.length;i++) {
for(int j=0;j<arrays[i].length;j++) {
System.out.print(arrays[i][j]+"\t");
}
System.out.println();
}
}
static int average(int...numbers) {
int total=0;
for(int x:numbers)
total += x;
return total/numbers.length;
}
}
class time {
int h, m, s;
void setTime(int hour,int minute,int second) {
h = ((hour>=0 && hour<=24) ? hour : 0);
m = ((minute>=0 && minute<=60) ? minute : 0);
s = ((second>=0 && second<=60) ? second : 0);
}
into this type of code for main.
a(data());
a(random());
a(array());
a(rows());
a("average " + average(45,15,15,48,97,45));

Categories