Command line arguments [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I've created a class called Human that works properly, it takes 2 arguments, age and name, to create a human.
To create a Human with command line arguments, I want to write
java Filename -H "Anna" 25
And it should create a Human with thatname="Anna", and thatage=25, where 25 is an int.
The code I've written is creating a list called Argument, and iterating through it to find -H. I need to do this because I'm going to be using this to create different classes later. I just need help with the syntax on the lines where I've written thename=, and theage=, because I don't know how to get the next item in list, and next-next item in list.
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (String item2: Argument) {
if (item2 == "-H") {
thatname = Argument.get(item2+1)
thatage = Argument.get(item2+2)
Human person = new Human(thatname,thatage);
System.out.println(person);
}

Why not just loop the args?
for ( int i = 0; i < args.length; i++ ) }
if (args[i].equals("-H")) {
i++;
thatName = args[i];
i++;
thatAge = args[i];
}
}
You should add some code to catch if one does not follow the rules you have set. Probably not enough arguments or other things humans do at the keyboard...

thatname = Argument.get(Argument.indexOf(item2)+1);
thatage = Argument.get(Argument.indexOf(item2)+2);
OR you know that 1st element is -H, 2nd element is name and 3rd is age, so you can use below code directly
thatname = Argument.get(1);
thatage = Integer.parseInt(Argument.get(2));

Your code have some problems, let me explain them to you for your assistance.
You cannot compare Strings with == you have to use equals method
in the String to compare between two Strings.
You have to use this for loop for(int i = 0; i < Argument.size();
i++) syntax so that you can iterate from zero to the number of
items in the list.
get method in ArrayList take the index as parameter and return the value at that index.
You can add i += 2 to skip the next two iterations which will
return the name and age value of the human. (It is optional)
Here is the working code:
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
String currentItem;
for (int i = 0; i < Argument.size(); i++) { // it will iterate through all items
currentItem = Argument.get(i); // getting the value with index;
if (currentItem.equals("-H")) {
String thatname = Argument.get(i+1);
String thatage = Argument.get(i+2);
i += 2; // Skipping 2 iterations of for loop which have name and age human.
Human person = new Human(thatname,thatage);
System.out.println(person);
}
}
}

