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
}
Related
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.
I want the following if statement to compare against multiple strings but when i compare against more than one it gives me the error message that I created. Below is the code which does not work.
The variables are test = 'c3400553' and test2 = 'c3400554'
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
!uname.getText().toString().equals(test) ||
!uname.getText().toString().equals(test2)
) {
uname.setError("Incorrect ID Format");
}
Below is the code which works for one comparison.
String test = "c3400553";
...
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
!uname.getText().toString().equals(test)
) {
uname.setError("Incorrect ID Format" );
}
I don't understand what the issue is
That's because you either need to remove some !, or you need to replace your || by &&.
It depends on what you are trying to achieve. If you want the id to be declared incorrect if it doesn't match the format AND if it is not equal to test AND ALSO not equal to test2, then the solution is this :
if (!uname.getText().toString().matches("[cC][0-9]{7}") &&
!uname.getText().toString().equals(test) &&
!uname.getText().toString().equals(test2) ) {
uname.setError("Incorrect ID Format" );
}
Otherwise, if what you want to do is to check whether uname matches the format, and is NOT equal to test and test2, then the problem is that you need to remove the ! before comparisons with test and test2 :
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
uname.getText().toString().equals(test) ||
uname.getText().toString().equals(test2) ) {
uname.setError("Incorrect ID Format" );
}
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;
}
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
I am completely stumped with this one . . .
If I call the function below with the following:
Search(SearchTextField.getText()); // (Fiberglass was entered)
Search("Fiberglass"); // hardcoded
I get the following results:
Fiberglass 10 Not Here
Fiberglass 10 String found!
Same String is passed with the same length, different results. How can this be?
Yes I've trimmed it on both sides of the == with no luck.
I am loosing my mind, any help would be appreciated.
Test[] array = new Test[3];
array[0] = new RowBoat("Wood", "Oars", 10);
array[1] = new PowerBoat("Fiberglass", "Outboard", 35);
array[2] = new SailBoat("Composite", "Sail", 40);
public void Search(String searchString) {
boolean found = false;
System.out.print(searchString + " " + searchString.length() + " ");
for (int i = 0; i < array.length; i++) {
if (searchString == array[i].getBoatMaterial()) {
found = true;
break;
}
}
if (found) {
System.out.println("String found!");
} else {
System.out.println("Not Here");
}
}
Use the .equals() method when you're comparing Strings. Do not use ==
equals() will compare the actual String content, no matter where the String resides in memory.
if (searchString.equals(array[i].getBoatMaterial())) {
Since String variables are references in Java, when you code
if (searchString == array[i].getBoatMaterial()) {
What you are actually doing is comparing two pointers. It just so happens that when you hardcode the same string in multiple places in your program the compiler reduces it to one instance (since Strings are immutable) and reuses it. This is why using a hardcoded value succeeds, since both pointers point to the same value. However, when the search string is not the same hardcoded "Fiberglass", the two strings are at different locations and the comparison fails. To compare two strings use the String.equals(String) method instead.
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.