So my program is supposed to say what type of a token it is from my input file. My second method is supposed to write whatever input from the keyboard to an output file until the user types stop. The problem is my first method won't output the integers to their right type. My second method will only put stop in the output file. Here is my code. Any help would be much appriciated.
public class R16 {
public void readFile(String inputFile) {
try {
File in = new File(inputFile);
Scanner scan = new Scanner(in);
while (scan.hasNext()) {
if (scan.hasNextInt()) {
System.out.println("Integer: " + scan.nextInt());
}
if (scan.hasNext()) {
System.out.println("String: " + scan.next());
}
if (scan.hasNextDouble()) {
System.out.println("Double: " + scan.nextDouble());
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error, not good");
}
}
public void writeFile(String outputFile) {
try {
File out = new File(outputFile);
PrintWriter w = new PrintWriter(out);
Scanner scan= new Scanner(System.in);
System.out.print("Enter Text: ");
while(!scan.next().equals("stop")){
w.print(scan.next());
}
w.close();
scan.close();
} catch (IOException e) {
System.out.println("Error, it just got real");
}
}
public static void main(String[] args) {
R16 test = new R16();
test.readFile(args[0]);
test.writeFile(args[1]);
}
}
In your loop, you check for stop then throw away all input.
while(!scan.next().equals("stop")){
Try using something like
String input;
while (!(input = scan.next()).equals("stop")) {
w.print(input);
Now within the loop, you have access to the input variable which contains the input string.
Related
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);
}
I would like to fix the java.util.NoSuchElementException bug.
I keep getting the error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Main.newUser(Main.java:28)
at Main.main(Main.java:18)
with this code
import java.util.Scanner;
import java.io.*;
class Main2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
input.close();
newUser();
}
private static void newUser()
{
try
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the name for the new user.");
String userNameNew = input.nextLine();
System.out.println("Please enter the password for the new user.");
String userPassWordNew = input.nextLine();
System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
PrintWriter out = new PrintWriter("users.txt");
out.print(userNameNew + "\r\n" + userPassWordNew);
out.close();
input.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
Can you please help me? Thank you.
I found the reason why you are getting this exception.
So in your main method, you initialized your Scanner class object and immediately close it.
Here is the problem. Because when scanner calls the close() method, it will close its input source if the source implements the Closeable interface.
When a Scanner is closed, it will close its input source if the
source implements the Closeable interface.
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
And InputStream class which is the input source in your case implements the Closeable interface.
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
And further you initialized the Scanner class object into your newUser() method. Here scanner class object initialized successfully but your input source is still close.
So my suggestion is that close scanner class object only once.
Please find the updated code of yours.
class Main2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
newUser(input);
//input.close()
}
private static void newUser(Scanner input)
{
try {
System.out.print("Please enter the name for the new user.");
String userNameNew = input.nextLine();
System.out.println("Please enter the password for the new user.");
String userPassWordNew = input.nextLine();
System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
PrintWriter out = new PrintWriter("users.txt");
out.print(userNameNew + "\r\n" + userPassWordNew);
out.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
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;
}
so im trying to read from a file the number of words and adding them up to give and int answer? And help and or suggestions would be nice, and i can only use a try/catch while for loop and if/else/if.... Thanks!
Here what i got so far:
package filereadingexercise2;
import java.io.*;
import java.util.Scanner;
/**
*
* #author theGreggstar
*/
public class FileReadingExercise2
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner keys = new Scanner(System.in);
String nameOfFile;
System.out.print("Please Enter The Name Of A File Or Directory, or Type Quit To Exit: ");
nameOfFile = keys.nextLine();
Scanner input = null;
try
{
input = new Scanner(new File(nameOfFile));
}
catch(FileNotFoundException s)
{
System.out.println("File does Not Exist Please Try Again: ");
}
while(input.hasNext())
{
String contents = input.next();
int length;
System.out.print(contents);
}
}
}
If I understand you correctly, you want something like this -
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
for (;;) { // Loop forever.
System.out.print("Please Enter The Name Of A File Or "
+ "Directory, or Type Quit To Exit: ");
String nameOfFile = keys.nextLine().trim(); // get the User input.
if (nameOfFile.equalsIgnoreCase("quit")) { // check for exit condition.
break;
}
File f = new File(nameOfFile); // Construct a File.
if (f.exists()) { // Does it exist?
if (f.isFile() && f.canRead()) { // is it a File and can I read it?
Scanner input = null;
try {
input = new Scanner(f); // The Scanner!
while (input.hasNextLine()) {
String contents = input.nextLine();
System.out.println(contents); // Print the lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (input != null) {
input.close(); // Close the file scanner.
}
}
} else if (f.isDirectory()) { // No, it's a directory!
try {
System.out.println("File "
+ f.getCanonicalPath()
+ " is a directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is a homework assignment, I have to write a program that reads a "input.txt" file and sees how many times to print a salutation (ex: Donald Duck, 4 so it prints Hello Donald Duck four times)
The problem I'm having is with outputting the salutation into a text file called "output.txt"
For some reason it only prints out the salutation for the last line in the input.txt instead of all of them.. Here's what I have so far:
import java.util.*;
import java.io.*;
public class Driver0 {
public static void main (String [] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Would you like the output to be written to a file?");
Scanner read;
String input = userInput.nextLine(); //user input
if(input.equals("yes")) {
System.out.println("Writing to \"output.txt\" now..");
}
else {
System.out.println("Printing to screen:");
}
try {
read = new Scanner(new File("input.txt")); //scanner reading file
}
catch (FileNotFoundException e){
System.out.println("File not found.");
return;
}
while(read.hasNextLine()) {
String newInput = read.nextLine();
String [] inputArray = newInput.split(","); //spliting
int num = 0;
num = Integer.parseInt(inputArray[2].trim());
for(int i = 0; i < num; i++) {
if(input.equals("yes")) { //writing to file
Driver0.outputting(inputArray);
}
else { //writing to screen
System.out.println("Hello" + inputArray[1] + inputArray[0]);
}
}
}
}
public static void outputting (String [] inputArray) {
PrintWriter output = null;
String fileName = "output.txt";
try {
output = new PrintWriter(new FileWriter(fileName));
}
catch(IOException error){
System.out.println("Sorry, can't open for writing.");
return;
}
output.println("Hello" + inputArray[1] + inputArray[0]);
output.close();
}
}
My problem is most likely within the outputting method or where it has a comment that says writing to file next to it
Every time through the while loop you're creating a new PrintWriter, writing one line to it, then closing it. This is just overwriting the file each time. You probably should only create one PrintWriter that you keep open and append to it instead.
The FileWriter class has a second constructor that takes a boolean argument to tell it to append to the end of the existing file rather than overwrite it from the start.
output = new PrintWriter(new FileWriter(fileName, true));
This is because you are creating each time a new file Using a new PrintWriter.
a minimally changed ,Quick fix for your sulution, will be (although there are yet many design problems in your code):
import java.util.*;
import java.io.*;
public class Driver0 {
public static void main (String [] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Would you like the output to be written to a file?");
Scanner read;
String input = userInput.nextLine(); //user input
if(input.equals("yes")) {
System.out.println("Writing to \"output.txt\" now..");
}
else {
System.out.println("Printing to screen:");
}
try {
read = new Scanner(new File("input.txt")); //scanner reading file
}
catch (FileNotFoundException e){
System.out.println("File not found.");
return;
}
////////////////////////
PrintWriter output;
String fileName = "output.txt";
try {
output = new PrintWriter(new FileWriter(fileName));
}
catch(IOException error){
System.out.println("Sorry, can't open for writing.");
return;
}
////////////////////////
while(read.hasNextLine()) {
String newInput = read.nextLine();
String [] inputArray = newInput.split(","); //spliting
int num = 0;
num = Integer.parseInt(inputArray[2].trim());
for(int i = 0; i < num; i++) {
if(input.equals("yes")) { //writing to file
Driver0.outputting(output,inputArray);
}
else { //writing to screen
System.out.println("Hello" + inputArray[1] + inputArray[0]);
}
}
}
///////////////////////////////
output.close();
///////////////////////////////
}
public static void outputting (PrintWriter output,String [] inputArray) {
output.println("Hello" + inputArray[1] + inputArray[0]);
}
}