Java: Unexpected Type Error [duplicate] - java

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 8 years ago.
Can someone help me understand why I'm getting an "Unexpected Type Error"?
if(s.charAt(i-1) == ' '){
String sub = s.substring(i, s.indexOf(' ')+1);
for(int j = 0; j < sub.length()/2; j++){
char temp;
temp = sub.charAt(j);
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
sub = sub+" ";
complete = complete+sub;
}
}
I'm getting the error on lines 6 and 7. I can't figure out why and I'd appreciate the help!

charAt() returns the character. It is not a left side operand aka you cannot assign a value to it.
Strings are immutable, which means you cannot change them (this seems to be your intention).
Instead: create a new String and add to that.
If this confused you, I try to elaborate a little: the assignment operator takes whatever is on the right and tries to shove it into whatever is on the left of it.
The problem here is that some things do not like it when you try to shove other things into them. You cannot put everything on the left that you want. Well, you can try:
"everything" = 5;
but this does not work, neither does this:
"everything" = 42;
Set aside what that last snippet failing implies to the universe and everything, your problem at hand is that charAt() is also one of those things that do not like it on the left side of the assignment operator.
I'm afraid there's no way to turn charAt() into one of those things that like it on the left side. A week after stranding on a deserted island without any plants but only solar powered refrigerators filled with steaks, this probably works:
vegetarian = meat;
Even though the vegetarian doesn't like it there, he'd accept his situation being on the left side of the = operator. He eats some steaks.
This does not hold true for what you are trying, though. There's no such deserted island for charAt().

In these lines you're trying to set the value of functions' return. This is illegal
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
as far as I see you're trying to change the characters of a String, but Strings are imutable objects. So you'll need to use a StringBuffer to set the values.

Related

Error at using Assignment operator in java [duplicate]

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 2 years ago.
I also the error "Left Hand Side of an Assignment must be a Variable" for following line
outPutArray.charAt(i)=inputArray[i]
how to resolve this? I have tried putting braces like but of no use
(outPutArray.charAt(i))=inputArray[i]
You are trying to mutate a String object. This is not possible, String is supposed to be immutable. You have to create a new String with the changed content, use a char array instead, or something else that allows you to actually achieve what you are trying to do in the end (which is: given an input String, return an output String where one character is changed).
With that out of the way, you can't do an assignment on the return value of a function. You don't get a reference back that you can change and then some variable gets changed. You get a value back. The great Is Java "pass-by-reference" or "pass-by-value"? question is maybe a good read.
Very silly, but the format should be:
inputArray[i] = outPutArray.charAt(i);
not
outPutArray.charAt(i) = inputArray[i]
putting the function on the left hand side means you are assigning a constant integer to a integer array element. As the integer is constant, it will fail. This is why we put our variables(inputArray[i] in your case) on the left hand side and our functions on the right hand(outPutArray.charAt(i)). Hope you understand!
.charAt(i) function returns the character at position i. It does not return the reference to the character at that index.
Look at this for more details

