How to properly use a java substring in an if test? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm reading a file line-by-line with Java and parsing the data in each line for a report. Periodically, there will be a URL that's been written to a line, and I want to bypass that line. I need to set up an if...then that tests for the presence of a URL -- in this specific case, I define that as the first four bytes of the line reading http. If the condition is true, read the next line in the file, but if the condition is false, send the current line to the parser for report output.
Simple, no? I'm running into issues where I cannot get my if..then statement to accurately recognize a true condition. My only clue is that when my inputString is equal to the test value, it passes as true. Beyond that...I can't spot anything out of the ordinary.
public class testClass
{
public static void main(String args[])
{
String inputString1 = "http://www.google.com/r";
String inputString2 = "google";
String inputString3 = "google search";
String inputString4 = "http";
parseInput(inputString1);
parseInput(inputString2);
parseInput(inputString3);
parseInput(inputString4);
}
//
private static void parseInput(String inputString8) {
int httpFlag;
if (inputString8.substring(0,4) == "http")
{ httpFlag = 1467; } else
{ httpFlag = 10644; }
System.out.println(inputString8+" "+inputString8.toLowerCase().substring(0,4)+" "+httpFlag);
}
}
Here's my output:
http://www.google.com/r http 10644
google goog 10644
google search goog 10644
http http 1467
I am expecting 1467 for both inputString1 and inputString4.
The console appears to display my input and substring properly, and nothing in the Java Documentation suggests that my substring would be a char array or anything apart from a string, so I can't figure out why http as the first four bytes of a 4-byte string is "different" from the first four bytes of a (4+x)-byte string. What am I missing?

Compare strings with equals, not ==. There's nothing special about the fact the string you're comparing is the result of calling substring.

use if (inputString8.substring(0,4).equals("http")).
== operator checks if the two expressions are the same object, you want to check if they have the same value.

== tests to see if two things are the same object. If you want to compare strings char by char use the equals () method of the String class.

Related

Address with zip code. Java

