//take the input from user
text = br.readLine();
//convert to char array
char ary[] = text.toCharArray();
System.out.println("initial string is:" + text.toCharArray());
System.out.println(text.toCharArray());
Output:
initial string is:[C#5603f377
abcd
println() is overloaded to print an array of characters as a string, which is why the 2nd print statement works correctly:
public void println(char[] x)
Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().
Parameters:
x - an array of chars to print.
The 1st println() statement, on the other hand, concatenates the array's toString() with another string. Since arrays don't override toString(), they default to Object's implementation, which is what you see.
Related
Code a method called countStudentsPerFaculty that accepts a string as input represents a faculty name and returns an integer value that represents the number of students in that faculty.
For example:
If the enrollment ArrayList has [“John|FIT”,”Tim|Law”,”Emma|FIT”]
Input “FIT”
return 2,
Input “Law”
return 1,
Input “Business”
return 0
I'm a beginner in Java. I've already used the .split() method to split the String in the array. But I'm not getting the output I want.
public int countStudentsPerFaculty(String facultyName) {
int numberOfStudents = 0;
for (String elem: enrollment) {
String[] nameOfFaculty = elem.split("|");
numberOfStudents++;
}
return numberOfStudents;
}
This is my code. My code is returning the output for each faculty as 3. Where am I going wrong? Thank you in advance.
You should check that if nameOfFaculty is equal to facultyName(method argument) then add one to numberOfStudents. same as below :
public int countStudentsPerFaculty(String facultyName) {
int numberOfStudents = 0;
for (String elem: enrollment) {
String nameOfFaculty = elem.split("\\|")[1];
if(nameOfFaculty.equals(facultyName))
numberOfStudents++;
}
return numberOfStudents;
}
When you call String.split(String regex), you get a array of Strings. For example, if I take the first String, "John|FIT", it will return an array: {"John", "FIT"}. You arent carrying any operation on the array of String, you get, so the for loop is basically useless. All you are doing is getting the number of elements in the array, by incrementing the value of numberOfStudents by 1, each time you iterate over the Strings in the array. Since there are 3 Strings in your array, countStudentsPerFaculty returns 3. #Zahra's answer gives the correct code, but I think it is important to clarify the working.
Lets take the same String as an example: "John|FIT".
The first statement of the for loop takes the second String in the array {"John", "FIT"}. the if statement checks whether the name of the faculty, "FIT" in this case is equal to the parameter of the method. If so, numberOfStudents is incremented by one. This procedure takes place for all the Strings in enrollment.
For better clarity, you can copy #Zahra's code, and try to debug it....
Also, as specified by #Eritrean, the split() method's parameter("|"), should be escaped with 2 backslashes ("\\|") as it accepts a regex String, as "|" is a special regex.
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 am trying to print the letters of the alphabet in caps. So I wrote this in a for loop:
System.out.print(Character.toChars(i));
//where i starts at 65 and ends at 90
This works fine and prints the letters but In my code I wanted to put a space between the letters to make it look nicer. So i did this:
System.out.print(Character.toChars(i) + " ")
Why does it print the memory address of the characters instead of the letter?
The solution I came up with was to explicitly convert the char to a new String object:
String character = new String(Character.toChars(i));
System.out.print (character + " ");
but I'm not quite sure why I can't just write "Character.toChars(i)"
In the first one Does the method(Character.toChars()) point to the address of the character and System.out.print is smart enough to print the value at that address? i.e the corresponding letter?
System.out.print(Character.toChars(i)) calls PrintStream.print(char[]), an overload that handles char[] specially.
Character.toChars(i) + " " is really equivalent to Character.toChars(i).toString() + " "; calling toString() on an array type results in a string representation of its address (this behaviour is directly inherited from Object).
A simpler solution for your particular case may be this:
System.out.println((char)i + " ");
The Character.toChars method returns char[], which will be represented as [C#<hex hashcode> in String form.
You don't need to use the toChars method (or do any casting at all):
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
You use string concatenation, with one side being an array of chars and the other a string and according to the Java language specification, then as the char array is not a primitive type, but a reference value (aka an object), its toString method is called. And as there is no specific method implemented for arrays, they inherit the method implementation from java.lang.Object, which prints the address.
On the other hand, System.out.print(Character.toChars(i)) calls a specific implementation of print for character arrays, see the documentation of PrintStream.
I am printing a 1d array of chars by using System.out.println(arr) and I get the characters in the array (not space seperated). When I do the same by adding a "/t", the output changes and it now prints the address of the char array.
I tried to print a 1d array of ints using System.out.println(arr), but the results were different and it printed the location of the array in memory.
Please tell what is going on and how is it all implemented.
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
class Main3{
public static void main(String[] args)throws java.lang.Exception{
int[] intArr = {1,2,3,4};
char[] charArr = {'a' , 'b' };
System. out.println(intArr); // prints the address of the intArr
System. out.println(charArr); // prints the charArr contents
System.out.println("\t" + charArr); // prints the address of the charArr after a tab
}
}
PrintStream has a method that accepts a char[].
However when you do "\t" + charArray java tries to do String concatenation. To do this it first has to convert charArray to a String using the Object#toString method(JLS 5.1.11). Then it passes the String into println.
The following print statement:
System.out.println(charArr);
invokes the PrintStream#println(char[]) method. From the documentation:
The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
Whereas the next print statement:
System.out.println("\t" + charArr);
converts the charArray to String, by invoking the toString() method of Object class, as arrays don't override it. And then the method PrintStream#println(String) is invoked.
So, the above print statement is equivalent to:
System.out.println("\t" + charArr.toString());
Look into the Object#toString() method to see how it forms the string for the array.
The way to access the elements of the array is with bracket notation. So for example if you want the get the int at index 0 of the intArr you could write
System.out.println(intArr[0]);
where the number in brackets is the index of the element you want or you could iterate over all of them with
for(int i = 0; i < intArr.length; i++){
System.out.println(intArr[i]);
}
This will work as long as whats in the array is not an object - in which case it will print the address.
I am new to Java.
I executed the below program successfully but I don't understand the output.
This is the program.
public class StringBufferCharAt {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
System.out.println("Length of sb : " + sb.length());
int start = 0;
int end = 10;
char arr[] = new char[end - start];
sb.getChars(start, end, arr, 0);
System.out.println("After altering : "+ arr.toString());
}
}
After executing this program: I got the following output:
Length of sb : 26
After altering : [C#21a722ef
My Questions:
Instead of printing 10 characters in the output, why 11 characters.
Instead of printing the original characters "abcdefghij" which are
inside sb, why did I get some other characters.
The arr.toString() in your last sentence is giving you a String value of your Object (doc here), here's an array. What you were probably trying to achieve was something like Arrays.toString(arr) which will print the content of your array (doc).
Why is the output 11 characters, and what do those characters mean?
It just so happens that the string representation of the char[], as specified by Object#toString(), is 11 characters: the [C indicates that it's a char[], the # indicates the following 8 hex digits are an address in memory. As the JavaDoc states,
This method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Class#getName() returns "C[" for a char array, and the default hashCode() implementation (generally) returns the object's address in memory:
This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.
How should this be solved?
If you want to print the contents of an array, use Arrays.toString():
// Instead of this:
System.out.println("After altering : "+ arr.toString());
// Use this:
System.out.println("After altering : "+ Arrays.toString(arr));
You need to have final print statement like this:
System.out.println("After altering : "+ new String(arr));
OR
System.out.println("After altering : "+ java.util.Arrays.toString(arr));
OUTPUT
For 1st case: abcdefghij
For 2nd case: [a, b, c, d, e, f, g, h, i, j]
Note: arr.toString() doesn't print the content of array that's why you need to construct a new `String object from char array like in my answer above or callArrays.toString(arr)`.
Arrays in java do not have any built in 'human readable' toString() implementations. What you see is just standard output derived from the memory location of the array.
The easiest way to turn a char[] into something printable is to just build a string out of it.
System.out.println("After altering : " + String.valueOf(arr));
The expression arr.toString() does not convert a char[] to a String using the contents of the char[]; it uses the default Object.toString() method, which is to print a representation of the object (in this case an array object). What you want is either to convert the characters to a String using new String(arr) or else an array representation of the characters using Arrays.toString(arr).
The one part of this question I can answer is #1. You are getting back 11 characters because the start and end variables are indexes. 0 is a valid index so, from 0 - 10 there are 11 different numbers.