I am trying to prompt the user to enter a file name and search for the filename and save it to 2 2-D array.
Example of the file is:
BBBBB
BBBBB
BBBBB
BBBBB
public class maze_2D{
static Scanner s = new Scanner(System.in);
public static void FromFile() throws Exception{//
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// Read from file.....
But when I run the program, i get an error
Enter Filename
java.io.FileNotFoundException:
Why is this happening, why this scanner doesn't allow me to enter any file name?
While inputting file name in command prompt give the full path including file name with extension where your file resides in the File System.
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
try {
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I made a little class using most of your code ad it worked fine... try examining your path+filename to ensure it is really there.
I have heard of scanner.getInteger forcing you to add a scanner.nextLine() after it but you are using nextLine to the the fileName so this shouldn't be the case.
public class NewClass {
static Scanner s = new Scanner(System.in);
public static void main(String args[]) throws Exception {
FromFile();
}
public static void FromFile() throws Exception {
System.out.println("Enter File name");
// I enter '/Users/myMame/Downloads/testFile.txt'
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// do your 2D array manipulation
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println("line: " + line);
}
}
}
Related
I having trouble figuring this out it supposed to print the contents of the txt file but i cant get it print.
This is the output im supposed to get.
Ingredient __________Amount Needed ______ Amount In Stock
baking soda_________4.50 ________________4.00
sugar ______________6.50________________3.20
import java.util.Scanner;
import java.lang.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
public class Lab8b {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
Scanner fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String name = fileScan.nextLine();
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
if (amountNeeded > amountInStock) {
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock");
System.out.println();
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
} //end if
if (amountNeeded <= amountInStock) {
System.out.println("Nothing");
} //end while
} //end if
} //end main
} //end class
Here are the problems I found with your code:
You created a while loop to read the contents of the file, but you don't do anything with it.
Need to wrap the code in a try-catch since FileNotFoundException might be thrown.
You attempt to call readLine() from filename instead of fileScan
I've assumed that you need amountNeeded and amountInStock to be doubles even though you don't do any calculations with them. If this isn't the case, you can simply leave them as strings instead of parsing.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
scan.close();
Scanner fileScan = null;
try {
fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock\n");
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I need to put my searching of the file in my readData() method in a loop that catches the fine not found exception then loops to prompt the user again for the file name until the correct one is entered. Once the proper file name is entered, then the return values pass to the other methods to continue the code.
I have tried putting the block of code into a do-while method but it results in a infinite loop. I need assistance with the semantics of this.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
I am expecting this to explain "File not found!" then prompt again for the file name until the correct one is entered. However it only does the try-catch once and then attempts to return the inputValues return value. This causes the program to crash.
I have tried do while loop. But it ends up in an infinite loop
package weightedavgdataanalyzer;
import java.io.*;
import java.util.*;
public class WeightedAvgDataAnalyzer {
public static void main(String[] args) {
ArrayList<Double> inputValues = readData();
double weightedAvg = calcWeightedAvg(inputValues);
printResults(inputValues, weightedAvg);
}
private static void printResults(ArrayList<Double> inputValues, double weightedAvg) {
System.out.print("Enter output file name: ");
Scanner input = new Scanner(System.in);
String outputFile = input.nextLine();
try {
PrintWriter writer = new PrintWriter(outputFile);
writer.print("The weighted average of the numbers is " + weightedAvg + ", when using the data ");
for (int i = 2; i < inputValues.size(); i++) {
writer.print(inputValues.get(i) + ", ");
}
writer.println("where " + inputValues.get(0)
+ " is the weight used, and the average is computed after dropping the lowest "
+ Integer.valueOf((int) inputValues.get(1).doubleValue()) + " values.");
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static double calcWeightedAvg(ArrayList<Double> inputValues) {
double sum = 0;
double average;
double weight = inputValues.get(0);
int toDrop = Integer.valueOf((int) inputValues.get(1).doubleValue());
ArrayList<Double> newList = new ArrayList<>();
for (int i = 2; i < inputValues.size(); i++) {
newList.add(inputValues.get(i));
}
Collections.sort(newList);
for (int i = (toDrop); i < newList.size(); i++) {
sum += weight * newList.get(i);
}
average = sum / (newList.size() - toDrop);
return average;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
}
Move the initialization of File file = new File(inputFileName); inside the loop as well as the "ask for new file name line". And last step is to also check if the file is an directory. You can't read directories with a Scanner, but file.exists() will still return true
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
File file;
System.out.print("Enter the name of the input file: ");
do {
inputFileName = input.nextLine();
file = new File(inputFileName);
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
} while (!file.exists() && !file.isDirectory());
return inputValues;
}
The other answers have not addressed that it is bad practice to control the flow of your code using catch and exception. You should reserve using your catch block for typically printing your errors or logging them.
I moved the logic of asking for the file into a loop that does not depend on an exception to correctly execute and placed it into a reusable method.
Here is what this change would look like:
ArrayList<Double> inputValues = new ArrayList<>();
double value;
File file = promptForFile(); //Condensed into a clean reusable single line of code
try {
Scanner input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //Or log the error
}
And the method you can reuse anywhere for a new prompt:
public static File promptForFile()
{
System.out.print("Enter the name of the input file: ");
Scanner input = new Scanner(System.in);
String inputFileName = input.nextLine();
File file = new File(inputFileName);
while(!file.exists() && !file.isDirectory())
{
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
inputFileName = input.nextLine();
file = new File(inputFileName);
}
return file;
}
Now the logic of your code is separated from searching for the file and the code is extremely reusable and readable.
This couldn't be done before since you had two different logics mixed intertwined.
File myFile = new File("myFile.txt");
while(!myFile.exists()){
//re-enter filename and instantiate myFile as a new object using it as the argument
}
could just check whether the file exists in a loop like so before using it. The issue with looping for the FileNotFoundException is that your writer is what throws that, so you would have to constantly instantiate the writer and check whether the exception is thrown before possibly looping again, which isn't ideal.
The problem is when the exception is caught, you never ask for a new file name, so you are running the code on the same faulty file path over and over again. To fix this, just move this code block:
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
inside the loop.
You may also want to eliminate a condition on your loop, and instead add a return; at the end of your try block.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
while (true) {
try {
// Get response in the loop, instead of one time-only
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
// Add your return statement here to get rid of the conditional
// loop.
return inputValues;
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
}
You can take input and can return once file is found or else can keep recording error message
public File getFile(){
while(true) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the name of the input file: ");
File file = new File(System.in);
if (file.exists()) {
return file;
}else{
System.out.println("File not found! Please try again ");
}
}
}
}
private List<Double> getData(File file){
List<Double> listOfDoubles = new ArrayList<>();
try(Scanner scanner = new Scanner(file)){
while(scanner.hasNextDouble()) {
listOfDoubles.add(scanner.nextDouble());
}
}
return listOfDoubles;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
File inputFile = getFile();
return getData(inputFile);
}
Hi I'm a beginner to file I/O and I'm having a small problem with writing to a file. What my program should do is write a username and password to a file. Here's my code (ill describe my problem after the code because its specific to program):
public class Helper {
public static void main(String[] args) throws Exception {
Home();
UserInput();
}
private static void Home() throws FileNotFoundException{
System.out.println("Here are the instrucions for the chat program:");
System.out.println("Type *R for registration" );
}
private static void UserInput() throws Exception{
Scanner scan = new Scanner(System.in);
String input = scan.next();
if(input.equals("*R")){
Register();
}
main(new String[0]);
}
private static void Register() throws FileNotFoundException{
try{
File info = new File("info.txt");
info.createNewFile();
FileOutputStream outputStream = new FileOutputStream(info);
PrintWriter out = new PrintWriter(outputStream);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
What I need is my info.txt file to store all of the usernames and passwords each pair on a different line, however it only stores the most recent one. That is, each time I write to info.txt it overwrites the most recent pair(username and password). Is there a way around this?
Java FileWriter constructor is called like this:
new FileWriter(String s, boolean append);
This simple constructor indicates that you want to write to the file in append mode.
Try following code:
private static void Register() throws FileNotFoundException{
try{
FileWriter fw = new FileWriter("info.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
Use this constructor instead. new FileOutputStream(info,true);
I'm trying to get the user to input their file name. If the file name is valid it passes through. However, if the file name is invalid then its suppose to ask the user again for a file. If a purposely enter an invalid file name, the program doesn't get past the exception branch.
Here's the code:
public class LineNumbers {
private static Scanner getFile() {
Scanner in = new Scanner(System.in);
Scanner scannedFile = new Scanner(System.in);
String inputFile;
boolean validFile = false;
while (!validFile) {
try {
System.out.print("Enter your file name: ");
inputFile = in.nextLine();
scannedFile = new Scanner(new FileReader(inputFile));
validFile = true;
} catch (Exception e) {
System.out.print(e);
System.out.print("Invalid File");
in.next();
scannedFile.next();
}
}
return scannedFile;
}
public static void main(String[] args) {
String word = getFile().nextLine();
}
}
Do are getting problems when calling in.next(); and scannedFile.next(); in catch block. You have already expected in.readLine() if invalid user input occurred. Additionally you should understand that the scannedFile is reachable, that's why got the exception. So you cannot use scannedFile.next(); in the catch block also.
Do following modifications
private static Scanner getFile() {
Scanner in = new Scanner(System.in);
Scanner scannedFile = new Scanner(System.in);
String inputFile;
boolean validFile = false;
while (!validFile) {
try {
System.out.print("Enter your file name: ");
inputFile = in.nextLine();
scannedFile = new Scanner(new FileReader(inputFile));
validFile = true;
} catch (Exception e) {
System.out.println(e);
System.out.println("Invalid File");
//no scanned file, input file could not find
scannedFile = null;
//file was not valid
validFile = false;
}
}
return scannedFile;
}
I can't figure out how to pass the Strings need to the method below.
stringToFile(); and
readingStringFromFile();
I know I need to pass the Strings in the main method but I can't figure out how.
Thanks in advance.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);//allow for use of keyboard input
mask(keyboard);
printingString();
fileName(keyboard);
stringToFile();
readingStringFromFile();
}
public static int mask(Scanner keyboard){
int holder;//creats a temp int
System.out.print("Enter the encryption mask: ");//asks fro encrytipon
holder = keyboard.nextInt();//userinput to holder
keyboard.nextLine();//consumption
return holder;//returns encryption mask
}
public static void fileName(Scanner keyboard){
String fileName ="a";
System.out.print("\nEnter a file name without extensions: ");
fileName = keyboard.next();//userinput to fileName
String completeFileName = fileName + ".txt";
}
public static void printingString(){
System.out.println("Original random character string:");
for (int i = 0; i < 50; i++)//loop to obtain 50 random characters
{
char randomChar = (char) ((Math.random()*255)+32);
System.out.print((randomChar));
}
}
public static void stringToFile(String completeFileName, String printingString)
throws FileNotFoundException {
System.out.println("Saving Original random character string...");
File myFile = new File (completeFileName);
Scanner fileReader = new Scanner (myFile);
PrintWriter fileWriter = new PrintWriter (myFile);
fileWriter.println(printingString);
fileWriter.close();
}
public static void readingStringFromFile(String completeFileName)
throws FileNotFoundException {
System.out.println("Original random character string from the file");
File myFile = new File (completeFileName);
Scanner fileReader = new Scanner (myFile);
String lineFromFile = fileReader.nextLine();
System.out.println(lineFromFile);
}
In your main method you should get the input -
System.out.println("Enter file name : ");
String completeFileName = keyboard.next();
System.out.println("Enter string : ");
String printingString = keyboard.next();
stringToFile(completeFileName, printingString);