String addition with int - java

System.out.println(1+2+"3");
System.out.println("1"+2+3);
output:-
33
123
First case is understood but the second case is not clear.

If we are doing + operation in string then is works as append(concatenation).
So in your first case 1+2+"3" ... 1+2 =3 but when it perform 3+"3" java concate 3 into String 3 that is 33.
and in second example "1"+2+3 ... 2 is append into String "1" that results as 12 and then "12" + 3 so result is = 123.

if the left part is String then it would invoke + operation on string which is append(concatenation) , while in number it is summation

+ is right associative; "1"+2 results in "12", and adding 3 gives "123".

The evaluation happens left to right. First time a string is met all the succeeding values are implicitly cast to string before being added to the expression. So in the first case you have 1+2 = 3, then a string is met and 2 is appended to the string "3". Second case - the string "1" is met and then each int is cast to string before being added to the result accumulated so far.

If you add anything to a string, it will be a string so 1 + "2"(string) is "12"(string).
if you keep on adding to string, you will keep on getting strings "12"(string) + 33 is "1233"(string).
I think this better justify your question.
Thanks
Kapil Garg

well, mathematical expressions are scanned from right usually.
In first case, if you scan from right , u get two int operands(1 and 2) and u add it and it comes to be 3 as int when move on further you find one operand("3") is string so you concatenate it and it comes out to be 33.
In second case, if you scan from right u get one string operand("1") and you concatenate it with 2 so it comes out to be 12 as string, when you move on you find int(2), but this time your first operand(12) is string, so again you concatenate it and it comes out to be 123.

in first case 1+2+"3"
first 1+2 is added and appended with string so output is 33.
but in the second case: "1"+2+3
first string is appended with 2 so operation of "1"+2 is string, automatically last is ("12"+3) also string.
that is :
1st case:
numeric output + string = string
2nd case:
string + numeric = string
that is casting to parent class with lower/wrapper data types the final output would be parent class.

Related

Calculator Class error checking

I'm doing some error checking for my BigInteger Calculator class. If an input has a space in between numbers and no valid operator (+,-,*,/,%,^) in between those numbers like the one below it is supposed to return "Error". Is there any way to check for this case using string methods?
Should return error because there is space in between numbers and no operator in between them:
2 + 1 1 1 1 1 + 2 //in this case the 1's do not have operators in between
2 2 2 //has spaces in between
valid:
2 + 2
22 + 2 + 1
2 + 11111 + 2
One option would be to split the string using String[] temp = [stringName].split(" "); and check to see that every other index is a valid operator.
Perhaps you can use regex to find space in between numbers.
String input = "1+2 2 2";
boolean found = Pattern.compile("[0-9]+\\s+[0-9]+").matcher(input).find();
You don't need to find the space between numbers specifically. In fact you should be ignoring spaces completely other than as delimiting the tokens.
You just need to scan and parse according to a grammar that doesn't have a syntax for two consecutive numbers. Or operators. At any given point you should know what's expected and what isn't.

Get Each Character From Output - Java

Right now I have a program that puts an inputted expression into Postfix Evaluation. Below is a copy of my console.
Enter an expression: ((5*2-1)/6+14/3)*(2*3-5)+7/2
5 2 * 1 - 6 / 14 3 / + 2 3 * 5 - * 7 2 / +
I now need to walk through the output, however this output is just a bunch of System.out.print 's put together. I tried using a stringBuilder however it cant tell the difference between 14 and a 1 and 4.
Is there anyway I can go through each character of this output? I need to put these numbers into a stack.
You can use String.split() and if you need only numbers regular expression.
Here is an Example:
public class Test {
public static void main(String[] args) {
String str = "1 * 2 3 / 4 5 6";
String[] arr = str.split(" ", str.length());
for (int i=0;i < arr.length;i++)
System.out.println(arr[i] + "is diggit? " + arr[i].matches("-?\\d+(\\.\\d+)?"));
}
}
str holds the long String. arr will hold the split sub strings.
you just need to make sure that each sub string differ one space from the other.
Well, you deleted your code while I was reading it, but here's a conceptually developed answer.
As you input every character, you want to push that to the stack.
The unique scenario you've mentioned 14 is unique in that it's two characters.
So what you would want to do is track if the last character was ALSO a number.
Here's a rough pseudo. Your stack should be all Strings to support this.
//unique case for digit
if(s.charAt(0).isDigit()) {
//check to see if the String at the top of a stack is a number by peeking at its first character
if(stack.peek().charAt(0).isDigit()) {
int i = Integer.parseInt(stack.pop()) * 10;
//we want to increment the entire String by 10, so a 1 -> 10
i = i + Character.getNumericValue(s.charAt(0)); //add the last digit, so 10 + 4 = 14
stack.push(Integer.toString(i)); //put the thing back on the stack
}
else {
//handle normally
stack.push(s.substring(0,1));
}
}
Is there a reason you need to parse the actual string?
If so, then what you do is, create a StringBuffer or StringBuilder, and wherever you put System.out.print in your code, append the buffer - including the spaces, which are what will help you differentiate between 1 4 and 14. Then you can convert that to a String. Then you can parse the String by splitting it by the spaces. Then iterate through the resulting String array.
If there is no reason for you to use the actual full string, you can instead use a List object and just add to it in the same places in the code. In this case, you don't need the spaces. Then you'll be able to simply iterate through the list.
You'll still be able to print you output - by printing the elements in the list.

