Java Reference
In-Depth Information
System . out . print (
"Total credit (in US dollars):\t"
);
System . out . println (100+150) ;
System . out . print (
"Total debit (in US dollars):\t"
);
System . out . println (50+25+100) ;
System . out . print (
"Balance:"
);
}
}
Running this program, we get:
Total credit (in US dollars):
250
Total debit (in US dollars):
175
Note that the
t
inside the string
"Total credit (in US dollars):\t"
denotes
the
tabulation
character that allows one to nicely align the latter numbers. The
problem is to get the balance we need to subtract 175 from 250. Of course, this
could be computed and displayed with the instruction:
\
System.out.println((100+150)-(50+25+100));
...but this will not yield an ecient approach since we would again compute the
two cumulative credit/debit sums. A much better strategy consists of storing
intermediate calculations in containers by using variables, as explained next.
1.6.1 Variables for storing intermediate values
In Java, variables are all
typed
. Java belongs to the large category of typed
programming languages. This means that we need to specify the type of
variables when declaring variables. To declare a variable named
credit
for
storing the overall credit modeled as an integer number, we use the syntax:
int credit;
Variables always need to be declared before use. By convention, we choose
in this textbook to declare all variables at the beginning of the
main
block
(delimited by the braces
). In this application, we consider that credit/debit
numbers are natural numbers (integers), so that we declare the variable to be
of type
int
.
{}
Program 1.8
Balance sheet using integer variables
class
BalanceSheet2
{
public static void
main ( String [
]
args )
int
credit ;
int
debit ;
Search WWH ::
Custom Search