Steveo
Steveo

Reputation: 557

Java unexpected output

Can some explain how i'm getting this answer:

three times two = 6

Code:

public class Params1 {
    public static void main(String[] args) {
        String one = "two";
        String two = "three";
        String three = "1";
        int number = 20;
        sentence(one, two, 3);
    }

    public static void sentence(String three, String one, int number) {
        String str1 = one + " times " + three + " = " + (number * 2);
    }

}

Upvotes: 0

Views: 279

Answers (5)

Denys Séguret
Denys Séguret

Reputation: 382092

Here's an useful diagram :

enter image description here

I hope it's clear.

And here's how you could have made the same code less confusing :

    public static void main(String[] args) {
        String a = "three";
        String b = "two";
        sentence(a, b, 3);
    }

    public static void sentence(String a, String b, int number) {
        String str1 = a + " times " + b + " = " + (number * 2);
        System.out.println(str1); // to let you inspect the value
    }

Upvotes: 7

Sanjeev
Sanjeev

Reputation: 433

String str1 = one + " times " + three + " = " + (number * 2);

here one == two == "three"

and three == one == "two"

and number== 3

so you are getting that out put. Better you refer : JAVA methods help

Upvotes: 0

Sirko
Sirko

Reputation: 74036

In the call to the sentence()

sentence(one, two, 3);

just replace, for the arguments sake, all variables with their values:

sentence( "two", "three", 3);

Then have a look what values the parameters inside that function get:

three == "two"
one == "three"
number == 3

Then replace the parameters in the sentence you generate and you have your result!

Besides, your variables names are not really self-explanatory. You should rethink them to prevent such misunderstandings.

Upvotes: 5

Wessel van der Linden
Wessel van der Linden

Reputation: 2622

you're giving 3 as a parameter for the 'sentence' method.

sentence(one, two, 3);

change that to

sentence(one, two, number);

Upvotes: 0

mprivat
mprivat

Reputation: 21902

It's really hard to guess what you are trying to achieve here. Surely, you don't expect the "string" literals to be interpreted as actual numeric values...

Correct your variable values:

String one = "one";
String two = "two";

and:

sentence(three, one, 3);

and:

public static void sentence(String three, String one, int number) {
    String str1 = one + " times " + three + " = " + (number);
}

Upvotes: 0

Related Questions