package com.example.test1;
import java.util.Scanner;
public class class1{
public static String methodOne(String name){
String studentName = name + " is his name";
return (studentName);
}
public static void main(String[] args) {
methodOne("John");
}
}
How can I get this method to print out name + " is his name"? It shows nothing when I run this. I also can't add a System.out.println in the String studentName. I'm new to all of this sorry. EDIT: I want to somehow input the print function into the method and not type out System.out.println to print out methodOne, is it possible?
package com.example.test1;
import java.util.Scanner;
public class class1{
public static String methodOne(String name){
String studentName = name + " is his name";
return (studentName);
}
public static void main(String[] args) {
System.out.println(methodOne("John")); // Print string in this console
}
}
The function of returns a value that is string, so when you call her like that :
methodOne("John");
You didn't use the string value, you didn't say print it or anything.
You can use the returned value like this:
package com.example.test1;
import java.util.Scanner;
public class class1{
public static String methodOne(String name){
String studentName = name + " is his name";
return (studentName);
}
public static void main(String[] args) {
String nameStudent = methodOne("John"); // Saves the returned value in a variable
System.out.println(nameStudent ); // Prints the returned value stored in the variable
}
}
You can also print straight without storing a variable, as they say here already.
I want to somehow input the print function into the method.
There are two ways I could interpret it.
You could just mean that you want print within the methodOne method. That is easy:
public static String methodOne(String name){
String studentName = name + " is his name";
System.out.println(studentName);
return studentName;
}
Comments:
If you are going to do it this way, there isn't an obvious reason why methodOne needs to return anything. You could declare it as a void method.
Doing this is probably bad design. Generally speaking, a method should do one thing. (The design principle is Separation of Concerns (SoC).) But this modified method is doing two things. It is forming the string, and it is printing it. And since it is printing it to a specific place (standard output), it's utility is limited. (What if I wanted to create that string without printing it? What if I wanted to print it to a different stream?)
The second interpretation is that you literally want to pass the println method to the methodOne method ... so that it can call it. This is how you could do it:
public static String methodOne(String name,
java.util.function.Consumer<String> fn){
String studentName = name + " is his name";
fn(studentName);
return studentName;
}
and call it like this
methodOne("Fred", System.out::println);
Related
I've been stuck here for a while.
I want to call string lesson from the lesson method into my toString() method. Both methods are in the same class.
Here is lesson method:
public static String lesson() {
System.out.println("Now you have written about your day, what are the lesson learnt ? Huh??");
Scanner lessonLearned = new Scanner(System.in);
String lesson = lessonLearned.nextLine();
return lesson;
}
Here is the toString method
#Override
public String toString() {
String final = "";
final = "[" + Calendar.getInstance().getTime() + "," +lessonShouldBeHere+ "," AnotherString + "]";
return out;
}
As written, String lesson is a local variable, and not accessible outside the context of the method (because it is on the stack and no longer exists).
static String storedLesson = null;
public static String lesson() {
System.out.println("Now you have written about your day, what are the lesson learnt ? Huh??");
Scanner lessonLearned = new Scanner(System.in);
String lesson = lessonLearned.nextLine();
storedLesson = lesson;
return lesson;
}
To solve this problem, make a static variable that holds the lesson value. I suggest static because this is a static method. If this method was a member method of a class, it would be better to make this a member variable.
Then use storedLesson in your toString method
This question already has answers here:
What does "void" mean as the return type of a method? [duplicate]
(5 answers)
Closed 5 years ago.
I have done a simple code to reverse a string in Java without using the inbuilt functions. But I have observed that unlike C where we can get a changed string back in the same variable using pointers, which it is not possible in Java due to the absence of pointer concept. So please show me what alternative way can I get back the string in the main function in Java.
class RevFun{
public void revFun(StringBuilder str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.println(str.charAt(i));//Here I am able to print it!
}
return;
}
}
class Rev
{
public static void main(String args[])
{
RevFun rev = new RevFun();
StringBuilder str = new StringBuilder("Hello");
System.out.println("Before reversing : "+str);
rev.revFun(str);
System.out.println("After reversing : "+str);//Here what should I do to get the reversed string from RevFun
}
}
give the second method returntype String
public static String handleString(String input){
// modify input
input += " test";
return input;
}
and either use, or assign the (new) value in your main:
public static void main(String[] args){
String a = "hello";
String b = handleString(a);
System.out.println(a);
System.out.println(b);
}
another way is to have your variable on class level:
static String test = "hi";
public static void main(String[] args){
System.out.println(test);
handleString();
System.out.println(test);
}
public static void handleString(){
test += " and bye";
}
both methods have access to the variable, so you won't even need to pass it as a parameter.
In Java Strings are immutable. This means that you can't change them. You can read more here
So if you want to "manipulate" an String you will have to return a new object
I have created an example class for my problem below.
public class testClass {
public void testMethod()
{
int testInteger = 5;
}
String testString = "Hello World" + testInteger;
}
I have an integer inside a method and a string that is in no method as seen above. I want the string to get the integer that inside the method but it cannot. Can someone please help explain why that is so and tell me how to make the string the integer. thanks.
For example:
public class testClass {
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
String testString = "Hello World" + testMethod();
}
The integer is a variable inside the method; it has scope of the method which means it can't be accessed from outside the method. The String is a field; it has scope of the class, so it can be accessed from anywhere inside the class including inside the method.
It's basic Java... the testInteger is defined in the method so not available out of the method. You could let the method return an int (being your testInteger) and call that method.
You cannot access a local variable from another method without returning it.
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
Then you can get the value by calling the method (assuming you have an instance of your class in a reference instance),
String testString = "Hello World" + instance.testMethod();
From The Java Tutorials: Variables,
Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Lets break down your code to see what is going on
you have such a function
public void testMethod()
{
int testInteger = 5;
}
as you see the return type is void so nothing will be return to anywhere that is called this method.
you have this line after your testMethod
String testString = "Hello World" + testInteger;
first it looks odd why?
because you do not have any main method so I do not know how your code runs
but Imagine you have main method like this
public static void main(String[] args){
String testString = "Hello World" + testInteger;
}
second, you did not even call your testMethod in order to utilize it inside your main method
Issues
1. you did not call your testMethod at all
2. Even if you called it, it would not help you because your return type is void
3. you need main method in order your code to be ran
Remedies
1. change your return type to int
your function signature:
public int testMethod()
2. if you want to use your method, you have to use it in your main method like
for example:
String testString = "Hello World" + testMethod();
3. do not forget to have your main method because it is necessary for your code to be ran
your main method signature is
public static void main(String[] args)
I am asked to "Write a static method which, given a String as an input parameter, will return another String representing the input string with all vowels removed."
I'm not exactly sure what they mean by this. I wrote this below. What would I need to change to the answer? Thanks
public static void main(String[] args) {
String s = "Hello there";
String s1 = s.replaceAll("[AaEeIiOoUu]", "");
System.out.print(s1);
}
Check answers from #NicksTyagi and others for the static method. However, I wanted to point out that you can optimize your regex like this: (?i)[aeiouy].
(?i) is an inline flag that indicates that the part of the regex that follows it, is case insensitive. By using this flag it's not necessary to put the letters in upper case.
Feel free to remove the y from the regex if it isn't considered as a vowel in your language.
Sample code
public static String removeVowels(String input) {
return input.replaceAll("(?i)[aeiouy]", "");
}
The static method you copied and pasted into your question is called main. It's kind of special, it takes a string[] as an argument, and it always returns void. In order to complete your assignment, you need to write another static method.
First, you need to give it a name.
static myFunction() {
}
Next, give it a return (output) type. Your assignment was to return a String.
static String myfunction() {
}
Then, you need to let it accept a parameter (input) of type String.
static String myFunction(String input) {
}
Almost last, we'll add in the logic to transform the input into an output.
static String myFunction(String input) {
input = input.replaceAll("[AaEeIiOoUu]", "");
}
Finally, we need to return the output.
static String myFunction(String input) {
String output = input.replaceAll("[AaEeIiOoUu]", "");
return output;
}
Viola. You are done! You won't need to know much more about the static keyword until you study object-oriented programming. The correct definition is that static methods are bound to a class, while non-static methods are bound to an instance of a class. Here is a gruesome example.
A static method could accept a Person and return a Person with all of its arms chopped off.
I am a person. I could use my very own non-static method to remove all of my arms.
Hope that helps you remember!
The class must be as below :
public class Demo {
public static String replaceVowel(String input)
{
input = input.replaceAll("[AaEeIiOoUu]", "");
return input;
}
public static void main(String[] args) {
String output = Demo.replaceVowel("Hello World");
System.out.println(output);
}
}
You just need to create another method with the static keyword. Call this method from main.
public static void main(Strings args[]){
removeVowels("Hello World");
}
public static String removeVowels(String textWithVowels){
return textWithVowels.replaceAll("[AaEeIiOoUu]", "");
}
When i run 2nd class i see " Car#15ab7626 " why ? in teory i must see 20, yes?
I have alredy used differnet combinatoin & ask google but dont understent why.
i have 1 class
public class Car {
public int drive(int a) {
int distance = 2*a;
return distance;
}
}
and 2nd class
public class CarOwner {
public static void main(String[] args) {
Car a = new Car();
a.drive(10);
System.out.println(a);
}
}
You are printing the car object, not the result printed by drive
That incomprehensible value JAVA is textual representation of Object.
When you do System.out.println(a); then by default toString() method calls on passed object.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Car#15ab7626 is the textual representation of Values class.
To print result which is returned by your drive() method, print,
System.out.println(a.drive(10));
If you want to print the result from the drive() method, assign the result to a variable and then print it.
int result = a.drive(10);
System.out.println("Result = " + result);
or directly pass the result to the System.out.println() method;
System.out.println("Result = " + a.drive(10));
If you want to print the a object in a readable way, override the toString() method in the Car class definition.
#Override
public String toString() {
return "This is a car"; //for example
}
You are returning the value you have from a drive method, but you're not printing it.
To print out the value of the drive method, use
public class CarOwner {
public static void main(String[] args) {
Car a = new Car();
System.out.println(a.drive(10));
}
}
That's not the way method return values work. If you want to see the result as 20, replace your SOP with the following
System.out.println(a.drive(10));