I currently have the following code for java.
public class lesson8
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
String user;
int length, counter, spacecounter;
spacecounter=0;
c.print("Enter a string. ");
user = c.readLine();
length = (user.length()-1);
for (counter=0;counter<length;counter++)
{
if (user.charAt(counter) = "")
{
spacecounter++;
}
}
c.println("There are "+spacecounter+" spaces in your string.");
c.println("There are "+counter+" characters in your string.");
// Place your program here. 'c' is the output console
// main method
}
}
I am getting an error on this part:
if (user.charAt(counter) = "")
The error is
The left-hand side of an assignment must be a variable.
I changed it to "==", but now I get another error:
The type of the left sub-expression "char" is not compatible with the type of the right sub-expression "java.lang.String".
How would I solve this?
Thanks!
So, the reason why
if (user.charAt(counter) = "")
gives that error is that "=" is an assignment operator in java, and so the left-hand side must be a variable. That being said, you probably actually want
if (user.charAt(counter) == ' ')
which uses the comparison operator (==) and the space character (' '). ("" is an empty string)
You are using an asignment over a comparison operator.
Change
if (user.charAt(counter) = "")
to
if (user.charAt(counter) == "")
Update:
You also have an error at comparison again.
You should also use single quotes ( ' ) to compare a char, otherwise it won't get compiled.
if (user.charAt(counter) == '')
But this too will not get compiled as a zero length char is not defined.
You should be comparing a valid character, say ' ' for space.
You want to use the equality operator ==, not the assignment operator = .
"==" is going to make sure that the value to the right is the same as the variable to the left.
"=" is an assignment operator and is used to give value TO the variable, rather than compare it.
I got same error in my code. Adding parenthesis solved this error
Changed from
if(isNotNullorEmpty(operator))
ArrayList<String> result = getOperatorAndTypeforName(name );
to
if(isNotNullorEmpty(operator)){
ArrayList<String> result = getOperatorAndTypeforName(name );
}
Related
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'.");
}
While I was creating a program to compress a string I ran into this strange problem, I will paste the code snippets with their outputs, I would like someone to clearly explain why this is happening.
The first code snippet: here if same letter appears consecutively, then the successive occurrences of the letter is replaced by the total count of same letters. Ex: aaabbb should be written as a3b3.
public static String compress(String str){
String compressed = "";
char prev = str.charAt(0);
int count = 1;
for (int i = 1; i < str.length(); i++) {
char curr = str.charAt(i);
if (curr == prev) { // in case curr is equal to prev
count++;
} else { // in case curr is not equal to prev
//compressed=compressed+prev+count;
compressed+=prev+count; // Shorthand used here
count=1;
prev=curr;
}
}
compressed=compressed+prev+count; // Shorthand not used
System.out.println(compressed);
return compressed;
}
the output for this above code when inputted with aabbccaabbccaabbccaabb is 99100101991001019910010199b2, observe the last two elements of the output, this is because outside the loop, shorthand is not used. If I write the expression as compressed = compressed +prev+count inside the loop, I'll get the intended output.
I thought this output is because the operation is messing with the address of the String. But the next code confused me again.
String prev= "abc";
String curr = "def";
String result="";
result+=prev+curr;
System.out.println(result);
I think this is because the right hand operation is performing an ASCII addition, I cannot come to a conclusion, can anyone clarify.
I am sleep deprived and hence I am not able to come to a conclusion, hence asking someone to clarify my trivial doubt.
It has nothing to do with the reference. When you did prev+count ascii value of the character in prev is added with the integer count. In this case :
ascii of "a" is 97, and it occurred twice... so 97 +2 = 99 ..
ascii of "b" is 98, and it occurred twice... so 98 +2 = 100 ..
ascii of "c" is 99, and it occurred twice... so 99 +2 = 101 ..
that's why the output is 99100101991001019910010199100
try this : compressed+=(""+prev)+count; // Shorthand used here
In this case, or in compressed+=""+prev+count case, since the operation happens from left to right, the + operator is applied on a string ("") and char(prev) and behaves like append and also returns a string. The resulting string is then appened with another int (prev)
A better way is using a StringBuilder
Take a look at this subject and at JLS 15.18.1 section :
You see this behavior as a result of the combination of operator
precedence and string conversion.
JLS 15.18.1 states:
If only one operand expression is of type String, then string conversion (ยง5.1.11) is performed on the other operand to produce a
string at run time.
Therefore the right hand operands in your first expression are
implicitly converted to string: string = string + ((char)65) + 5;
For the second expression however string += ((char)65) + 5; the +=
compound assignment operator has to be considered along with +.
Since += is weaker than +, the + operator is evaluated first.
There we have a char and an int which results in a binary numeric
promotion to int. Only then += is evaluated, but at this time
the result of the expression involving the + operator has already been evaluated.
Whenever you add a char to an int in java first it converts the character into its equivalent ASCII value and then adds it to the integer
eg suppose the following scenario ,
char c = 'a'; // ASCII value of 'a' is 97
int i = c + 5 ; // result will be 97 + 5 = 102
I think this answers your first half question
Now the Second part ,
Whenever you use the shorthand operator in Java the expression at right hand side is evaluated first.
Hence , for expresion
result += prev + curr it is evaluated as
result = result + (prev + curr);
Therefore ,
result+=prev+curr; // Here first it appends "abc" with "def" and then the resultant "abcdef" is appended to as result .
you can convert your charater value "prev" to string and than append count to it.
compressed += Character.toString(prev) + count;
What i'm trying to do is incorporate interface methods to complete a task given the variables inside of a string. The string i'm given, "s" can be made up numbers, +, -, and * symbols. The integer return is fairly easy as all i'm doing is returning an integer interface method of that int. However, for the other 3 symbols, I need to recursively incorporate a method to find the left and right nodes. I've posted my code below...
public static Expression parseString( String s ) {
String[] parse = s.split("\\s+");
String[] parsecopy;
Expression exp1;
Expression exp2;
if(s == null) {
return null;
}
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
else if() {
The problem - So my code creates a copy of the original string to find the next item in that string. I do this by using the Array function, copyOfRange(). However, when I want to call exp2 = parseString(parsecopy), i'm receiving an error because parseString takes in a string argument which has to be of the type String[]. The reason i'm trying to get parsecopy instead of parsecopy[0] is because parsecopy wouldn't create an endless loop and I would actually be able to iterate through the string.
Error code - The method parseString(String) in the type Parse is not applicable for the arguments (String[])
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
exp1 = parseString(parse[0]);
you are doing recursive calling here.
Since the parameter you pass to split is a regex, you can simply do:
String[] ss = "12121+34234 *23423 -123123 *123123-12312+1231231-123123".split("\\s?[\\+\\-\\*]\\s?");
this way you split your string wherever you got a +, - , or * (possibly with a whitespace after or before).
And please do the null-check of the string before split it :D
Hope it helps.
It seems like you want to check parse[1] equals "+" rather than parse[0].
You would expect 1 + 2 rather than + 1 2.
I have a simple string that I'm trying to determine if a specific index results in a specific char.
I'm trying to do it like this (but I get compilation errors):
if(myString.charAt(7).equals("/")) {
// do stuff
} else {
// do other stuff
}
Error:
Type mismatch: cannot convert from char to boolean
(myString.charAt(7).equals("/")
should be following because charAt() returns char:
myString.charAt(7) == '/'
if(myString.charAt(7)== '/') {
// do stuff
} else {
// do other stuff
}
Putting a character in double quotes makes it a String. Single quotes makes it a char. And you compare characters with literal == whereas you compare Objects with the equals method
There's a couple solutions on this answer that give you what you were probably trying to do, which is compare a single character to another single character. I won't go over that because they've done excellently.
But you can still use a String if you like, and prepare for the future. (Perhaps "/" changes to "//"?) you can do this:
if(myString.substring(7,8).equals("/")) {
// stuff
}
Then down the road you might be like
public static final String SEPARATOR_STRING = "//";
public static final int SEPARATOR_START = 7;
public static final int SEPARATOR_END = 7 + SEPARATOR_STRING.length();
// later
if(myString.substring(SEPARATOR_START,7SEPARATOR_END).equals(SEPARATOR_STRING)) {
// stuff
}
charAt() returns char, not object, so you need to compare it that way:
if(myString.charAt(7)== '/') {
...
note the single quote around /.
if(myString.substring(7,8).equals("/"))
or
if(myString.charAt(7)=='/')
or
if(myString.indexOf("/"))==7) can be use
I have a doubt which follows.
public static void main(String[] args) throws IOException{
int number=1;
System.out.println("M"+number+1);
}
Output: M11
But I want to get it printed M2 instead of M11. I couldn't number++ as the variable is involved with a for loop, which gives me different result if I do so and couldn't print it using another print statement, as the output format changes.
Requesting you to help me how to print it properly.
Try this:
System.out.printf("M%d%n", number+1);
Where %n is a newline
Add a bracket around your sum, to enforce the sum to happen first. That way, your bracket having the highest precedence will be evaluated first, and then the concatenation will take place.
System.out.println("M"+(number+1));
It has to do with the precedence order in which java concatenates the String,
Basically Java is saying
"M"+number = "M1"
"M1"+1 = "M11"
You can overload the precedence just like you do with maths
"M"+(number+1)
This now reads
"M"+(number+1) = "M"+(1+1) = "M"+2 = "M2"
Try
System.out.println("M"+(number+1));
Try this:
System.out.println("M"+(number+1));
A cleaner way to separate data from invariants:
int number=1;
System.out.printf("M%d%n",number+1);
System.out.println("M"+number+1);
Here You are using + as a concatanation Operator as Its in the println() method.
To use + to do sum, You need to Give it high Precedence which You can do with covering it with brackets as Shown Below:
System.out.println("M"+(number+1));
System.out.println("M"+number+1);
String concatination in java works this way:
if the first operand is of type String and you use + operator, it concatinates the next operand and the result would be a String.
try
System.out.println("M"+(number+1));
In this case as the () paranthesis have the highest precedence the things inside the brackets would be evaluated first. then the resulting int value would be concatenated with the String literal resultingin a string "M2"
If you perform + operation after a string, it takes it as concatenation:
"d" + 1 + 1 // = d11
Whereas if you do the vice versa + is taken as addition:
1 + 1 + "d" // = 2d