Java input from terminal strange behavior - java

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.

Related

Problems with String Input [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So, for some reason I'm having problems just USING a string input.
I don't know why. Maybe it's some incredibly stupid thing everyone knows, but I don't.
Here's the non-functioning code:
import javax.swing.*;
public class Thing {
public static void main(String[] args) {
String input;
JOptionPane.showMessageDialog(null,"Welcome to the test...");
input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
String i = input;
if(i == "Yes") {
tutorial();
} else if(input=="'Yes'") {
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
} else {
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
}
Yes, I actually do have a tutorial method somewhere else, and it works fine.
The main problem is that if I enter 'Yes' or Yes, it still goes to the final else.
I only put in the
String i = input;
and changed it from
if(input == "Yes") {
because it didn't work then, either.
So what am I doing wrong?
Don't use the == operator to compare Strings, use equals() instead, as thoroughly explained here, here, here, here or any of the numerous duplicates.
if ("Yes".equals(input))
Or even
if ("yes".equalsIgnoreCase(input))
Notice that the operation is invoked on the "yes" literal to avoid a possible NullPointerException in the case input was null and the operation was invoked on it (Yoda condition).
From the Java Language Specification, Chapter 15 - Expressions, section 21 - Equality Operators:
15.21.3. Reference Equality Operators == and !=
While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (§3.10.5). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).
As mentioned, the problem is that you are comparing this String using the == comparator, not the .equals() method.
If you are running on Java 7, my advice, for a cleaner solution, would be also to wrap this in a switch statement:
JOptionPane.showMessageDialog(null,"Welcome to the test...");
String input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
switch (input) {
case "Yes":
tutorial();
break;
case "'Yes'":
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
break;
default:
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}

While loop dosnt work properly in my programm [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to ask user to insert operator and get the answer till user enters keys other than +,-,* or \ .I did the program like this.But it will not work properly.Its looping even for other keys.What is the problem with the coding?
public static void main(String Args[]) throws IOException
{
InputStreamReader myrdr=new InputStreamReader(System.in);
BufferedReader myBfr=new BufferedReader(myrdr);
Scanner myScanner=new Scanner(System.in);
String mathOp;
float Res,Num1,Num2;
System.out.print("Mathematical Operator :");
mathOp=myBfr.readLine();
Res=0;
while(mathOp!="+"||mathOp!="-"||mathOp!="*"||mathOp!="\\")
{
System.out.print("Enter number one: ");
Num1=myScanner.nextInt();
System.out.print("Enter Number Two: ");
Num2=myScanner.nextInt();
switch(mathOp)
{
case "+":
Res=Num1+Num2;
break;
case "-":
Res=Num1-Num2;
break;
case "\\":
Res=Num1/Num2;
break;
case "*":
Res=Num1*Num2;
break;
default:
{
System.out.println("Programme Exits");
return;
}
}
System.out.println("Answer is : "+Res);
System.out.print("Mathematical Operator :");
mathOp=myBfr.readLine();
}
}
Don't use == (which compares if the 2 operands are the same String object, which they aren't), use equals() (which compares if the contents of the 2 String objects are the same).
But better yet, simplify your code to this:
while (!"+-*\\".contains(mathOp))
btw, divide is usually a normal slash /, not a backslash \.
Yoy have to use someting like that
while((!mathOp.equals("+"))||(!mathOp.equals("-"))||(!mathOp.equals("*"))||(!mathOp.equals("\")))
First of all you should know the proper use of || and &&
True || False returns true
True || False || False || False returns true,one True is enough to make the condition return true no matter how many false you have
So in your case you are saying that if the input is different from one of them than let it proceed,so if you have + it will enter since + is different that -. You should instead use &&.
True && False returns False
True && True && True && False returns False. One False is enough to return False no matter how many True you have.
If you use && you would be telling the condition to return true only if all the sub-conditions are true,i.e it is different than + and different than - and different than * and different than .
Moreover, replace your "+" by '+' because the latter it is a character while the first is a string. == can be used only on characters,numbers and boolean values. To compare Strings you should use .equals("x")
Make your while loop like this
while(mathOp.equals("+") || mathOp.equals("-") ||
mathOp.equals("//") || mathOp.equals("*"))
Use String.equals() to compare string in Java, not == or !=. To explain more, you shouldn't use == or != while comparing String values in Java because they check for equality for the values in the right and left operands. i.e a memory address in case of String objects ,which will not be equal for two different objects. You can make use of == and != with primitive datatypes and compile time constants. There is also a concept called String constant pool which has the compile time String constants created by using assignment operator like String new = "new"; without using new operator during object creation which can be compared using == or !=.

How do I link a user input argument with a string?

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
}

Multiple arguments for !somearray.contains

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

Java .getText vs. Hard Coded String not returning the same results

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.

Categories

Resources