JAVA trying to find positions of the year. Not Working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have a small program that reads a json file that gives the
weather, time, temp, wind, ect. I need to calculate the average
tempature for 2009 through 2015. The years are in an array, and are in
length, around 60k. I am trying to write a small loop that will first
find the position of the first instance of the year 2009 and then
the last instance of the year 2009. Then I can run my
average temp loop through that, but I am running into an issue as seen
below.
place will be the index of the array. However, no matter how I run my
code, it always equals -1, rather than giving me the position of
the index in the array. Both arguments in the if statements are
strings.
So what am I doing wrong?
String twozerozeronine = "2009";
int place = -1;
for (int a = 0; a < years.size(); a++){
if (years.get(a) == twozerozeronine){
place = 1;
break;
}
}
System.out.println(place);
years.get(a) == twozerozeronine
checks whether the object on the left side of the operator and the object on the right side of the operator are the very same. In your case they might be similar, but will never be the very same.
You will need to check whether they are similar instead:
years.get(a).equals(twozerozeronine)
You can use equals() method to compare the value of the Strings.
Like: if ( years.get( a ).equals( twozerozeronine ) ){
The == operator compares the Object references (in your case, both are not equal) whereas equals() method compares the actual string values (in your case, the string values are "2009").

Java: StringIndexOutOfBoundsException when using .charAt() in for-loop

thank you in advance for reading about my problem.
I am making a Hangman game where I want to print out a hidden version of the current word, but I would like to update it when a correct letter is guessed (on the right spot, too). I've been looking around StackOverflow but I just can't seem to find an explaination that I understand. If someone could help me, that would be great. :D
I'll post the for-loop that this is about. I can post more of the code if you might need it. The answerInput and guessInputString are both read from the console earlier in my code using a br.readLine() method.
for (int i = 0; i < inputAnswer.length(); i++) {
char inputAnswerChar = inputAnswer.charAt(i);
char guessInputChar =guessInputString.charAt(i);
if (inputAnswerChar == guessInputChar) {
replacementString.replace(replacementString.charAt(i), inputAnswerChar);
}
}
Thank you for any help that you can give me!
Your code is assuming that guessInputString and replacementString both have at least as many characters as inputAnswer, which is obviously wrong to assume, since your loop only guarantees that the i'th character exists for the inputAnswer String.
BTW, replacementString.replace(replacementString.charAt(i), inputAnswerChar) has no effect, since it cannot change the String it is executed for (since Strings are immutable). You must assign the new String returned by this method back to replacementString :
replacementString = replacementString.replace(replacementString.charAt(i), inputAnswerChar)

Order of operations in i=i++; [duplicate]

This question already has answers here:
Why this giving me 0? [duplicate]
(7 answers)
Closed 8 years ago.
Understanding the difference between ++i and i++, the below example still feels counter-intuitive.
Could someone please explain the order of operations and assignments in the following example?
int i = 0;
i = i++;
System.out.println(i); // 0
Namely on line two, why is i not incremented after the assignment?
The simple way to see it is like this:
Step 1: Your int i = 0; line, which (of course) does this:
i = 0
Then we come to the i = i++; line, where things get interesting. The right-hand side of the = is evaluated, and then assigned to the left-hand side. So let's look at the right-hand side of that, i++, which has two parts:
Step 2:
temporary_holder_for_value = i
The value of i is read and stored away in a temporary location (one of the virtual machine registers, I expect). Then the second part of i++ is done:
Step 3:
i = i + 1
Now we're done with the right-hand side, and we assign the result to the left-hand side:
Step 4:
i = temporary_holder_for_value
The key is that last step. Basically, everything to the right of the = is done first, and the result of it is then assigned to the left. Because you used a post-increment (i++, not ++i), the result of the expression on the right takes i's value before the increment. And then the last thing is to assign that value to the left-hand side.

Java: Syntax error on token "-", Expression expected after this token [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Well hello guys, i'm starting the programmer life now, i'm really new into it, but i'm trying really, really hard and i'm making some easy programs to run on eclipse console, it's very simples 'cause i'm just getting started... well, everything went out ok, except for this one program, i can't make it work in no way... i'm gonna put it all here so if there's anything really, really wrong tell me, and i'm also going to expecific the problem that eclipse found... Here it is:
public class Pagamento {
public static void main(String[] args) {
int vvalor;
int vpagto;
int vtroco;
String voperador;
vvalor = 200;
vpagto = 250;
voperador = -;
if (vpagto > vvalor){
System.out.println ("Troco:" + vpagto - vvalor);
}if (vpagto = vvalor ){
System.out.println ("Troco:" + 0);
}if (vpagto < vvalor){
System.out.println ("Transação inconcluída!");
}
}
}
I had to define the " - " 'cause it asked to (when i did it, it said in the first System.out.println, that 'the operator - is undefined for the argument type(s) String, int and in the line' "}if (vpagto = vvalor ){" it appeared the error "can't convert from int to boolean), and when i did defined, it just gave this error on the line "voperador = -;":
Syntax error on token "-", Expression expected after this token. What does that mean ? Is everything so wrong ? What should i do to fix it ? Please help me, i try to search but i found nothing like this here, nothing that could solve my problem... thanks and please help !
it should be voperador = "-"; You have missed the double quotes. Strings are required to be enclosed within double qoutes
replace }if (vpagto = vvalor ){
with }if (vpagto ==vvalor ){
Also keep - with in ""(double qoutes) like voperador ="-";
voperador is a String, which can't be assigned to -. If you want the string to be "-", then use voperador = "-";
For your first error: This line isn't valid:
voperador = -;
String constants must go in quotes:
voperador = "-";
A - by itself is either a unary negation operator (e.g. -a) or a binary subtraction operator (e.g. a - b). The error you are seeing is the result of the compiler becoming very confused as to why a negation/subtraction operator was just hanging out between an equal sign and a semicolon.
For your second error: You have this:
if (vpagto = vvalor )
But you should have this:
if (vpagto == vvalor )
In Java, a single = means "assignment". Comparisons are done with the double ==. The reason you saw the error you saw is because Java evaluates the expression a = b to the value of a after the assignment (that's the rule), which in this case happens to be of type int (since vpagto is an int). At the same time, it expects the condition in an if statement to be a boolean (e.g. if (true) ...). The compiler was confused because it wanted a boolean but you gave it an int.
For your third error, you have this:
("Troco:" + vpagto - vvalor)
But what you really mean is this:
("Troco:" + (vpagto - vvalor))
Java evaluates expressions from left to right. As a convenience, it lets you add pretty much anything you want to a string, and the result is a string version of the values you've specified. However, this only works with +, there's no special definition of - for strings. Since it goes left to right, first "Troco:" + vpagto is evaluated, and that is a string. But then you try to subtract vvalor from a string, and the compiler complains. By adding parentheses, you tell it to perform the math on the integers first, before attempting to append the result to a string.
The errors you are making here are very basic. You should really go through the official Language Basics tutorial.

Categories

Resources