0

Driver class:

String world = methods.printHelloWorld("Hello, world!");
{
    System.out.println(world);
}

method class:

public void printHelloWorld(String world)
{
    world = "Hello, world!";
}

Prompt: (part of a larger project)

void printHelloWorld()

Parameters: none

Return nothing. Directly prints to System.out the String "Hello, world!"

I'm getting the error that I cannot convert from void to String. I can't use a return in my method class. I know I can change public void printHelloWorld(String world) to public String printHelloWorld(String world), but that isn't what my teacher wants us to do. (I tried those already)

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Evan
  • 870
  • 1
  • 12
  • 24

6 Answers6

2

You can't convert to a String because there's nothing to convert. A return type of void means "does not return a value".

Also, you can assign values inside a method to a formal parameter all you want (unless it is declared final) and it won't change the value of the actual parameter used in the call to the method.

Perhaps you were trying to do this:

String world = "Hello, world!";
methods.printHelloWorld(world);

and

public void printHelloWorld(String world)
{
    System.out.println(world);
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

I know I can change public void printHelloWorld(String world) to public String printHelloWorld(String world), but that isn't what my teacher wants us to do. (I tried those already)

Then you can print inside the method itself. Something like:

public void printHelloWorld(String world)
{
    System.out.println(world);
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

The exception is very clear: You cannot convert from void to String.

This is how you can achieve what you are trying to do:

public void printHelloWorld(String world) {
    System.out.println(world);
}

Then

methods.printHelloWorld("Hello, world!");
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
0
public void printHelloWorld(String world)
{
    world = "Hello, world!";
    System.out.println(world);
}
Sachin Thapa
  • 3,559
  • 4
  • 24
  • 42
Victor
  • 16,609
  • 71
  • 229
  • 409
0

in method Class have

  public static String world = "Hello, world!";

in driver class

 String world1 = methods.world;
 System.out.println(world1);
0

Your method should return String

public String printHelloWorld(String world)
{
    world = "Hello, world!";
    return world;
}

or Simply

public String printHelloWorld(String world)
{
    return "Hello, world!";
}

Cheers !!

Sachin Thapa
  • 3,559
  • 4
  • 24
  • 42