Skip to content

Commit 0366862

Browse files
committed
added a question to 3.1
1 parent 4727ea1 commit 0366862

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

source/ch3_javadatatypes.ptx

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,44 @@ 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+
234+
<exercise xml:id="java-square-number-exercise" label="java-square-number-exercise">
235+
<statement>
236+
<p>
237+
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.
238+
</p>
239+
<program xml:id="java-square-number" interactive="activecode" language="java">
240+
<input>
241+
public class KmToMiles {
242+
public static void main(String[] args) {
243+
// write your code here
244+
}
245+
}
246+
</input>
247+
</program>
248+
</statement>
249+
<solution>
250+
<program language="java">
251+
<input>
252+
import java.util.Scanner;
253+
public class KmToMiles {
254+
public static void main(String[] args) {
255+
Double kilometers;
256+
Double miles;
257+
Scanner input;
258+
input = new Scanner(System.in);
259+
System.out.print("Enter distance in kilometers: ");
260+
kilometers = input.nextDouble();
261+
miles = kilometers * 0.621;
262+
System.out.println(kilometers + " kilometers is equal to " + miles + " miles.");
263+
}
264+
}
265+
</input>
266+
</program>
267+
</solution>
268+
</exercise>
269+
270+
233271
</subsection>
234272

235273

0 commit comments

Comments
 (0)