Skip to content

Commit 0c44ce9

Browse files
authored
Merge pull request #365 from habibasorour/issue_363_practice
Issue 363: added a question to 3.1
2 parents 4727ea1 + d82ee5b commit 0c44ce9

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

source/ch3_javadatatypes.ptx

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ public class TempConv {
230230
<p>
231231
So, what exactly does the import statement do? What it does is tell the compiler that we are going to use a shortened version of the class&#x2019;s name. In this example we are going to use the class <c>java.util.Scanner</c> but we can refer to it as just <c>Scanner</c>. We could use the <c>java.util.Scanner</c> class without any problem and without any import statement, provided that we always referred to it by its full name. As an experiment, you may want to try this yourself. Remove the import statement and change the string Scanner to <c>java.util.Scanner</c> in the rest of the code. The program should still compile and run.
232232
</p>
233+
233234
</subsection>
234235

235236

@@ -279,6 +280,44 @@ public class TempConv {
279280
<p>
280281
The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. In our temperature converter, the calculation <c>(fahr - 32) * 5.0/9.0</c> works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written <c>5/9</c>, which would result in 0.
281282
</p>
283+
284+
285+
<exercise xml:id="java-square-number-exercise" label="java-square-number-exercise">
286+
<statement>
287+
<p>
288+
Write a program that converts km to miles. Use the <c>Scanner</c> class to read the input. Note that 1 km is approximately equal to 0.621 miles.
289+
</p>
290+
<program xml:id="java-square-number" interactive="activecode" language="java">
291+
<input>
292+
public class KmToMiles {
293+
public static void main(String[] args) {
294+
// write your code here
295+
}
296+
}
297+
</input> <stdin> </stdin>
298+
</program>
299+
</statement>
300+
<solution>
301+
<program language="java">
302+
<input>
303+
import java.util.Scanner;
304+
public class KmToMiles {
305+
public static void main(String[] args) {
306+
Double kilometers;
307+
Double miles;
308+
Scanner input;
309+
input = new Scanner(System.in);
310+
System.out.print("Enter distance in kilometers: ");
311+
kilometers = input.nextDouble();
312+
miles = kilometers * 0.621;
313+
System.out.println(kilometers + " kilometers is equal to " + miles + " miles.");
314+
}
315+
}
316+
</input>
317+
</program>
318+
</solution>
319+
</exercise>
320+
282321
</subsection>
283322
</section>
284323

0 commit comments

Comments
 (0)