You cannot iterate the list using String. When iterating a list you required a index number like list.get(indexNumber);
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (int i=0;i<args.length;i++) {
if (args[i].trim().equals("-H")) {
i++;
thatname = Argument.get(i);
i++;
thatage = Argument.get(i);
Human person = new Human(thatname,thatage);
System.out.println(person.getName()+" "+person.getAge());
}

Why using array list when you can directly use args? and while you're having only two parameters don't use a for loop access them direclty.
One thing you should know is that String is an object in java so comparing two Strings with == sign will return false even if they have same value (== will compare the id of the object), you should use .equale() function to compare the value of the object.
Check out this code :
public static void main(String[] args) {
if(args.length>0)
{
try{
if (args[0].equals("-H")) {
Human person = new Human( args[1],args[2]);
System.out.println(person);
}
}catch(ArrayIndexOutOfBoundsException exception) {
System.out.println("error with parameters");
}
}else
System.out.println("No command");
}

Related

Passing strings to an array through a method [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Implement a method for adding elements to the class CacheMemory.
The Class cache memory has an array memory whose length is passed through a constructor.Elements can be added to the array only if it has not been added before and if the length of the arrays added is within the boundaries of the array.(within its length).
This is the code I came up with so far:
public class CacheMemory {
private String[] memory;
public CacheMemory(int length) {
this.memory = new String[length];
}
public void addingElementsToCache(String mem) {
for (int i = 0; i < memory.length; i++) {
if (memory[i] != mem) {
memory[i] = mem;
System.out.println(mem);
break;
} else {
System.out.println("Element already exists");
}
}
}
}
If i call this method without break,of course it will print out the string five times,but I don't want the same string to be printed out five times,I want to add five different strings and then,while loop goes through the array,and comes to element that has already been passed,to print out the message.
Actually , you need to use !string.equals("anotherString") instead of !=,since the != only compare the address of the string ,instead of the content of the string,but the method equals does it.
You got some of the logic wrong. You have to wait until you have checked all elements in the cache before you can decide that it doesn't already exist. And also, you should use .equals() for comparing Strings.
public void addingElementsToCache(String mem)
{
// Loop over slots
for (int i = 0; i < memory.length; i++)
{
if (memory[i] == null) {
// You have reached an unused slot, use it!
memory[i] = mem;
System.out.println(mem);
return;
}
else if (mem.equals(memory[i])) {
// You found a duplicate
System.out.println("Element already exists");
return;
}
}
// You have checked all positions without finding an empty slot
System.out.print("The cache was full, unable to add!");
}
If you exercise this code with
public static void main(String[] args)
{
CacheMemory cache = new CacheMemory(10);
asList("foo", "foo", "bar", "boz", "bar")
.forEach(cache::addingElementsToCache);
}
... it will print the following, which is what I think you expect:
foo
Element already exists
bar
boz
Element already exists

How do I make this get method for array lists simpler? [duplicate]

This question already has answers here:
Ways to iterate over a list in Java
(13 answers)
Closed 7 years ago.
import java.util.*;
public class ChristmasParty
{
private Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
ChristmasParty cp = new ChristmasParty();
cp.run();
}
public void run()
{
menu();
addName();
}
public void menu()
{
System.out.println("Welcome to the guests lists program");
System.out.println("Enter a name or enter X to quit");
}
public void addName()
{
String nameAdded = "";
ArrayList<String> guestsLists = new ArrayList<String>();
do
{
System.out.print("Enter a name: ");
nameAdded = input.nextLine();
guestsLists.add(nameAdded);
System.out.println("-----------------------------------------------");
System.out.println(nameAdded + " has been added to the guests list.");
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
System.out.println(guestsLists.get(0));
System.out.println(guestsLists.get(1));
System.out.println(guestsLists.get(2));
System.out.println(guestsLists.get(3));
System.out.println(guestsLists.get(4));
System.out.println(guestsLists.get(5));
System.out.println(guestsLists.get(6));
System.out.println(guestsLists.get(7));
System.out.println(guestsLists.get(8));
System.out.println(guestsLists.get(9));
System.out.println(guestsLists.get(10));
System.out.println(guestsLists.get(11));
System.out.println(guestsLists.get(12));
System.out.println(guestsLists.get(13));
System.out.println(guestsLists.get(14));
System.out.println(guestsLists.get(15));
}
}
Hello, I am trying to make a code that will prompt the user to enter a name,and that name will be saved in the arraylists, and then once the user exits and quits by pressing "X", it will display all the names in the lists. However how do I make the System.out.println(guestsLists.get()); codes simpler rather than typing it all out?
Put this code:
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
for(int i = 0; i < guestsLists.size(); i++)
{
System.out.println(guestsLists.get(i));
}
OR
for(String s : guestsLists)
{
System.out.println(s);
}
And remove all the sysouts after the
System.out.println("========================");
Simply iterate through the list using an enhanced for loop:
...
for (String name : guestsLists) {
System.err.println(name);
}
...
You can use that form of a for loop when you do not need an index inside the loop, but just want to iterate over the collection. In these cases, it is much easier to read (and less code) than using an explicit index (or using an explicit Iterator).
See also https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

ArrayIndexOutOfBoundsException converting C# to Java

I'm working on a program that will go through a list of records (IDs and Tickets) and parse them into two list respectively. It will also cross search the lists to see which IDs have a corresponding ticket based on names. Here is a link to an earlier version: here
Now, I've been rewritting with the help of some C# code from a coworker, but I'm having trouble with a parsing method. Here is the C# version:
public void parseLine(string _line)
{
if(string.IsNullOrWhiteSpace(_line)){ return;}
code = _line.Substring(0, 3);
ticketID = _line.Substring(3, 10);
string tmp = _line.Substring(13).Trim();
//get the first and last name
string [] tmp1 = tmp.Split(",".ToCharArray());
if(!(tmp1.Length > 1))
{
throw new Exception("unable to get the first and last name");
}
lastname = tmp1[0];
firstname = tmp1[1].Trim();
}
Here is my Java version:
public void parseLine(String line) throws Exception {
// code will store Ticket code *Alpha ticketId will store 10
// *digit code
code = line.substring(0, 3);
ticketId = line.substring(3, 10);
// tmp will store everything afterthe first 13 characters of
// line and trim the name(s)
String tmp = line.substring(13).trim();
// tmp1 array
String[] tmp1 = tmp.split(".*,.*");
if (tmp1.length > 1) {
throw new Exception("UNABLE TO GET NAME");
}
last = tmp1[0];
first = tmp1[1].trim();
}
This is in a seperate class, that will model the people with tickets. My main class(so far) which invokes the actual parseLine method is as follows:
public class ParkingTickets {
public static void main(String[] args) throws
FileNotFoundException, Exception {
ArrayList<TicketPeople> tickets = new ArrayList<>();
HashMap<String, List<SbPeople>> people = new HashMap<>();
File srcFile = new File("source.txt");
Scanner myScanner = new Scanner(srcFile);
while (myScanner.hasNextLine()) {
String line = myScanner.nextLine();
//System.out.println(line);
if (line.matches("^\\p{Alpha}.*$")) {
//System.out.printf("Ticket: %s%n", line);
TicketPeople t = new TicketPeople();
t.parseLine(line);
tickets.add(t);
}
myScanner.close();
}
}
}
the compiler points at the if statement in the parseLine method, and obviously the parseLine method in main class, when I tried stepping through that sepcifiv line, I see that it's starts parsing the the data from the source file but something is off. From the documentation the error means: Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
I used an ArrayList for the ticket list and from what I understand it is a dynamic list that does not need to be set with a specific index size. I'm still learning and am having trouble understanding this exception. I would greatly appreciate any help.
Your call to split() in Java, doesn't match the split() from C#.
// String[] tmp1 = tmp.split(".*,.*");
String[] tmp1 = tmp.split(","); // <-- ",".
also, your check logic seems to have been reversed. But, I would suggest
if (tmp1.length != 2) {
throw new Exception("UNABLE TO GET NAME");
}
1) In C# it is Substring(int startIndex, int length). In java String substring(int startindex, int endindex).
2)The java code has also changed the exception logic. In C# code ther eis a not if(!(tmp1.Length > 1)), whereas in java code, if (tmp1.length > 1)

