java charAt() method and surrogate - java

I am writing java code and want to know why the output of this code is x. I was expecting t since it is the 5th letter.
public class StringBufferDemo{
public static void main(String args[]){
StringBuffer sb = new StringBuffer("ttsttxctlltnt");
System.out.println(sb.charAt(5));
}
}

It's because in java a StringBuffer object is indexed starting at 0. 1st char at position 0, 2nd char at position 1, etc...
String ------ "t t s t t x c t l l"
ArrayIndex -- 0 1 2 3 4 5 6 7 8 9

The index starts from 0 and not 1. Hence in the string "ttsttxctlltnt", the character at position 5(0,1,2,3,4,5) i.e 'x' will be printed.

the index starts at 0 so the the character at 5 th posistion is x ... if u want t as the output then try the following
System.out.println(sb.charAt(4));

Related

What will be the output of String.substring(String.length)?

public class Str {
public static void main(String[] args) {
String str = "abcde";
String s = str.substring(str.length());
System.out.println(s);
}
}
The index of character 'e' is 4, but I am trying to get the whole string of length 5. If I execute the code above, why it is not throwing the IndexOutOfBoundsException?
The JavaDoc for String.substring() states:
[throws] IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Since your beginIndex is equal to the length of the string it is a valid value and substring() returns an empty string.
The empty String ("" with length 0) is a valid String. So that is what is returned by your code.
In other words str.substring(str.length()-1); returns the string "e", and str.substring(str.length()); returns the empty string. Perfectly valid.
Assume you got a String:
Hello World
this is what the indicies look like:
H e l l o W o r l d
0 1 2 3 4 5 6 7 8 9 10
"Hello World" has length of 11 so str.length would be equal to 11 in this case
now there is no index 11 in there, in fact 11 is beyond the last index. thats why you receive a IndexOutOfBounds
Additionally str.substring(number) returns a substring STARTING from the specified number all the way to the end of the string.
so str.substring(4) in this case would return
o World
Just thought i should put that in here

How can a number triangle come out of this code?

I'm a beginner in java and this code was used in a book I'm reading, however I can't seem to figure out how it works.
The code:
public class NumberTriangleWhile {
public static void main(String[] args) {
int number = 0;
String output = "";
while (number < 10) {
output = output + number;
System.out.println(output);
number++;
}
}
}
The output:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
I don't understand why each number is printed and then somehow stored and reused in the next line, can someone explain this please?
output is a string variable. When you add something to it like this:
output = output + number;
It does not add the numerical value of the number, but instead just joins the number with the original string. For example, if output was originally 1 and number is 2, the above line will change output to 12, not 3.
The loop keeps looping until number is 10. In the first iteration, output changed from an empty string to 0. In the second iteration (number has now increased to 1), output changed to 01 (the original 0 joined with the current value of number - 1). In the third iteration, number is incremented to 2. 2 is then added to the end of output to form 012. This carries on until number is 10.
The misconception you have might be that you think output becomes empty after you print it. It does not. It will still hold the same value.
In every step inside while loop, output added with number, in Java adding something with String will result in String for example:
String str = "a" + 2;
results in str="a2";.
If we start our loop, in first step number = 0 and output="" hence output = "" + 0 that make output = "0" in second run number=1 hence output = "0" (Old output value) + 1 that make output = "01" and so on
The string output is defined outside of the while loop. It can be read from and written to inside of the while loop and its contents will be consistent in the next iteration.
If output would be defined inside of the while loop, for example:
while ( number < 10) {
String output = "";
output += number;
}
then your output would just be (with new line after each number)
0
1
2
3
4
5
6
7
8
9
Since the new number is consistent throughout each iteration of the while loop, it is "stored" as you say
Each number is getting printed because its getting concatenated.
When number=0,
And you are storing the value of number into the output as:
Output=output+number
Then the number which is an integer gets stored as a string in the output
Each time the loop runs the new incremented number gets concatenated with the previous value in the string output.
That's why all numbers are getting printed each time.
make this change in your code and you'll get your output
public static void main(String[] args)
{
int number=0;
String output="";
while(number <10)
{
output=output+number;
System.out.println(output);
number++;
output="";
}
}

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.

Changing code from Java to C

So I made this program in Java first and then I wanted to make the same program in C++. While in Java it worked perfectly here I have one major issue. I used a char variable for my array and in C++ it pastes the ascii code I assume(smiley face,rhomb...). So this is a tic tac toe game so I want my program to display the numbers like this:
1 2 3
4 5 6
7 8 9
and after I insert 1 to be like this:
X 2 3
4 5 6
7 8 9
If I make the array Int I get instead of X and 88. If I make it char I can put the X and it displays it correct but numbers from 1-9 are rhomb etc. Help me please! Thank you.
char A[9]={1,2,3,4,5,6,7,8,9};
for(int i = 0, j = 0; i < 9; ++i, ++j)
{
if(j==3)
{
j = 0;
cout<<"\n";
}
cout<<A[i]<<" ";
}
This line:
char A[9]={1,2,3,4,5,6,7,8,9};
should be:
char A[9]={'1','2','3','4','5','6','7','8','9'};
In the first version what you're doing is creating an array of characters with their ascii values (you can find an ascii table here).
The overload of operator<< for a char by default prints a character, not the integer value stored. To get it to print an integer you can cast it:
std::cout << static_cast<int>(A[1]) << ' ';
Alternatively you could use int for the array.

substring index range

Code:
public class Test {
public static void main(String[] args) {
String str = "University";
System.out.println(str.substring(4, 7));
}
}
Output: ers
I do not really understand how the substring method works. Does the index start at 0? If I start with 0, e is at index 4 but char i is at 7 so the output would be ersi.
0: U
1: n
2: i
3: v
4: e
5: r
6: s
7: i
8: t
9: y
Start index is inclusive
End index is exclusive
Javadoc link
Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end.
To make life easier for substring operation, imagine that characters are between indexes.
0 1 2 3 4 5 6 7 8 9 10 <- available indexes for substring
u n i v E R S i t y
↑ ↑
start end --> range of "E R S"
Quoting the docs:
The substring begins at the specified
beginIndex and extends to the
character at index endIndex - 1. Thus
the length of the substring is
endIndex-beginIndex.
See the javadoc. It's an inclusive index for the first argument and exclusive for the second.
Like you I didn't find it came naturally. I normally still have to remind myself that
the length of the returned string is
lastIndex - firstIndex
that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception
so
"University".substring(6, 10)
returns the 4-character string "sity" even though there is no character at position 10.
public String substring(int beginIndex, int endIndex)
beginIndex—the begin index, inclusive.
endIndex—the end index, exclusive.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3, 8));
}
}
Output: "lo Wo"
From 3 to 7 index.
Also there is another kind of substring() method:
public String substring(int beginIndex)
beginIndex—the begin index, inclusive.
Returns a sub string starting from beginIndex to the end of the main String.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3));
}
}
Output: "lo World"
From 3 to the last index.
Yes, the index starts at zero (0). The two arguments are startIndex and endIndex, where per the documentation:
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
See here for more information.
The substring starts at, and includes the character at the location of the first number given and goes to, but does not include the character at the last number given.
For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing.
I would understand substring(startIndex, length) to remember that.
public class SubstringExample
{
public static void main(String[] args)
{
String str="OOPs is a programming paradigm...";
System.out.println(" Length is: " + str.length());
System.out.println(" Substring is: " + str.substring(10, 30));
}
}
Output:
length is: 31
Substring is: programming paradigm

Categories