user3363473
user3363473

Reputation:

Printing out two variables on one line?

I can't seem to figure out how to print both variables i and balance. When i use + it actually adds them. I also tried several other ways to do it that I looked up on Google but they didn't come out correct either. However When I print out either variable i or balance by themselves, I do get the correct result. Can someone help me?

import java.util.*; 

public class Forloops
{
    public static void main (String [ ] args)
    {
        System.out.print("Enter Balance:");
        double balance = input.nextDouble();

        System.out.print("Enter Number of Months:");
        int i = input.nextInt();

        for ( i = 0; i <= 12; i = i + 1 ) 
        {
            balance = balance * (1.00417);
            System.out.println( balance);
        }
    }
}

Upvotes: 1

Views: 399

Answers (4)

Forbidden404
Forbidden404

Reputation: 1

When you have a string and sum it with an integer, Java will cast the integer to string automatically. The problem is that you aren't using any string inside the println() function. So the basic thing is to add "" between i and balance.

System.out.println(i + "" + balance);

This would work fine, but you have to know why. If balance was a string, using the way you thought would work, don't forget this, java will cast the variable when needed, when you should've done, like adding two different type of variables.

Upvotes: 0

Gee858eeG
Gee858eeG

Reputation: 185

Alternatively

System.out.println(i + "" + balance);

or

System.out.println("After " + i +" months: " + balance);

Upvotes: 1

user2591612
user2591612

Reputation:

Try

System.out.println("I = " + i + " balance = " + balance);

Upvotes: 0

wns349
wns349

Reputation: 1306

try

System.out.println(String.valueOf(i) + String.valueOf(balance))

Upvotes: 2

Related Questions