Array in Method Header: error ']' expected (Java)

I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!

java : mapping the Values from Enumeration to Object

I have a Enumeration as shown in below program
public class Test {
public static void main(String args[]) {
Vector v = new Vector();
v.add("Three");
v.add("Four");
v.add("One");
v.add("Two");
Enumeration e = v.elements();
load(e) ; // **Passing the Enumeration .**
}
}
There is also a Student Object
public Student
{
String one ;
String two ;
String three ;
String four ;
}
i need to pass this Enumeration to another method as shown below
private Data load(Enumeration rs)
{
Student stud = new Student();
while(rs.hasMoreElements())
{
// Is it possible to set the Values for the Student Object with appropiate values I mean as shown below
stud.one = One Value of Vector here
stud.two = Two Value of Vector here
stud.three = Three Value of Vector here
stud.four = Four Value of Vector here
}
}
Please share your ideas on this .
Thanks
Sure. You could use the elementAt method, documented here, to get the value you wanted. Do you have a specific reason you are using a Vector? Some of the List implementations might be better.
Enumerations don't have the idea of "first value", "second value", etc. They just have the current value. You could work around this in various ways:
The easy way -- convert it to something easier to work with, like to a List.
List<String> inputs = Collections.list(rs);
stud.one = inputs.get(0);
stud.two = inputs.get(1);
// etc.
Keep track of the position yourself.
for(int i = 0; i <= 4 && rs.hasNext(); ++i) {
// Could use a switch statement here
if(i == 0) {
stud.one = rs.nextElement();
} else if(i == 1) {
stud.two = rs.nextElement();
} else {
// etc.
}
}
I really don't recommend either of these things, for the following reasons:
If you want your parameters in a particular order, just pass them in that way. It's much easier and it's also easier to maintain (and for other people to read).
void example(String one, String two, String three, String four) {
Student student = new Student();
student.one = one;
student.two = two;
// etc.
}
You shouldn't use Enumeration at all, since it's been replaced with Iterator and Iterable since Java 1.2. See ArrayList and Collection.

Categories