Why does my toString method return 0? - java

Why does my toString method return 0? I have to concatenate an randomly generated integer onto a String and when I print the result it is always 0. What should I do?
class Cozi:
public String toString(){
String concat="";
Clienti ob = new Clienti();
for(int i=1;i <= Clienti.getNrClienti();i++){
concat = " <" + ob.getRandomInt2() + ">";
System.out.print(concat);
}
return concat;
}
class Clienti:
public int serviceTime(){
System.out.print("\n");
Random randomServ = new Random();
for (int idx = 1; idx <= nrClienti; ++idx){
randomInt2 = randomServ.nextInt(maxServ);
System.out.println("Generated : " + randomInt2);
}
return randomInt2;
}
I have also the methods get and set randomInt2.
I foud out why I was getting only 0. Because randomInt2 was declared int in class Clienti, instead of private static int. Now the problem I got is that my concat object gets only the last value for randomInt2. Any suggestions?

If you have an empty String "" as a return value, then it means you do not enter the for loop. Check if the condition i <= Clienti.getNrClienti() is met for any i.
And there is a bug in the for loop, you have to modify:
concat=" <"+ob.getRandomInt2()+">";
By
concat += " <"+ob.getRandomInt2()+">";
Note: when you want to concatenate Strings you can use StringBuilder which is more performant.

String s = "a";
s = "b";
System.out.println(s); // b
You want to concat if I got that right:
String s = "a";
s = s + "b";
System.out.println(s); // ab

Related

How to print a String array using a non-void method?

