Write a program called FileInput to read an int, a double, and a String form a text file called 'test.txt', and produce the following output: a. The integer read is 24, b. The floating point number read is 70.94, c. The String read is 'Archangel', d. Hi! Archangel, the sum of 24 and 70.94 is 94.94. (Hint use Scanner to read from file)
Updated: Oct. 2, 2023 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Java Programming
Difficulty: Intermediate.
Companies who previously asked this: -.
Objective: Write a program called FileInput
to read an int
, a double
, and a String
from a text file called test.txt
, and produce the following output:
a. The integer read is 24
b. The floating point number read is 70.94
c. The String read is "Archangel"
d. Hi! Archangel, the sum of 24 and 70.94 is 94.94
Hint: use Scanner
to read from file.
Input: Read an int
, a double
, and a String
from a file.
Expected Output: Result will vary based on the data in the file..
Sikademy Solution
package sikademy;
/**
*
* @author Archangel Macsika
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
// This class reads the content of file and prints it in required format.
public class FileInput {
private static final Logger LOG = Logger.getLogger(FileInput.class.getName());
public static void main(String[] args) {
LOG.info("Into Main method");
String[] fileValues = new String[3];
int i = 0;
File file = new File("/sikademy/test.txt");
if (file.exists() && file.isFile()) {
try {
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
fileValues[i] = scan.nextLine().toString();
i++;
}
String valueOne=fileValues[0];
String valueTwo=fileValues[1];
String valueThree=fileValues[2];
LOG.info("The integer read is: " + Integer.valueOf(valueOne));
LOG.info("he floating point number read is :" + Float.valueOf(valueTwo));
LOG.info("The String read is :" + valueThree);
LOG.info("Hi " + valueThree + "!, the sum of " + Integer.valueOf(valueOne) + "and " + Float.valueOf(valueTwo) + " is " + (Integer.valueOf(valueOne) + Float.valueOf(valueTwo)));
} catch (FileNotFoundException e) {
LOG.log(Level.SEVERE, "Exception occurred. The Exception is : " + e.getMessage());
}
}
else{
LOG.log(Level.SEVERE,"Sorry!! File not found...");
}
}
}