Last two letters of a user inputted string using substring (Java)

I'm writing a program that generates star wars names. The user inputs their first, last, mother's maiden name, birth city, and first car and the program gives a star wars name. I need the last two characters* of the user inputted last name. I know I can use substring, but I cannot get anything to work. The best I have is:
lastname.substring(lastname.length() -2)
which gives the first two letters of the last name, and not the last. Also, I cannot use lastname.substr(-2) because substr for some reason won't work (not sure why, this would be much easier).
Thanks for any help.
*EDIT: I hope I didn't confuse anyone, I need the last two characters of the last name.
Actually I see my problem now: my original last name variable is
String lastname = console.nextLine().substring(0,2).trim().toUpperCase();
which keeps the first two letters, so the reason I was getting the first two letters was because of this. I understand now. Is there a way to get the last two letters from this same variable?
So if the name was Michael, you just want Micha?
Try:
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
For example:
String lastName = "Michael";
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
System.out.println(trimmedLastName); // prints Micha
The reason mine works and yours doesn't is because the first parameter of substring is where to start. So I start from the first letter, and end on the second last letter (not inclusive).
What yours does is start on the second last letter, and continue on until the end of the string.
However, if you wanted just el from Michael, you could do this:
String lastName = "Michael";
String trimmedLastName = lastName.substring(lastName.length() - 2);
System.out.println(trimmedLastName); // prints el
Try this out,
lastname.substring(lastname.length() -3,lastname.length() -1);
If you need the different ways, here:
StringBuffer myString = new StringBuffer(inputString);
myString.revert();
StringBuffer userInput = new StringBuffer(myString.subString(2));
String result = userInput.revert();
Have a nice day.
Because String is immutable so when you call subString it doesn't change the value of lastname.
I think you should do:
String genName = lastname.subString(lastname.lengh()-2);
lastname.substring(lastname.length() - 2) should return the last 2 letters.
lastname.substring(0, 2) returns the first two.
substring(index) is includive
substring(index1, index2) is inclusive, exclusive respectively.

Pulling just certain address from href tag in string always ends in .jpg

I have a string that always looks like so:
Site Info
...where sitenum=XXX will be any 3 or 4 or 5 number combo. I am trying to get just the sitenum from this string.
I figured this would give me the correct information for 3 numbers:
String src = de.substring(de.lastIndexOf("sitenum=") + 3);
However, that just takes 'sit' off of the 'sitenum=' and returns everything else like ">Site Info
I would like it to stop after getting the numbers and hitting the " that is found just after the numbers.
Am i using lastIndexOf incorrectly?
EDIT -- Answer worked for one url, but not another:
http://www.wcc.nrcs.usda.gov/cgibin/wygraph-multi.pl?state=NV&wateryear=current&stationidname=19K07S
I am trying to pull 'state' from this url, but it is not pulling state, just replacing letters in 'state'... Here is the code:
String state = de.substring(de.lastIndexOf("state=") + 2,
de.indexOf("&", de.lastIndexOf("state=")));
The state is always a 2 letter or the number 0... When I run this on my string I get:
ate=0
for example... I am confused on how this works?
EDIT EDIT! AH! I get it... so 2 needs to be 6 cause that is the amount of chars I am comparing to find the next char from?
Use this:
String src = de.substring(de.lastIndexOf("sitenum=") + 8,de.indexOf("\"",de.lastIndexOf("sitenum=")));
Not the best way of doing it, but check if it is what you need:
String src = de.substring(de.lastIndexOf("sitenum=") + "sitenum=".length(), de.indexOf(">Site Info") - 1);
Actually you are trying to get the text which is after "sitenum=", but lastIndexOf("sitenum=") will return the starting index of "sitenum=" and not the text which you are expecting
try
int startindex = de.lastIndexOf("sitenum=") + "sitenum=".length();
int endIndex = de.lastIndexOf("\">Site Info</a>");
String src = de.substring(startindex ,endIndex);

string index out of range exception

I'm looking for help correcting an exception error for 'string index out of range'. My code is supposed to take two strings as input from the user(string1 and string2) and create new strings that are parts of the originals.
So far I have the following:
modString1 = string1.substring(string1.length() -3, string1.length());
modString2 = string2.substring(0,3);
The above code is supposed to take the last 3 characters of string1 and the first 3 characters of string2. The problem I am having comes when the user inputs a string that is shorter than 3 characters.
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
For example, if the user enters 'A' for the first string it will change the string to 'xxA' and if 'A' is entered for the second string it will change that to 'Axx'?
Put an if statement before your code, checking the length of the string before you process it.
For example:
if(string1.length() < 3) {
// Add characters to the string
}
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
What you are looking for is called padding.
It can be done in a number of ways. The simplest is probably to use an external library such as Apache's StringUtils. You could also write a padding method yourself using a StringBuilder.
Related:
How can I pad a String in Java?
put the validation like below and add the string.
For ex.
if(string1.length()<3){
String op = 'xx';
string1 += op;
}

Categories