Data entered is not writing to file - java

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);

Related

How can I question the user if they want to add a new record for a file?

My code simply asks the user to enter data for a file. I want to ask them every time if they want to add a new record before doing the process. Following is my code.
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Assign11 {
public static void main(String[] args) throws IOException{
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.nextLine();
System.out.println("Enter age.");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? "
+ "Type 'y' or 'n'.");
answer = keyboard.nextLine();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}
}
But the problem is that the question of adding a new record doesn't asked to user. So I was wondering what I did wrong and how I could fix it.
Here is quick fix for you. Please check following code.
You need to use next() in place of nextLine().
public static void main(String arg[]) {
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
try{
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.next();
System.out.println("Enter age.");
age = keyboard.nextInt();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? Type 'y' or 'n'.");
answer = keyboard.next();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}catch(IOException ex){
ex.printStackTrace();
}finally {
keyboard.close();
}
}
Hope this solution works.

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

appending to arrays won't work for my code, is there a bug somewhere or am I using it wrongly?

The program I'm working on is supposed to append values input from a scanner to their respective arrays from a different method. However when using the code exampleArray.push(value);, it gives me an errors saying :" Error: cannot find symbol, symbol: method push(java.lang.String)."
Am I doing anything wrong? Did I miss something?
Code for the class:
public class Agenda
{
public static String names[];
public static int days[];
public static int types[];
public static int diffs[];
public static int row;
public Agenda()
{
}
public void createA() throws IOException
{
FileWriter nFile = new FileWriter("CurrentAgenda.txt", false);
PrintWriter output = new PrintWriter(nFile, false);
output.println("Current Agenda");
//clear out data file
output.close();
nFile.close();
FileWriter dFile = new FileWriter("Data.txt", false);
PrintWriter clear = new PrintWriter(dFile, false);
clear.print("");
clear.close();
dFile.close();
create();
}
public static void create() throws IOException
{
System.out.println("Your file will be: CurrentAgenda.txt");
System.out.println("Input types:");
System.out.println("Name--> Characters: A-Z");
System.out.println("Type/Summative=(3), Formative=(2), Extra=(1)--> Integer: 1-3");
System.out.println("Days Until Deadline--> Integer: Any");
System.out.println("Difficulty/Easy=(1), Medium=(2), Hard=(3)--> Integer: 1-3");
System.out.println("Please input assignments:\n");
String again;
names = new String[100];
days = new int[100];
types = new int[100];
diffs = new int[100];
row=0;
do{
FileWriter data = new FileWriter("Data.txt", true); //putting data in table for append
PrintWriter append = new PrintWriter(data, true);
Scanner input = new Scanner(System.in);
System.out.println("Please input assignment name: ");
String name = input.nextLine();
names[row] = name;
append.print(name +",");
System.out.println("Please input the number of days until the due date: ");
int day = input.nextInt();
days[row] = day;
append.print(day + ",");
System.out.println("Please input assignment type:");
int type = input.nextInt();
types[row] = type;
append.print(type + ",");
System.out.println("Please input the assignment difficulty: ");
int diff = input.nextInt();
diffs[row] = diff;
append.println(diff);
append.close();
data.close();
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
again = input.next();
input.close();
row++;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work.add(new Items((names[count]),(days[count]),(types[count]),(diffs[count])));
}
Collections.sort(work, new Comp1());
FileWriter firstL = new FileWriter("CurrentAgenda.txt", true); //formats the Viewer file
PrintWriter paste = new PrintWriter(firstL, true);
paste.println("Do these Assignments in order:");
paste.close();
firstL.close();
System.out.println("Sorted Assignment Entries: ");
for(Items e:work)
{
FileWriter agenda = new FileWriter("CurrentAgenda.txt", true);
PrintWriter add = new PrintWriter(agenda, true);
add.println(e);
add.close();
agenda.close();
System.out.println(e);
}
}
public static void add() throws IOException
{
String again;
do{
FileWriter data = new FileWriter("Data.txt", true);
PrintWriter append = new PrintWriter(data, true);
Scanner input = new Scanner(System.in);
System.out.println("Please input assignment name: ");
String name = input.nextLine();
names.push(name);
append.print(name +",");
System.out.println("Please input the number of days until the due date: ");
int day = input.nextInt();
days.push(day);
append.print(day + ",");
System.out.println("Please input assignment type:");
int type = input.nextInt();
types.push(type);
append.print(type + ",");
System.out.println("Please input the assignment difficulty: ");
int diff = input.nextInt();
diffs.push(diff);
append.println(diff);
append.close();
data.close();
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
again = input.next();
++row;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work2 = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work2.add(new Items((names[count]),(days[count]),(types[count]),(diffs[count])));
}
Collections.sort(work2, new Comp1());
FileWriter firstL = new FileWriter("CurrentAgenda.txt", false);
PrintWriter paste = new PrintWriter(firstL, false);
paste.println("Current Agenda");
paste.println("Do these Assignments in order:");
paste.close();
firstL.close();
System.out.println("Sorted Assignment Entries: ");
for(Items e:work2)
{
FileWriter agenda = new FileWriter("CurrentAgenda.txt", true);
PrintWriter add = new PrintWriter(agenda, true);
add.println(e);
add.close();
agenda.close();
System.out.println(e);
}
}
There is not push method for java arrays. Instead, you must set the value by using the index at which you want to set it. For example, you could set the first spot of the names array to Rob by saying:names[0]="Rob"; You will have to know the index. For your situation, you can consider using a counter that starts at 0 and increments every time you save an assignment name.
Hope this helps!
You should not be using standard arrays. Your compiler is correct there is no push method for a standard array.
But there is a different array-like type you can use.
Try using an ArrayDeque (documentation here). It has the push method you're looking for.
You just have to remember that they get initialized a little differently than an array.
Instead of
String[] array = new String[50];
You use
ArrayDeque<String> array = new ArrayDeque<>(50);
The capacity argument for the constructor is optional. The size of an ArrayDeque can change, unlike a standard array.
You can then call your push(E) method just like you do in your code.
A push() method does not exist for arrays, if you want you can make a generic metod to push to your array something like:
<T> void push(T[] array, int index, T value) {
array[index] = value;
}

java programming, writing to text files

how do i make this code write to the text file height.txt? it creates it but it doesnt write to it.
and it also compiles and says data is written to the file but there isnt any data when i open the file why is that?
import java.io.*;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
public class readinguserinput {
public static String gender;
public static int motherHeight;
public static int fatherHeight;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
try
{
FileWriter fw = new FileWriter("height.txt");
PrintWriter pw = new PrintWriter(fw);
System.out.println ("Enter gender");
gender = keyboard.next();
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
keyboard.nextLine();
while (motherHeight < 0)
{
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
}
System.out.println ("Enter father Height");
fatherHeight = keyboard.nextInt();
while (fatherHeight < 0)
{ System.out.println ("Enter Father Height");
fatherHeight = keyboard.nextInt();
}
pw.close();
}catch (IOException e){
System.out.println("file not found");
}
System.out.println("data written to the file");}}
The code never writes anything to the file. Try pw.print() and pw.println().
Change:
System.out...
To:
pw.out...
You are currently writing output to the console, not your PrintWriter
Your program just prints what you tell it to print. In this case you told it to print 'data written to the file', but you didn't tell it to actually write anything to the file. Your program lied to you, on your instructions.
As stated before. You haven't actually written anything to your file.
Try this
import java.io.*;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
public class readinguserinput {
public static String gender;
public static int motherHeight;
public static int fatherHeight;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
try
{
FileWriter fw = new FileWriter("height.txt");
PrintWriter pw = new PrintWriter(fw);
System.out.println ("Enter gender");
gender = keyboard.next();
pw.println("Gender: " + gender); // ***************
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
pw.println("motherHeight: " + motherHeight); // ***************
keyboard.nextLine();
while (motherHeight < 0)
{
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
pw.println("motherHeight: " + motherHeight); // ***************
}
System.out.println ("Enter father Height");
fatherHeight = keyboard.nextInt();
pw.println("fatherHeight: " + fatherHeight); // ***************
while (fatherHeight < 0)
{ System.out.println ("Enter Father Height");
fatherHeight = keyboard.nextInt();
pw.println("fatherHeight: " + fatherHeight); // ***************
}
pw.close();
}catch (IOException e){
System.out.println("file not found");
}
System.out.println("data written to the file");}}
Sample program to write a text file,
String content = "This is the content to write into file";
File file = new File("/data/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(content);
bufferedWriter.close();
Refer: How to write text file in Java ...

Java program will not output to file

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);
}

Categories

Resources