Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Java 1 Help In this exercise we write a program that copies two numbers from an input stream to the console Create a new Java
Java 1 Help
- In this exercise we write a program that copies two numbers from an input stream to the console
- Create a new Java file and name it TwoNumbers.
- Then, let's create a text file to test our program.
- In Eclipse, click on the name of the project. Then, go to File->New->File
- Name your text file infile.txt.
- In the file, add a list of numbers each on their own line, like this:
10 20
-
We will read from this file in our program.
- Now, we will create a second text file.
- Click on the name of the project again. Then, go to File->New-File
- Name this file outfile.txt
- Now, open TwoNumbers.java.
- Add a main method and place the following import statement above main:
import java.io.*;
- Also, as part of the signature of main(), add throws IOException:
public static void main(String[] args) throws IOException{
- Declare two int variables at the top of main:
int first;
int second;
- Add code to create a new File object:
File inFile = new File("infile.txt");
- Add statements to read two numbers from the input stream. For example, here is the correct code for reading the first number:
Scanner input = new Scanner(inFile); first = input.nextInt();
- Close the stream when finished reading:
input.close();
- Next, we will add some code to write to a file.
- Declare a new File variable for the outfile.txt:
File outFile = new File("outfile.txt");
- Next, declare a PrintWriter variable and connect it to this File:
PrintWriter out = new PrintWriter(outFile);
- Using the PrintWriter, we will write some text into our outfile:
out.println("first=" + first);
//add a line of code to print the second number here
- Lastly, close the PrintWriter:
out.close();
- Compile and run your modified program to make sure you made the changes correctly.
- When you run the code, nothing should appear on the console.
- Instead, open outfile.txt in Eclipse and verify that you have the following contents in your file:
first=10 second=20
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started