public class Main {
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(tex));
reader.close();
}
public static int calculateCharacters(String text, int tex){
tex = text.length();
return tex;
}
}
So I receive a string from String text, then I send it to the method to calculate it's length and return a number which should be intercepted by System.out.println(calculateCharacters(tex));
and the probram should show me the number of letters in the string that was entered, the problem is: nothing reaches System.out.println(calculateCharacters(tex));
why ? where is this return tex;
returning it then ?
Well I'm not entirely sure why you've got an int tex
variable, but removing it lets this work perfectly. Try rewriting your method:
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
or if you're ready to be snazzy:
public static int calculateCharacters(String text) {
return text.length();
}
Java is pass-by-value ( Is Java "pass-by-reference" or "pass-by-value"? ), so keeping an extra int in there that you only use to store things locally won't actually change your value of tex.
Also, you instantiate the String
text
, but then pass tex
to calculateCharacters()
. Since you haven't created a tex
variable before this, your compiler doesn't know what to pass to calculateCharacters()
. Try changing that to:
System.out.println(calculateCharacters(text));
instead.
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(text));
reader.close();
}
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
}
It works
For counting the string use below code...
public class Main {
static int stringCount;
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
calculateCharacters(text);
System.out.println(stringCount);
reader.close();
}
public static int calculateCharacters(String text){
stringCount = text.length();
return stringCount;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.