So I'm supposed to write a method to print the elements of an array. This is how I did it:
public static void join(String phrase[])
{
for (int i = 0; i < phrase.length; i++)
{
System.out.print(phrase[i] + " ");
}
}
This code works, but the prof says we must return a String with this method, and I don't know how to do it this way. I tried:
public static String join(String phrase[])
{
for (int i = 0; i < phrase.length; i++)
{
String sentence = System.out.print(phrase[i] + " ");
return sentence;
}
}
Error: incompatible types: void cannot be converted to java.lang.String
I know I cannot use .print because the method is not void. But then, how do I print?
Any ideas? This is a beginner Java class, so I don't know any other way.
This would also work:
public static String join(String phrase[])
{
String sentence = "";
for (int i = 0; i < phrase.length; i++)
{
sentence += phrase[i] + " ";
}
return sentence;
}
Here is what I'm doing:
1) Creating an empty string outside the for loop that will be used to hold all the values of the array
2) Adding each element of array (with a space after) to the string with sentence += phrase[i] + " ";
3) Once the for loop adds all the elements to the string, return it!
System.out.println return void
You can't assign void to a String variable. You simply want to assign the concatenated value, not print it.
String sentence = phrase[i] + " "
You declare sentence each iteration
You need to concatenate each cells, so declare a variable before the loop and append the String in the loop
String sentence = "";
for (int i = 0; i < phrase.length; i++){
sentence += phrase[i] + " "; //same as sentence = sentence + phrase[i] + " ";
return sentence;
}
You return a value inside the loop...
The loop will end at the return, so only the first value will be present in the String. Only return the value after it is fully done, after the loop.
String sentence = "";
for (int i = 0; i < phrase.length; i++){
sentence += phrase[i] + " ";
}
return sentence;
FYI: In the same issues, if the array is empty, no value are returned, so it will also be a problem since a method should return a String in every cases (or throw an exception`.
Shorter solution :
This loop can be done simply with String.join since Java 8
return String.join(" ", phrase);
Please do the following:
public static String join(String phrase[]){
StringBuilder str = new StringBuilder();
for(String s: phrase){
str.append(s);
}
System.out.println(str);
return str.toString();
}
Dont use += and add the values of the string array to another string as it will create a new object every time you add a new string to the preprocessed string. Instead use StringBuilder which is more memory efficient.
You can also do the following:
public static String join(String phrase[]){
String str = Arrays.toString(phrase);
System.out.println(str);
return str;
}
This will print each elements and return the entire result :
public static String printElements(String phrase[]) {
String result = "";
for (int i = 0; i < phrase.length; i++)
{
System.out.print(phrase[i] + " ");
result += phrase[i];
if( i != phrase.length - 1)
{
result += " ";
}
}
return result;
}

Java - Comparing single Char to String

Thanks for taking your time to look at my question. This is one of the methods I created for decrypting a message. This isn't the entire code, believe me I have been trying for hours messing with the code, I didnt just hop on here and hope you guys would do it for me, I'm just asking a HOW to do something!
Just so you guys know, I can't really change much from what I currently have because I'm limited based on the assignment.
My problem: I need to make any character that is an "x" equal a SPACE or " ". Basically I'm trying to hardcode every "x" within the string to become a space because it's not printing what it should be.
What I currently have:
public static String decryption(String s, int n)
{
int originalChar, decryptedChar;
String message = "";
char c;
for(int i = 0; i < s.length(); ++i)
{
c = s.charAt(i);
decryptedChar = (int)c;
if(decryptedChar + n > 126)
originalChar = 32 + ((decryptedChar + n) - 113);
// Problem here
if(c.equals("x"))
originalChar.equals(" ");
else
originalChar = decryptedChar + n;
message = message + (char)originalChar;
}//end for loop
return message;
}//end method
I marked the problem area. If anyone can tell me how to do this properly so that I can make any "x" equal " " instead that would be awesome! Thanks for your time.
your problem is with:
originalChar.equals(" ");
equals() method is a method that checks equality - it returns true if originalChar equals " ", and what matters in your case- it does not alter originalChar in any way, just compares it to " ".
if you want to set originalChar to be " ", you need to do originalChar = " "
In any case, a much easier solution would be:
s = s.replace("x"," ");
one of the problems is with .equals. That is not meant to do a comparison on a character, only Strings.
Further more below you try to assign a String to a character with ""s, a character assignment needs ''.
I dont get the encryption part so much so I mocked up just a simple replacement code.
Bonus: you may want to ensure both x and X are replaced.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "xxistheXbestxandxmorexxHehehe";
int n = 100;
String message = decryption(s, n);
System.out.println(message);
}
public static String decryption(String s, int n)
{
int originalChar, decryptedChar;
String message = "";
String ret = "";
char c;
for(int i = 0; i < s.length(); ++i)
{
c = s.charAt(i);
decryptedChar = (int)c;
if(decryptedChar + n > 126)
originalChar = 32 + ((decryptedChar + n) - 113);
// Problem here
if(c =='x')
{originalChar = ' ';
c = ' ';}
else
{originalChar = decryptedChar + n;
c = c;}
message = message + (char)originalChar;
ret += c;
}//end for loop
//return message;
return ret;
}//end method
Use the method replaceAll of the String class.
For example:
String a = "AxBxCxD";
String b = a.replaceAll("x"," ");
String b is what you want, that is "A B C D". You need b, because replaceAll does not change a.
If you want to change a, you can set it to b:
a = b;
That's all :)

Get first letter of a String (more than one word)

I am trying to get the first letter of every word in a String:
String recInf = recursos.getString(nombre);
char[] tipoAbreviado = recInf.toCharArray();
tipoAbreviado[0] = Character.toUpperCase(tipoAbreviado[0]);
for (int i = 0; i < recInf.length() - 2; i++) {
// Es 'palabra'
if (tipoAbreviado[i] == ' ' || tipoAbreviado[i] == '.' || tipoAbreviado[i] == ',') {
// Reemplazamos
tipoAbreviado[i + 1] = Character.toUpperCase(tipoAbreviado[i + 1]);
}
nombre = tipoAbreviado.toString();
}
Finally the value of nombre is [C#3b1938ea, not the first letter of every word in recInf
You can use Arrays.toSting(your_array) to print your Array.
Take a look what toString() in Arrays do
public static String toString(long[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
But when you use tipoAbreviado.toString(); it will call toString() method in Object class.
What toString() method in Object class do?
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
That's why you are getting your current out put.
Instead of using toString on an Array which prints the memory address representation, you should create a String from char[] using new String(char[])
nombre = new String(tipoAbreviado);
You can use string's .split() with the correct regex and then just pick the first char:
String[] words = "Your String & !+ and some extraodrinary others".split("[^a-zA-Z]+");
for (String word: words ){
System.out.println(word.charAt(0));
}
You can try to fetch them with a Regular Expression.
When I use the RegEx (\w)\w+ on the string Hallo Welt, ich bin ein String, I get an array with H, W, i, b, e, S. Note: You have to run the expression as global expression (more than once).
Assuming the String object you want to process is recInf i would recommend to do it as follows:
String recInf = new String(text.replaceAll("[^\\p{L}\\p{Nd} ]+"," ")
.replaceAll("[\\s]+", " "));
String[] words = recInf.split(" ");
String[] firstLetters = new String[words.length];
for(int i=0; i<words.length;i++){
firstLetters[i]=words[i].getCharAt(0);
}
You could try this
nombre = (new StringBuilder(tipoAbreviado)).toString();

Two variables initialization at once in for loop

I want to write a code for reversing of string.
I know there are many methods for it. However, I want to try using Arrays. But I am having problem with the output.
Following is my code:
package practice_package;
public class Practice_Class {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "Jeevan";
char[] a = s1.toCharArray();
String s2 = "satyasahithi";
char[] b = s2.toCharArray();
String rs1 = new String(reverse(a));
System.out.println("The reverse of '" + s1 + "' is: '" + rs1 + "'");
String rs2 = new String(reverse(b));
System.out.println("The reverse of '" + s2 + "' is: '" + rs2 + "'");
}
public static char[] reverse(char[] args) {
char[] r = args;
int i,j;
for(i=args.length-1,j=0; i>=0 && j<args.length; i--, j++) {
r[j]= args[i];
}
System.out.println(r);
return r;
}
}
And my output is:
navvan
The reverse of 'Jeevan' is: 'navvan'
ihtihaahithi
The reverse of 'satyasahithi' is: 'ihtihaahithi'
As you can see, only the first half of the string is being reversed while the second half remains as it is.
What's the wrong in the code. Can I initialize two variables at once in 'for' loop like that. Where am I missing the logic?
When you assign last to first, you lose the char, you should keep it in temporary and assign to other.
for(i=args.length-1,j=0; i>=0 && j<args.length/2; i--, j++) {
char t = r[j];
r[j]= r[i];
r[i] = t;
}
Use StringBuffer.reverse()
String s1 = "Jeevan";
StringBuffer a = new StringBuffer(s1);
System.out.println(a.reverse());
The logic inside your for loop. Lets consider the first iteration where i points to 5 (in case of string Jeevan) and j points to 0. When you say r[j]= args[i] J will be replaces with n and you lose the character J. This is the part where your logic went wrong. As a solution either you can take another array and store as given below
public static char[] reverse(char[] args) {
char[] r = new char[args.length];
int i,j;
for(i=args.length-1,j=0; i>=0 && j<args.length; i--, j++) {
r[j]= args[i];
}
System.out.println(r);
return r;
}
or as nr4bt suggested above.

How to convert an integer value to string?

How do I convert an integer variable to a string variable in Java?
you can either use
String.valueOf(intVarable)
or
Integer.toString(intVarable)
There are at least three ways to do it. Two have already been pointed out:
String s = String.valueOf(i);
String s = Integer.toString(i);
Another more concise way is:
String s = "" + i;
See it working online: ideone
This is particularly useful if the reason you are converting the integer to a string is in order to concatenate it to another string, as it means you can omit the explicit conversion:
System.out.println("The value of i is: " + i);
Here is the method manually convert the int to String value.Anyone correct me if i did wrong.
/**
* #param a
* #return
*/
private String convertToString(int a) {
int c;
char m;
StringBuilder ans = new StringBuilder();
// convert the String to int
while (a > 0) {
c = a % 10;
a = a / 10;
m = (char) ('0' + c);
ans.append(m);
}
return ans.reverse().toString();
}
Integer yourInt;
yourInt = 3;
String yourString = yourInt.toString();
There are many different type of wat to convert Integer value to string
// for example i =10
1) String.valueOf(i);//Now it will return "10"
2 String s=Integer.toString(i);//Now it will return "10"
3) StringBuilder string = string.append(i).toString();
//i = any integer nuber
4) String string = "" + i;
5) StringBuilder string = string.append(i).toString();
6) String million = String.format("%d", 1000000)

Categories

Resources