writing files in java from user input - java

I'm trying to write a program which will take user input from a list of options then either:
write to a file
alter an existing file or
delete a file.
At the moment I'm stuck on just writing to the file from the user input. I have to use regex notation for each of the users input as seen in the snippet. Any help or guidance on what i could do will be highly appreciated, and yes there are a lot of errors right now. Thanks!
import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
private UserInput[] list;
class Input {
public static void main(String[] args) {
Scanner in = (System.in);
string Exit ="False";
System.out.println("person details");
System.out.println("");
System.out.println("Menu Options:");
System.out.println("1. Add new person");
System.out.println("2. Load person details ");
System.out.println("3. Delete person Entry");
System.out.print("Please select an option from 1-5\r\n");
int choice = in.nextLine();
if (choice == 1)
system.out.println("you want to add a new person deails.");
AddStudnet();
else if (choice == 2){
system.println("would you like to: ");
system.println("1. Load a specific entry");
system.println("2. Load ");
}
//Error checking the options
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int input = Integer.parseInt(br.readLine());
if(input < 0 || input > 5) {
System.out.println("You have entered an invalid selection, please try again\r\n");
} else if(input == 5) {
System.out.println("You have quit the program\r\n");
System.exit(1);
} else {
System.out.println("You have entered " + input + "\r\n");
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your input!\r\n");
System.exit(1);
}
}
}
//Scanner reader = new Scanner(System.in);{ // Reading from System.in
//System.out.println("Please enter your name: ");
//String n = reader.nextLine();
//}
// File file = new File("someFile.txt", True);
// FileWriter writer = new FileWriter(file);
// writer.write(reader);
// writer.close();
public static void addPerson(String args[]) throws IOException{
class input Per{
scanner in = new scanner (system.in);
system.out.print("Please enter you Name: ");
String name = in.nextLine()
final Pattern pattern = Pattern.compile("/^[a-z ,.'-]+$/i");
if (!pattern.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid String");
//String Name = regex ("Name")
//regex below for formatting
system.out.println("Please enter your Job title:");
//String CourseNum = regex ("JobTitle");
system.out.println("Please enter your Town:");
//String Town = regex("Town");
system.out.println("Please enter your postcocde:");
//String postcocde = regex("postcocde");
system.out.println("Please enter your street:");
//String Street = regex ("Street");
system.out.println("Please enter your House Number:");
//String HouseNum = regex ("HouseNum");
}
}
//public static void

Is not clear that you look for " i'm stuck on just writing to the file"
here exemple on how to create/write to a file
String export="/home/tata/test.txt";
if (!Files.exists(Paths.get(export)))
Files.createDirectory(Paths.get(export));
List<String> toWrite = new ArrayList();
toWrite.add("tata");
Files.write(Paths.get(export),toWrite);
look at java tm
https://docs.oracle.com/javase/tutorial/essential/io/file.html
lio

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.

How to get user input into this piece of code using scanner

I can get the program to add the preset values into the csv file but I want to adjust it so the user can enter the student ID Char(6) and the Student Mark (max 100) and also ensuring a minus mark cant be entered. How would I go about doing this?
public class Practicalassessment {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
System.out.println("Enter the Students ID: ");
scanner scanner = new scanner (System.in);
String ID = scanner.nextline();
System.out.println("You have selected Student" + ID);
System.out.println("Enter the Students Mark");
scanner scanner1 = new scanner(System.in);
String mark = scanner1.nextLine();
System.out.println("You Have Entered" + mark);
String filepath = ("marks.txt");
newMarks(ID,mark,filepath);
}
public static void newMarks (String ID, String mark, String filepath) throws IOException
{
try
{
FileWriter fw = new FileWriter(filepath,true);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter pw = new PrintWriter (bw);
pw.println(ID+","+mark);
pw.flush();
pw.close();
JOptionPane.showMessageDialog(null, "Records Updated Sucessfully");
}
catch (Exception E)
{
JOptionPane.showMessageDialog(null, "Records Unable to Be Updated");
}
}
}
Personally, I would keep to a single User Experience approach. If one is going to use JOptionPane to display a dialog, then one should collect information using a GUI as well.
I'd do (note that by convention Java variables are camelCase starting with a lower case):
String id = JOptionPane.showInputDialog("Enter Student's ID:");
// NOTE: need to check for null if canceled
// NOTE: should verify the input/format
The Error message noted in the comment is because the Java Scanner is with a capital letter. Not sure what that other thing is.
However, if one wants to use a Scanner, then instantiate only one:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Students ID: ");
String ID = scanner.nextline();
System.out.println("You have selected Student" + ID);
System.out.println("Enter the Students Mark");
String mark = scanner.nextLine();
System.out.println("You Have Entered" + mark);
...
Note that the same constraints of input validation exist as well with the Scanner input.

