I was wondering how I should write this if statement in my assignment.
The question is:
Print option 2 if one of the strings begins with the letter w or has 5 characters.
I would use the .contains to find the "w".
if (two.contains("w") {
System.out.println(two);
but the one with the characters I am unsure how to find the method.
If you have a List or Set, you may need to loop over them one by one, to do the actual comparing try this:
(two.startsWith("w") || two.length() == 5) {
System.out.println(two);
}
The first condition checks if given String object starts with given char, and the other one counts the number of characters in the String and checks your desired lenght, which is 5.
For more useful information and String object has, check this out String (Java Platform SE 7)
String aString = ".....";
if (aString.startsWith("w") || aString.length() == 5) {
System.out.println("option 2");
}
The method .contains returns true if find a substring (in this case "w") in string. You should use .startsWith method.
Related
I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan
I want to be able to print a string that doesn't contain the words "Java", "Code" or "String", though I am unsure on how to achieve this as I thought this would be achieved by using '!' (NOT). However, this is not the case as the string is still printed despite the inclusion of the words I want to forbid.
Any advice on how to achieve this would be greatly appreciated, thanks in advance.
System.out.println("Type in an input, plez?");
String userInput6 = inputScanner.nextLine();
if (!userInput6.toLowerCase().contains("Java") || !userInput6.toLowerCase().contains("Code") || !userInput6.toLowerCase().contains("String")) {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
} else {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
}
I thought this would be achieved by using '!' (NOT)
It is. You just haven't applied it correctly to your situation:
You start with this statement:
userInput6.toLowerCase().contains("java") ||
userInput6.toLowerCase().contains("code") ||
userInput6.toLowerCase().contains("string")
which checks if the input contains any of these, and you wish to negate this statement.
You can either wrap the entire statement in parentheses (()) and negate that:
!(userInput6.toLowerCase().contains("java") ||
userInput6.toLowerCase().contains("code") ||
userInput6.toLowerCase().contains("string"))
or apply the DeMorgan's law for the negation of disjunctions which states that the negation of a || b is !a && !b.
So, as Carcigenicate stated in the comments, you would need
!userInput6.toLowerCase().contains("java") &&
!userInput6.toLowerCase().contains("code") &&
!userInput6.toLowerCase().contains("string")
instead.
Your statement is simply checking if the string doesn't contain at least one of these substrings. This means the check would only fail if the string contained all of these strings. With ||, if any operand is true, the entire statement is true.
Additionally, mkobit makes the point that your strings you are checking for should be entirely lowercase. Otherwise, you are checking if a .toLowerCased string contains an uppercase character - which is always false.
An easier way to think of it may be to invert your if statement:
if (userInput6.toLowerCase().contains("Java") ||
userInput6.toLowerCase().contains("Code") ||
userInput6.toLowerCase().contains("String")) {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
} else {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
}
Since you're using logical OR, as soon as one your contains checks it true, the entire condition is true. You want all the checks to be true, so you need to use logical AND (&&) instead
As #mk points out, you have another problem. Look at:
userInput6.toLowerCase().contains("Java")
You lower case the string, then check it against a string that contains an uppercase. You just removed all uppercase though, so that check will always fail.
Also, you can use regexp :)
boolean notContains(String in) {
return !Pattern.compile(".*((java)|(code)|(string)).*")
.matcher(in.toLowerCase())
.matches();
}
Or just inline it:
System.out.println("Type in an input, plez?");
String userInput6 = inputScanner.nextLine();
if (!Pattern.compile(".*((java)|(code)|(string)).*")
.matcher(userInput6.toLowerCase())
.matches()) {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
} else {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to make a simplified version of Black Jack in Java using eclipse. I'm trying to make it so the player types 'hit' or 'stand', and while they haven't, it keeps prompting them to do so.
while (hitorstand != ("hit") || hitorstand != ("stand"))
{
System.out.println("Would you like to hit or stand?(1 for hit, 2 for stand)");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
}
if (hitorstand.equals("hit"))
{
playercard3 = random.nextInt(10) +2;
System.out.println(""+playercard3);
}
else if (hitorstand.equals("stand"))
{
System.out.println("You had a total value of " + playercardtotal + ".");
if (hiddendealercard == card2)
When I run it, no matter what I type it cannot escape the while loop. I know it would work if I used numbers but I really want to learn how to use words as input.
while (hitorstand != ("hit") || hitorstand != ("stand")) // This is not the right way
Use the equals() method for String value comparison. == is for object reference comparison.
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")) // This is
I'm not sure why you'd use the != in the while loop condition, whereas you've properly used (hitorstand.equals("hit")) just below the while, in a if statement.
Also, there seems a minor mistake in the while loop block.
hitorstand.toLowerCase(); // This does nothing
As Strings are immutable in java, you need to assign back the changed string to be able to see the changes
hitorstand = hitorstand.toLowerCase(); // Assigning back the lowercase string back to hitorstand
You need to use .equals(..) instead of ==. This is because == is used for reference equality, while .equals() is simply for value equality.
For example:
while(!hitorstand.equals("hit") || !hitorstand.equals("stand"))
Comparing hitorstand != ("hit") you actually compare object references not the String value itself. To compare strings you need to use equals method. In java every class inherits equals ( from Object ) and it can be overriden for custom object comparison
Try this:
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")){
Adding to the answers, a good rule of thumb is to use .equals() with strings and == with integer values or variables with integer values (or the value null).
One way you could do this would be to use a character. For example: instead of
while (hitorstand != ("hit") || hitorstand != ("stand"))
you could have it check for the first character in the string using the charAt() command with the index of the string in the parenthesis. So since your looking for the first character, it would be at index 0.
while (x != 'h' || x != 's')
x being a char.
Inside your while loop,
System.out.println("Would you like to hit or stand?");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
x = x.charAt(0); // you would just add this line. This gets the character at index 0 from the string and stores it into x. So if you were to type hit, x would be equal to 'h'.
Your if statement could stay the same or you could also change the condition to (x == 'h') and (x == 's'). That's up to you.
I am doing a homework assignment for my Computer Science course. The task is to get a users input, remove all of the vowels, and then print the new statement.
I know I could easily do it with this code:
string.replaceAll("[aeiou](?!\\b)", "")
But my instructor wants me to use nested if and else if statements to achieve the result. Right now I am using something like this:
if(Character.isLetter('a')){
'do something'
}else if(Character.isLetter('e')){
'do something else'
But I am not sure what to do inside the if and else if statements. Should I delete the letter? Or is there a better way to do this?
Seeing as this is my homework I don't want full answers just tips. Thanks!
I think what he might want is for you to read the string, create a new empty string (call it s), loop over your input and add all the characters that are not vowels to s (this requires an if statement). Then, you would simply print the contents of s.
Edit: You might want to consider using a StringBuilder for this because repetitive string concatenation can hinder performance, but the idea is the same. But to be honest, I doubt it would make a noticeable difference for this type of thing.
Character.isLetter('a')
Character.isLetter(char) tells you if the value you give it is a letter, which isn't helpful in this case (you already know that "a" is a letter).
You probably want to use the equality operator, ==, to see if your character is an "a", like:
char c = ...
if(c == 'a') {
...
} else if (c == 'e') {
...
}
You can get all of the characters in a String in multiple ways:
As an array with String.toCharArray()
Getting each character from the String using String.charAt(index)
I think you can iterate through the character check if that is vowel or not as below:
define a new string
for(each character in input string)
//("aeiou".indexOf(character) <0) id one way to check if character is consonant
if "aeiou" doesn't contain the character
append the character in the new string
If you want to do it in O(n) time
Iterate over the character array of your String
If you hit a vowel skip the index and copy over the next non vowel character to the vowel position.
You will need two counters, one which iterates over the full string, the other which keeps track of the last vowel position.
After you reach the end of the array, look at the vowel tracker counter - is it sitting on a vowel, if not then the new String can be build from index 0 to 'vowelCounter-1'.
If you do this is in Java you will need extra space to build the new String etc. If you do it in C you can simply terminate the String with a null character and complete the program without any extra space.
I don't think your instructor wanted you to call Character.isLetter('a') because it's always true.
The simplest way of building the result without regexp is using a StringBuilder and a switch statement, like this:
String s = "quick brown fox jumps over the lazy dog";
StringBuffer res = new StringBuffer();
for (char c : s.toCharArray()) {
switch(c) {
case 'a': // Fall through
case 'u': // Fall through
case 'o': // Fall through
case 'i': // Fall through
case 'e': break; // Do nothing
default: // Do something
}
}
s = res.toString();
System.out.println(s);
You can also replace this with an equivalent if, like this:
if (c!='a' && c!='u' && c!='o' && c!='i' && c!='e') {
// Do something
}
I have a strange problem when adding a value to a String array which is later involved in an array sort using a hash map. I have a filename XFR900a, and the XFR900 part is added to the array using the following code;
private ArrayList<String> Types = new ArrayList<String>();
...
Types.add(name.substring(0,(name.length() - 1));
System.out.println(name.substring(0,(name.length() - 1));
I even print the line which gives "XFR900", however the array sort later on behaves differently when I use the following code instead;
Types.add("XFR900");
System.out.println(name.substring(0,(name.length() - 1));
which is simply the substring part done manually, very confusing.
Are there any good alternatives to substring, as there must be some odd non ascii character in there?
Phil
UPDATE
Thanks for your comments everyone. Here is some of the code that later compares the string;
for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last == matchedArray.get(i)) {
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));
As you can see I have added a test System.out.println("DO NOT MATCH" ... and below is some the output;
DO NOT MATCH :FR99-XFR900
DO NOT MATCH :XFR900-XFR900
I only run the substring on the XFR900a filename. The problem is that for the test line to be printed last != matchedArray.get(i) however they are then the same when printed out to the display.
Phil
You should never use the == operator to compare the content of strings. == checks if it is the same object. Write last.equals(matchedArray.get(i)) instead. The equals() method checks if to object are equal, not if they are the same. In case of String it checks if the two strings consists of the same characters. This might eliminate your strange behaviour.
PS: The behaviour of == on string is a little unpredictable because the java virtual machine does some optimization. If two strings are equal it is possible that the jvm uses the same object for both. This is possible because String objects are immutable anyway. This would explain the difference in behaviour if you write down the substring manually. In the one case the jvm optimizes, in the other it doesn't.
Use .equals() rather than == because they are strings!
if (last.equals(matchedArray.get(i))) {}
Never use == operator if you wanted to check the value since operator will check the Object reference equality, use equals operator which check on the value not the reference i.e. for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last.equals(matchedArray.get(i))) { // Line edited
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));