This is a very basic program for Uni which writes user data to a file. I have followed the instructions clearly yet it does not seem to output the data to a file. All it does is create an empty file. I'm using Ubuntu, if this makes a difference.
import java.util.Scanner;
import java.io.*;
/**
This program writes data to a file.
*/
public class FileWriteDemo
{
public static void main(String[] args) throws IOException
{
String fileName; // File name
String friendName; // Friend's name
int numFriends; // Number of friends
// Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Get the number of friends
System.out.print("How many friends do you have? ");
numFriends = keyboard.nextInt();
// Consume the remaining new line character
keyboard.nextLine();
// Get the file name
System.out.print("Enter the filename: ");
fileName = keyboard.nextLine();
// Open the file
PrintWriter outputFile = new PrintWriter(fileName);
// Get data and write it to a file.
for (int i = 1; i <= numFriends; i++)
{
// Get the name of a friend
System.out.print("Enter the name of friends " +
"number " + i + ": ");
friendName = keyboard.nextLine();
}
// Close the file
outputFile.close();
System.out.println("Data written to the file.");
}
}
You are creating a PrintWriter instance but nothing is being written to it.
Perhaps you meant to include outputFile.println(friendName) inside the for-loop?
Try
for (int i = 1; i <= numFriends; i++)
{
// Get the name of a friend
System.out.print("Enter the name of friends " +
"number " + i + ": ");
friendName = keyboard.nextLine();
outputFile.println(friendName);
}
Related
The thing i'm hoping to do is read a csv file with 6 rows and 6 columns in it using Java. I then need to print out each row and allow the user to select 1 option. Here is what I have, I know my code chooses 1 and prints it, but I don't know how to change it from printing one random row, to printing all 6 rows. Probably in an ArrayList or 2dArray?
package theContest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
public class theContest {
// The main() method
public static void main(String[] args) throws FileNotFoundException {
//
String fileName = "contest.csv";
File file = new File(fileName);
if (!file.isFile()) {
System.err.println("Cannot open file: " + fileName + ".");
System.exit(0);
}
//
int numContest = 0;
Scanner input = new Scanner(file);
while (input.hasNext()) {
input.nextLine();
numContest++;
}
input.close();
System.out.println("Total of " + numContest + " contestants.");
//
int winner = 0;
Random random = new Random();
winner = random.nextInt(numContest) + 1;
System.out.println("The winner is contestant number " + winner + ".");
//
String winnerDetails = "";
input = new Scanner(file);
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
input.close();
System.out.println("Winner is: " + winnerDetails);
//
String id = "";
String name = "";
String seats = "";
String trans = "";
String rate = "";
String price = "";
input = new Scanner(winnerDetails);
input.useDelimiter(",");
id = input.next();
name = input.next();
seats = input.next();
trans = input.next();
rate = input.next();
price = input.next();
input.close();
System.out.println("Details are:");
System.out.printf("%-5s : %s\n", "ID", id);
System.out.printf("%-5s : %s\n", "Name", name);
System.out.printf("%-5s : %s\n", "Seating", seats};
System.out.printf("%-5s : %s\n", "Transfer", trans};
System.out.printf("%-5s : %s\n", "Rate", rate};
System.out.printf("%-5s : %s\n", "Price", price};
}
}
Here:
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
Your file has N rows. The above code iterates all lines, and stores the result in a single variable. In each iteration, you overwrite what you put there before. So, what your code does is: it reads N lines, and throws away everything prior the last row.
In other words: if you have 6 lines, and you want to print all of them ... then that all your processing needs to be "part" of a loop, too.
For example, you could turn winnerDetails into an array of String, and then put each line in its own slot. Then you loop over the array, and print each slot.
And as you already know about ArrayList, best use that then. That also means: you need to read the file only once. Open the file, read each line, and push that into an ArrayList. Afterwards, you can do whatever you want with that list.
And note: that is actually the point you should start with. Dont solve your whole problem at once. Slice it into smaller parts. Like: reading data from CSV ... has nothing to do with later processing the lines and printing those. You can write code that just takes an ArrayList, processes those and prints stuff. Which you can ... test on its own, as you can hardcode such lists in your code.
This is my assignment - Write a program that reads a file and removes all comma’s from it and writes it back out to a second file. It should print to the console window, at the end, the number of comma’s removed.
The program needs to:
Prompt the user for the name of the file to read.
Reads file
Write the non-comma characters to output.txt, including all spaces.
When done reading the input file, write the total number of comma’s removed to the console window.
For example, if the input file contains 3+,2 = 5m, 7%,6 =1 hello
Then the output.txt file should contain:
3+2=5m 7%6=1 hello
And the console window should print “Removed 3 commas”.
Right now I'm having trouble actually removing commas from my input file, I think I would write the line under my last if statment.
Tried figuring out how to remove commas from the input file
package pkg4.pkg4.assignment;
import java.util.Scanner;
import java.io.*;
/**
*
* #author bambo
*/
public class Assignment {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the inputfile?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
Scanner inputFile = new Scanner(f);
System.out.println("Please enter the output file");
String outputfile = keyboard.nextLine();
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(fw);
int lineNumber=0;
while(inputFile.hasNext());
lineNumber++;
int commacount = 0;
String line = inputFile.nextLine();
if (line.length () != 0)
commacount++;
for(int i=0; i< line.length(); i++)
{
if(line.charAt(i) == ',');
{
commacount++;
}
pw.println("removed " + commacount + "commas");
}
}
}
According to your requirement for program i am suggesting you to use java 8 classes.for simplicity.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) throws IOException {
String content = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
content = new String(Files.readAllBytes(Paths.get(inputfile)));
long total_numbers_of_char = content.chars().filter(num -> num == ',').count();
System.out.println("Please enter the output file");
content = content.replaceAll(",", "");
String outputfile = keyboard.nextLine();
Files.write(Paths.get(outputfile), content.getBytes());
System.out.println("removed " + total_numbers_of_char + " commas");
keyboard.close();
}
}
To print on console you should be using :
System.out.println("removed " + commacount + "commas");
To write the line in the output file without the commas :
pw.println(line.replaceAll(",",""));
I am attempting to create and write to a .txt file so that another program can open and read it. The problem is that the entered data is not being written to the file created. It is a blank .txt document.
import java.util.Scanner;
import java. io.*; //import class for file input.
public class inventoryStock
{
public static void main(String args[]) throws Exception
{
//Declarations
String[] itemName = new String [10];
double[] itemCost = new double [10];
double[] inStockNumber = new double [10];
int counter = 0;
//End declarations
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
do
{
System.out.print("Enter item name");
pw.println();
itemName[counter] = input.next();
System.out.print("Enter item cost");
pw.println();
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
pw.println();
inStockNumber[counter] = input.nextDouble();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);
} //End of main method
} //End of InventoryStock class.
It seems that you didn't really write what you want to file. You can try the code below.
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
Two recommendations to you.
Since the size 10 is everywhere in your code. You'd better extract it to a single variable for better maintainability.
Please follow the naming convention of java. For your case, the first letter of class name should be capitalized. Use InventoryStock instead of inventoryStock.
The entire code is like below, hope it will help. Thx.
import java.util.Scanner;
import java.io.*; //import class for file input.
public class InventoryStock {
public static void main(String args[]) throws Exception {
int size = 10;
// Declarations
String[] itemName = new String[size];
double[] itemCost = new double[size];
double[] inStockNumber = new double[size];
int counter = 0;
// End declarations
Scanner input = new Scanner(System.in);
// Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
{
do {
System.out.print("Enter item name");
itemName[counter] = input.next();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
counter += 1;
} while (counter < size);
fw.flush();
}
fw.close();
System.exit(0);
} // End of main method
} // End of InventoryStock class.
You'll have to actually tell PrintWriter to write to file or else it won't do anything even though you grab the user's input with input.next(). Try something like this:
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw, true);
do
{
System.out.print("Enter item name");
itemName[counter] = input.next();
pw.write(itemName[counter]);
pw.println();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
pw.write(String.valueOf(itemCost[counter]));
pw.println();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.write(String.valueOf(inStockNumber[counter]));
pw.println();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);
Firstly, this is my first post here. I've done some searching but can't seem to find anything that is applicable. Please link if you know where I should look!
I've got a txt file formatted as below saved to my desktop:
Isaac Newton 84 James
Clark Maxwell 48 Marie Curie 66
Aristotle 62
I'm wanting a scanner to run through the file breaking the data into 'name' and 'age', resulting in ...println(name + " " + age). I tried this with two while loops as below and Eclipse doesn't return any errors, it just lags right up and outputs nothing.
Literally just after I wrote this, Eclipse crashed entirely saying it had a heap error and has run out of memory.
I've since realized that the !scan.hasNextInt() doesn't really make logical sense... if I called a String token as a scan.nextInt() value it would error, so I'm unsure why it didn't.
Ultimately, any ideas on how to do what I want using scanners or ideas as to why the below code killed Eclipse would be awesome.
String fileName = "C:\\Users\\Username\\Desktop\\testing.txt";
File myFile = new File(fileName);
String name = "";
int age = 0;
Scanner scan = new Scanner(myFile);
while(scan.hasNext()){
while(!scan.hasNextInt()){
name = name + " " + scan.hasNext();
System.out.print(name + " ");
}
while(scan.hasNextInt()){
age = scan.nextInt();
System.out.println(age);
}
}
Try just use one while, and use if to verify if is int for age or is not int, which will be the name:
while (scan.hasNext()) {
if (!scan.hasNextInt()) {
name += scan.next() + " ";
} else {
System.out.print(name + " " + scan.nextInt() + " ");
name = "";
}
}
You don't need the two inner while loops, they can be replaced with if statements
if(scan.hasNextInt()){
age = scan.nextInt();
System.out.println(age);
}
else{
name = name + " " + scan.next();
System.out.println(name);
}
This solves your problem. What I did is import the entire thing and then do the formatting in memory rather than doing it when reading the line (especially since the line doesn't contain all the data we need).
public static void main(String[] args) throws IOException {
String fileName = "/path/to/file.txt";
byte[] encoded = Files.readAllBytes(Paths.get(fileName));
String fileContents = new String(encoded);
String[] contents = fileContents.split("\\s");
for (String element : contents) {
if (!element.isEmpty()) {
if (!isNumeric(element)) {
System.out.printf(element + " ");
} else {
System.out.println(element);
}
}
}
}
private static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Assuming your data file consists of pairs of
name age
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
String fileName = "test.txt";
File myFile = new File(fileName);
String name = "";
int age = 0;
Scanner scan = new Scanner(myFile);
scan.useDelimiter(" ");
while (scan.hasNext())
{
if (scan.hasNext())
{
name = scan.next();
System.out.print(name + " ");
}
if (scan.hasNextInt())
{
age = scan.nextInt();
System.out.println(age);
}
}
// TODO code application logic here
}
I am attempting to learn how to prompt users to enter a file name, rather than predefining it, so that Java can go through with the Scanner and read through it. I have written a program that does what I need it to do, but only when the file in question is predefined.
I have looked around the site for duplicate questions, and found a few, but the scope in which it was asked was a bit more advanced than where I am. Can anyone offer me a bit of guidance on how to prompt a user to enter the file he/she wants, as opposed to predefining it (as code below is set to).
Note - This was written assuming the files read in had integers < 0 and > 0, hence why the min/max functions were done in the way they were...simply trying to teach myself one step at a time.
import java.io.*;
import java.util.*;
public class ProcessNumbers {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("inputdata.txt"));
int max = 0;
int min = 0;
int sum = 0;
int count = 0;
double average = 0;
System.out.println("Enter file name: "); //currently a println for ease of reading via Run
while (input.hasNext()) {
if (input.hasNextInt()) {
int number = input.nextInt();
sum += number;
count++;
average = (double) (sum) / count;
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
} else {
input.next();
}
}
System.out.println("Maximum = " + max);
System.out.println("Minimum = " + min);
System.out.println("Sum = " + sum);
System.out.println("Count = " + count);
System.out.println("average = " + average);
}
}
Try this:
System.out.println("Enter file name: ");
Scanner fileNameScanner = new Scanner( System.in );
String fileName = "";
if ( fileNameScanner .hasNext() ) {
fileName = fileNameScanner.next();
}
...
Using the fileName string, create a File object and use as per your requirements.
Easiest way would be to replace
new File("inputdata.txt")
with
new File(args[0])
This way the first command-line argument will be treated as a filename.
You can use Scanner to read a input from user (it doesn't only read from a File):
Scanner prompt = new Scanner(System.in);
System.out.print("Enter name of the file: ");
String name = prompt.next(); // enter "inputdata.txt"
Scanner input = new Scanner(new File(name));
// ...
Another approach would be to use the Console.
You substitute your scanner to read from a File returned from a new method:
Scanner input = new Scanner(getFileFromUser());
...
private static File getFileFromUser() {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String filePathname = c.readLine("Enter file pathname: ");
return new File(filePathname);
}
Also don't forget to close your scanner in the end of main method to avoid resource leak:
input.close();