Reading a file with scanner

EDIT: I ADDED A NEW PART to catch fileexception error
This is a pincheck program. I'm supposed to create a txt file with the following lines:
peter, 1212
john, 1234
mary, 0000
I then have to write a java program to prompt user for the file path of the txt file then key in their name and pin number. I'm able to compile my code but I don’t get the expected result when I type in the correct name and pin.
import java.util.*;
import java.io.*;
public class PINCheck {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter file path: ");
String filepath = s.nextLine();
File passwordFile = new File(filepath);
System.out.print("Enter name: ");
String name = s.nextLine();
System.out.print("Enter password: ");
String password = s.nextLine();
try {
Scanner sc = new Scanner(passwordFile);
while (sc.hasNext()) {
if (password.matches(".*[a-zA-Z]+.*")) {
System.out.println("You have entered a non-numerical PIN!");
} else if (sc.hasNext(name) && sc.hasNext(password)) {
System.out.println("You have logged in successfully.");
}else {
System.out.println("Login Failed.");
}
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
This line : Scanner sc = new Scanner("passwordFile"); implies that Scanner will scan from the String specified in the constructor and not the actual file.
Use Scanner sc = new Scanner(passwordFile); instead.
A similar mistake for File passwordFile = new File("filepath");.
Use it like File passwordFile = new File(filepath);
In both cases, pass the variable, not the string.

My bufferedread only reading the first line of my file?

The bufferedreader I have used in my code seems to read only the first line of the code. Can some one help me solve the problem, I've been trying for a long time.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;
public class Task2Recipe {
private static String Ingredient;
private static String ServingNumber;
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'");
String choice = user_input.next();
user_input.nextLine();
if (choice.equals("write")) {
write();
}
if (choice.equals("read")) {
read();
}
}
public static void write() {
try {
FileWriter Task2Recipe = new FileWriter("P:/Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedWriter recipe = new BufferedWriter(Task2Recipe);
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the name of your recipe, if more than 1 word, seperate your words with a dash");
String RecipeName = user_input.next();
recipe.write("Name of recipe: " + RecipeName);
recipe.newLine();
System.out.println("Please enter the number of people your recipe serves");
ServingNumber = user_input.next();
recipe.write(ServingNumber);
recipe.newLine();
System.out.println("Please enter the name of your first ingredient, the quantity and units separated with a comma");
Ingredient = user_input.next();
recipe.write(Ingredient);
recipe.newLine();
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
String choice2 = user_input.next();
user_input.nextLine();
while (choice2.equals("yes")) {
System.out.println("Please enter the name of your ingredient, the quantity and units separated with a comma");
Ingredient = user_input.nextLine();
recipe.write(Ingredient);
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
choice2 = user_input.next();
user_input.nextLine();
}
recipe.close();
} catch (Exception e) {
System.out.println("A write error has occured");
}
}
public static void read() {
try {
Scanner user_input = new Scanner(System.in);
FileReader file = new FileReader("P:Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedReader buffer = new BufferedReader(file);
System.out.println("Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'");
String choice3 = user_input.next();
user_input.nextLine();
while (choice3.equals("yes")) {
String line;
System.out.println("Please enter the new serving number");
int NewServingNumber = user_input.nextInt();
int counter = 0;
while ((line = buffer.readLine()) != null) {
counter++;
if (counter == 2) {
}
if (counter > 3) {
String[] word = Ingredient.split(",");
int Quantity = Integer.parseInt(word[1]);
int ServingNumberInt = Integer.parseInt(ServingNumber);
int Multiplier = ServingNumberInt / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
System.out.println(line);
buffer.close();
}
} catch (Exception e) {
System.out.println("A read error has occured");
}
}
}
My input was:
applep - for the recipe name
10 - for serving number
apple,10,apples - for the ingredient, I only added 1 ingredient.
When I read and read my file and change the recipe servinging number, it doesn't not work and gives in an 'read error'. In addition, to test the problem, I printed the variable 'line' and it only seems to read the first line.
Thanks in advance!
You have two independent cases - one for reading and one for writing. If in one case, you assign values ​​to variables, it does not mean that in other case you can read them. Also the counter is not set correctly. Try this code -
while((line = buffer.readLine()) !=null) {
counter++;
if (counter == 3) {
//String[]word = Ingredient.split(",");
String[]word = line.split(",");
int Quantity = Integer.parseInt(word[1]);
//int ServingNumberInt = Integer.parseInt();
int Multiplier = NewServingNumber / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
it gives -
Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'
read
Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'
yes
Please enter the new serving number
10
Your new quantity is 10

I am trying to write into a file which already contains information

Sorry for the lengthy code below, my code is able to execute and run properly when user input option '5'. I have already get all the values from user input and there is no error, but it did not write to my file.
My file currently has data in it:
Anthony Ducan;anthony;a123;55 Peter Street;3321444;VISA;3213504011223
Barry Blake;barry;a999;456 George Street;23239876;VISA;435677779876
Claire Rerg;clare;c678;925 Edward Lane;67893344;MASTERCARD;223344556677
I am trying to store the exact same way as my textfile.
Is there something wrong with my coding at void writeLinesToFile() method or is it the void newCust() method?
Still puzzled that I have no errors but it is not writing to my file.
public MainPage1(){ //start of MainPage1()
System.out.println("=====================================================");
System.out.println("Kreg Hotel Booking System - Main Page");
System.out.println("=====================================================");
System.out.println("[1] General Information");
System.out.println("[2] Make Booking");
System.out.println("[3] Active Booking Summary");
System.out.println("[4] Existing Customer");
System.out.println("[5] New Customer");
System.out.println("[6] Check Booking Status");
System.out.println("[7] Promotions");
System.out.println("[8] Exit\n");
System.out.println("Note: You have to select option 2 & 3 before option 4 & 5\n");
System.out.println("Please enter your selection: ");
try{choice = input.nextInt();}//to try to see if user input integer
catch (java.util.InputMismatchException e){//to catch if user didnt input integer
System.out.println("Invalid Input");
return;
}
while(true){ //start of do-while loop
if(choice==4||choice==5)
{
if(roomInfo.isEmpty()==true || addOns.isEmpty()== true){
System.out.println("Please enter option 2 or 3 before option 4 or 5");
choice=input.nextInt();
}
else if(choice == 4){existingCustomers();}
else if(choice ==5){newCust();}
else new MainPage1();
}
switch(choice){
case 1:break;
case 2:break;
case 3:break;
case 4:break;
case 5:newCust();
break;
case 6:break;
case 7:break;
case 8:System.out.println("Thank you. See you again soon");//exit the menu
System.exit(0);break;
default:System.out.println("Please enter number between 1 to 8");//prompts the user if they didnt enter between 1 to 8
choice = input.nextInt();
break;
}
}//while(choice!=1 || choice !=2 || choice!=3 ||choice!=4); // end of do-while loop
}//end of MainPage1()
public static void main(String[] args){//start of main page
new MainPage1();//to call the constructor
}//end of mainpage
public void writeLinesToFile(String filename,String[] linesToWrite,boolean appendToFile){
PrintWriter pw = null;
try {
if (appendToFile) {
//If the file already exists, start writing at the end of it.
pw = new PrintWriter(new FileWriter(filename, true));
}
else {
pw = new PrintWriter(new FileWriter(filename));
//this is equal to:
//pw = new PrintWriter(new FileWriter(filename, false));
}
for (int i = 0; i < linesToWrite.length; i++) {
pw.println(linesToWrite[i]+";");
}
pw.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the PrintWriter
if (pw != null)
pw.close();
}
}
public void newCust(){
System.out.println("Welcome to Kreg Hotel Booking System");
System.out.println("==============================================");
System.out.println("Please enter your name: ");
n = input.nextLine();
n = input.nextLine();
System.out.println("Please enter your login username: ");
un = input.nextLine();
System.out.println("Please enter your login password: ");
pw = input.nextLine();
System.out.println("Please enter your address: ");
a = input.nextLine();
System.out.println("Please enter your contact: ");
con = input.nextLine();
System.out.println("Please enter your credit card type: ");
ct = input.nextLine();
System.out.println("Please enter your credit card number: ");
cn = input.nextLine();
MainPage1 util = new MainPage1();
util.writeLinesToFile("customerinfo.txt",new String[]{n,un,pw,a,con,ct,cn},true);
new MainPage1();
}
}//end of class
Have a look at File, BufferedWriter and FileWriter docs. You should be able to accomplish this with those two class. This code should get you started.
String content = "Add this everytime";
File file =new File("example.txt");
//if file does not exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(content);
bufferWritter.close();
System.out.println("Done");

Categories

Resources