The constructor will throw an IllegalArgumentException exception with the message "Invalid Address Argument" if any parameter is null, or if the zip code has characters others than digits.
The method Character.isDigit can help during the implementation of this method. See the Java API (Character class) for additional information.
I've had the illegal argument exception down. But, not the zip code. Help?
Program.
if(street==null||city==null||state==null){
throw new IllegalArgumentException("Invalid Address Argument");
}
if(zip == Character.isDigit(ch)){
//To do???
}
try apache stringutils
public static boolean isNumeric(CharSequence cs)
Checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false.
null will return false. An empty CharSequence (length()=0) will return false.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = false
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
cs - the CharSequence to check, may be null
Returns:
true if only contains digits, and is non-null
Since:
3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence), 3.0 Changed "" to return false and not true
int zipcode = 0;
try {
zipcode = Integer.parseInt(zipcode);
}catch (Exception e){}
if (zipcode <= 0)
{
throw new Exception(..);
}
And less than 1,000,000 if you want to be precise. You are using Char which makes no sense as you will have a String.
This sounds like homework to me, so I think the first thing you need to do here is learn how to read the documentation. Let's start by taking your instructor's hint, and looking up the documentation for Character.isDigit(char ch)
public static boolean isDigit(char ch)
Handwaving away some of the terms there, the critical things are that the method is static (which means we call it like Character.isDigit(myVariable) and that it returns a boolean (true or false value), and that it accepts a parameter of type char.
So, to call this method, we need a char (single character). I'm assuming that your zip variable is a String. We know that a string is made up of multiple characters. So what we need is a way to get those characters, one at a time, from the String. You can find the documentation for the String class here.
There's a couple of ways to go about it. We could get the characters in an array using toCharArray(), or get a specific character out of the string using charAt(int index)
However you want to tackle it, you need to do this (in pseudocode)
for each char ch in zip
if ch is not a digit
throw new IllegalArgumentException("Invalid Address Argument")

Why is this if-statement not working? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I've been working on a small personal project and mainly polishing the IO aspect of the program.
I'm mainly having trouble with one method, which is responsible of calling two methods that read one line of text document and dissect it to find a certain string.
public boolean noSavedGame(){
boolean noGameFound = false;
read(); //method reads the text document that can have multiple lines
String temp = find(); //method finds the property and returns it in a string
if(temp == "none"){
System.out.println("Saved game not found");
noGameFound = true; //a saved game WAS NOT FOUND
}
else{
System.out.println("saved game found");
noGameFound = false; //a saved game WAS FOUND
propertyDetail = temp;
}
return noGameFound;
}
So, the first line of the text document looks like this:
<pastSavedGame> - none
read() correctly takes that line and find() correctly returns "none" as its supposed to return the property.
But the conditional is not working right. Even though temp equals "none", the if-statement is executed, not the else statement. At first, I thought whitespace was an issue, but does not seem to be a factor.
I apologize for what may be a very simple question, but I am new to Java. Thank you for the help.
To compare strings use equals() instead of ==.
equals() compares the content; == checks whether it is the same instance.

String compare function equals not giving correct result

I am using eclipse with java
I am trying to compare two string removing all the space between them.
Here is my code
First I am removing whitespace within the Strings.
System.out.println("["+StringUtils.deleteWhitespace(s4)+"]");
System.out.println("["+StringUtils.deleteWhitespace(s3)+"]");
// comparing Strings
if(s4.equals(s3))
{
System.out.println("Text Match");'
}
Below is the output from lines 1 and 2 that is displaying on Eclipse console:
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
From what I can see, there is no difference between two string yet it is displaying string as a mismatch.
You did not assign the results of the deleteWhitespace() operation to anything. Your two strings will therefore remain unchanged.
Store the result like so, before printing it:
s4 = StringUtils.deleteWhitespace(s4);
The method StringUtils.deleteWhitespace(s4) does not change the String referenced by s4 (Strings are immutable) but returns a new string.
If you do the following code:
s3 = StringUtils.deleteWhitespace(s3);
s4 = StringUtils.deleteWhitespace(s4);
if (s4.equals(s3)) {
System.out.println("Text Match");'
}
Then you will see that the two strings are really equal and the "Text Match" is printed.

String replace and output in Java [duplicate]

This question already has answers here:
Java String replace not working [duplicate]
(6 answers)
Closed 9 years ago.
I got a query, please see code below:
public void readFile(String path,String pathName,int num){
try{
PrintWriter out2=new PrintWriter(new PrintWriter(path));
File a=new File(pathName);
Scanner b=new Scanner(a);
while(b.hasNextLine()){
String message=b.nextLine();
Scanner h=new Scanner(message);
while(h.hasNext()){
String f=h.next();
if (f.equals("are")){
f.replace("are","ARE");
}
}
out2.printf("%s",message);
out2.println();
.......
The file content for scanner read is
who are you?
how are you?
what is up!
However, when I run the above codes and the output to the new file are the same with the input file, it means the "are" not replaced by "ARE", I have no idea which part is wrong, please advise, thanks guys!
This line just outputs the message unchanged to the new file.
out2.printf("%s",message);
Also the loop is strange too: why do you read it word by word, and then use String.replace()? You could do it line by line, using String.replaceAll():
while(h.hasNextLine()){
String message=b.nextLine();
out2.printf("%s",message.replaceAll("(^|\\W)are(\\W|$)"," ARE "));
}
The (^|\\W)are(\\W|$) string is a regular expression, having the meaning to match all content, that starts with either being the start of the string ^, or a non-word character (\\W), the string are, and ends with a non-word character or the end of line($)...
As scanner has whitespace as the default delimiter, it might be ever better to use (^|\\s)are(\\s|$), however both these will replace the whitespace before and after "ARE" with a single space ()...
Also, keep in mind, that String.replace does not mutate the input String... You have to assign the result, or use it any other way, like pass it to a function...
String is final and immutable, which is the same.
so f.replace("are","ARE"); must be inserted into a new or not variable.
f = f.replace("are","ARE");
I do not understand why you are doing that. Here is an alternative approach:
Get a BufferedReader to read the file.
While there is data in the file, read the lines.
If line.contains("are") then line = line.replace("are","ARE")
println(line)
As to why your code did not work:
In this line, f.replace("are","ARE"); You forgot to get the output.
Make it as such: message = f.replace("are","ARE");
Another option is to use StringBuffer or StringBuilder
Strings are immutable. Therefore, you can not run the replace method on object f and expect its value to be changed since the replace method of a string object will simply return a new String object.
either use a StringBuilder instead, or use :
f = f.replace
On the other hand, StringBuilder objects are mutable. Therefore, you can run the StringBuilder version of the replace method directly on the object if you choose that route instead.

Reversing a string without using any built in methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Printing reverse of any String without using any predefined function?
Please advise how to reverse a string without using built in methods. I want to use only string class, please advise let say there is a string "john is a boy" and print "yob a si nhoj".
This method will return the string backwards. all you have to do is iterate through the string backwards and add it to another string.
you do this using a for loop, but first check if the string has a greater lenght than 0.
Java Strings have a method "charAt(index)" which return a single character on the position of the string, where position 0 is the first character. so if you would like to reverse "Boy" you would start on letter 2, then 1, and then 0, and add them all together into a new String, resulting in "yoB".
public static String reverseString(String inString) {
String resultString = "";//This is the resulting string, it is empty but we will add things in the next for loop
if(inString.length()>0) {//Check the string for a lenght greater than 0
//here we set a number to the strings lenght-1 because we start counting at 0
//and go down to 0 and add the character at that position in the original string to the resulting one
for(int stringCharIndex=inString.length()-1;stringCharIndex>=0;stringCharIndex--) {
resultString+=inString.charAt(stringCharIndex);
}
}
//finaly return the resulting string.
return resultString;
}
You could iterate through all the characters in your string and prepend them to a StringBuffer using the insert(0, char) method. Then at the end of the iteration, your StringBuffer will be the reversed string.

Categories