I have created a JAR file that takes in 3 arguments and returns a string but my code does not seem to recognize the arguments values even when they are correct.
I assign the arguments:
if (args.length > 1)
{
raftcode = args[0];
Selection =args[1];
Option = args[2];
System.out.println("Getting arguments");
}
I have checked the values they are correct but program never enters the if statement
if (Selection == "Sightings")
{
//Get sightings text
}
else if (Selection == "Captures")
{
//Get captures text
}
else if (Selection == "Myrafts")
{
//Get my rafts text
}
else if (Selection == "Other")
{
// Get other text
}
If I run the code without the args it returns the string using the default test variables and I can output the argument values.
Any advice on what is wrong would be great :)
You should be using .equals rather than == as below
if ("Sightings".equals(Selection))
{
//Get sightings text
}
As others have said you should be comparing strings with .equals not ==. Strings can be compared with == if you use String.intern everywhere but this is still risky as it will fail if you forget so much as a single instance.
If you are using command line parameters extensively have a look as Commons CLI
Related
I have a bit of a problem with this recursion method. I'm fairly new to Java.
This method checks if an input is either "exit" only or "start" followed by two times either "user" or "easy".
It works fine except for the return. If I enter a wrong input and then a right on it returns the previous wrong input with which I obviously can't continue working, why is that?
I've had this problem before but always somehow managed to avoid it.
You might notice that I print out a valid commadnd right when it's validated, this works fine and produces the result I need. But when printing out the return of the function on line 2 the above mentioned problem takes place. I've added numbers to the printed strings so I can recognize which is which.
I have tried returning immediately when there's a valid command but I still need that retrun at the end since the function gives me an error if return statements are exclusively in conditional statements so the problem persists.
Thanks for any help!
public static void main(String[] args) {
System.out.println(setup() + "3");
}
static String setup() {
System.out.print("Input command: ");
String command = input.nextLine();
String[] split = command.split(" ");
if(!(command.equals("exit") || split.length == 3)) {
System.out.println("Invalid parameters!");
setup();
}
else {
if(command.equals("exit")) {
System.out.println("Valid parameters! Exit");
System.out.println(command + "2");
}
else if(split[0].equals("start") && (split[1].equals("easy") || (split[1].equals("user")) && split[2].equals("easy") || split[2].equals("user"))) {
System.out.println("Valid parameters! Start");
System.out.println(command + "1");
}
else {
System.out.println("Invalid parameters!");
setup();
}
}
return command;
}
first of all I think that you meant to call the recusive call as
return setup()
second of all when using conditional operator (&&, ||) you should use () for make sure you get the logic condition you expect.
if you will update it to :
return setup instead of setup()
validate what you wrap the right part of condition with Parenthesis():
else if (split[0].equals("start") && ((split[1].equals("easy") || split[1].equals("user")) && (split[2].equals("easy") || split[2].equals("user")))) { System.out.println("Valid parameters! Start"); System.out.println(command + "1"); }
I've got the following code which works except for the command line arguments, everytime i write "Insertion" it won't go in the if-statement so the output would be "Algorithm not found. Use: [ Insertion | Merge ]"
public static void main(String[] args) throws IOException, InsertionAndMergeException, Exception {
if( args.length < 2 ) {
System.out.println("Use: <path> <algorithm> ");
System.exit(1);
}
if(args[1] == "Insertion" || args[1] == "Merge"){
testWithComparisonFunction(args[0], args[1], new RecordComparatorIntField());
}else
System.out.println("Algorithm not found. Use: [ Insertion | Merge ]");
}
In command-line i'm typing this, what am I doing wrong?
java insertionandmergeusagejava/InsertionAndMer
geUsage "/home/zenoraiser/Scrivania/Università/Secondo Anno/Algoritmi/1718/LAB/Progetto/Integers.txt" "Insertion"
You're confusing == with .equals, if you change your if statement to
if ("Insertion".equals(args[1]) || "Merge".equals(args[1])) {
You should get the expected result.
In Java, the == operation takes the LHS value and compares it directly with the RHS value, this is fine for primitive types such as int, double, etc. Strings are a bit different though. Because a String is effectively an array of characters, it is stored as an Object, so the == operator will compare the pointers to the LHS/RHS (which in this case are not equal).
You can observe seemingly strange behavior around this with code like:
String a = "Test.";
String b = "Test.";
System.out.println(a == b); // true
System.out.println(a.toLowerCase() == b.toLowerCase()); // false
This is due to a process known as "String interning", which effectively stores multiple strings under the same pointer while they have the same value.
Also note that by putting the String literal first in the comparison, you remove the possibility of a NullPointerException if args[1] were to be non-existent.
So, I'm rather new to Java and I just starting a project, but I ran into some issues.
My question is... How do I link a user input (argument) with a String?
I have already defined a few Strings earlier on in my code, but in this line I want it to match up and check from the String which matches the argument and check if it contains something:
if (!cs.hasPermission("foo." + args[0]) && [CODE HERE] ){
I want [CODE HERE] to check If args[0] (user input) matches a String, if it does then check if it matches some text.
Java has a .equals() method which can be used to compare two Strings. It can used to compare two variables which hold references to String objects or to compare String literals
if( args[0].equals(someString) ) { // compare args[0] to another String variable
}
if( "someText".equals(args[0]) ) { // compare args[0] to a String literal
}
Reading through the String documentation will also be very useful to you starting out.
This is String equals api, so it should look something like:
if (!cs.hasPermission("foo." + args[0]) && args[0].equals(string){
//code
}
You can easily do it with the equals() method. But you should also check that args[0] is set.
if (args.length > 0) {
if (!cs.hasPermission("foo." + args[0]) && "StringToCompare".equals(args[0])) {
// do something
}
} else {
// handle error
}
Is it possible to have multiple arguments for a .contains? I am searching an array to ensure that each string contains one of several characters. I've hunted all over the web, but found nothing useful.
for(String s : fileContents) {
if(!s.contains(syntax1) && !s.contains(syntax2)) {
found.add(s);
}
}
for (String s : found) {
System.out.println(s); // print array to cmd
JOptionPane.showMessageDialog(null, "Note: Syntax errors found.");
}
How can I do this with multiple arguments? I've also tried a bunch of ||s on their own, but that doesn't seem to work either.
No, it can't have multiple arguments, but the || should work.
!s.contains(syntax1+"") || !s.contains(syntax2+"") means s doesn't contain syntax1 or it doesn't contain syntax2.
This is just a guess but you might want s contains either of the two:
s.contains(syntax1+"") || s.contains(syntax2+"")
or maybe s contains both:
s.contains(syntax1+"") && s.contains(syntax2+"")
or maybe s contains neither of the two:
!s.contains(syntax1+"") && !s.contains(syntax2+"")
If syntax1 and syntax2 are already strings, you don't need the +""'s.
I believe s.contains("") should always return true, so you can remove it.
It seems that what you described can be done with a regular expression.
In regular expression, the operator | marks you need to match one of several choices.
For example, the regex (a|b) means a or b.
The regex ".*(a|b).*" means a string that contains a or b, and other then that - all is OK (it assumes one line string, but that can be dealt with easily as well if needed).
Code example:
String s = "abc";
System.out.println(s.matches(".*(a|d).*"));
s = "abcd";
System.out.println(s.matches(".*(a|d).*"));
s = "fgh";
System.out.println(s.matches(".*(a|d).*"));
Regular Exprsssions is a powerful tool that I recommend learning. Have a look at this tutorial, you might find it helpful.
There is not such thing as multiple contains.
if you require to validate that a list of string is included in some other string you must iterate through them all and check.
public static boolean containsAll(String input, String... items) {
if(input == null) throw new IllegalArgumentException("Input must not be null"); // We validate the input
if(input.length() == 0) {
return items.length == 0; // if empty contains nothing then true, else false
}
boolean result = true;
for(String item : items) {
result = result && input.contains(item);
}
return result;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public void play () {
int anInteger;
//guess return code
int code;
while (true) {
String input=null;
input = JOptionPane.showInputDialog("Please enter an integer");
if (input == "-1") {
//JOptionPane.showMessageDialog(null, input);
System.exit(0);
break;
} else {
if (input==null) {
System.exit(0);
} else if (input.isEmpty()) {
continue;
} else {
anInteger = Integer.parseInt(input);
code = this.oneGuess (anInteger);
//JOptionPane.showMessageDialog(null, anInteger);
}
}
}
}
I want, if the user enter -1, show the program will not prompt the message box any more. Above is the code I have come up with, so far. Why it doesn't work?
String comparisons does NOT work with "==" operator, use "String.equals(Object)" function
input.equals("-1");
Better way would be
"-1".equals(input);
as it also takes care of null input
You are comparing strings, which are objects, with the == operator, which checks whether two object references refer to the same object instance. Instead you should use the equals method for comparing them.
There is a difference between comparing with == and equals. The first compares pointers, the latter contents. That is probably your issue.
You compare Strings with ==, which creates a problem. You can have many different String-Objects which all show "-1". The == tests, if you have exactly the same object on the left and right side. You want to know, if the objects on the left and right sie have an equal content.
Better try
input.equalsIgnoreCase("-1");
EDIT: To answer the comment: input.equalsIgnoreCase("-1") is the same as input.equals("-1") in the case of "-1" as there are no uppercase/lowercase letters in "-1". However, I prefer equalsIgnoreCase in the case of Strings, because it is defined on String, rather than on Object. Still, as the equals-definition is overridden for the String class, it works too in this example and "ignoreCase" is not needed.