This question already has answers here:
Java FileWriter with append mode
(4 answers)
Closed 2 years ago.
My program asks the user for their name and age. The username is their name and age plus a random character at the end of it. I want to store that username into a new text file but whenever I run the code it only writes one username at a time it doesn't include the one that I added before. Here is my code Please help me I am new.
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Userfile {
private static String name;
private static Scanner scanage;
private static Scanner scan;
public static void main(String[] args) throws IOException {
Random r = new Random();
int age;
String username;
char randomc = 2;
System.out.println("Please enter your name");
scan = new Scanner(System.in);
name = scan.nextLine();
System.out.println("Please enter your age");
scanage = new Scanner(System.in);
age = scanage.nextInt();
username = name.toLowerCase()+age;
String alphabet = "xy!&69£zHDErnABCabcFfGghIiJjKkLlMmNPp";
for (int i = 0; i < 1; i++) {
randomc = alphabet.charAt(r.nextInt(alphabet.length()));
String userId = username + randomc;
System.out.println("Your Username is " +userId);
}
FileWriter userid = new FileWriter("file path");
String userId = username + randomc;
userid.write("\n" + "Username: " + userId);
userid.close();
}
}
It's because you are overriding the file everytime.
Replace
FileWriter userid = new FileWriter("file path");
with
FileWriter userid = new FileWriter("file path", true);
If you want to write text to a file to which you've already written text before, you need to use the FileWriter(File file,boolean append) constructor:
FileWriter userid = new FileWriter("file path", true); //assuming "file path" is the actual path to the file
Besides that, your program only asks for input once, so you'll need to run it multiple times if you want to add multiple usernames. Or you could wrap what you've done in a loop to ask for input multiple times. And speaking of loops, the one loop you do have serves no real purpose as the statements it executes will run once, just like they would without a loop wrapping them.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
I am trying to create a .json file with with part of the filename coming from user input. However I keep getting the null value in the resulted filename: it is nullworkoom.json
where null should actually be a string coming from the user.
This is part of my code:
public class WorkRoomApp {
private String name;
//private static final String JSON_STORE = "./data/workroom.json";
private String JSON_STORE = "./data/" + name +"workroom.json";
private Scanner input;
private WorkRoom workRoom;
private JsonWriter jsonWriter;
private JsonReader jsonReader;
// Step 1
public WorkRoomApp() throws FileNotFoundException {
jsonWriter = new JsonWriter(JSON_STORE);
jsonReader = new JsonReader(JSON_STORE);
runWorkRoom(); // Step 2
}
// Step 2
private void runWorkRoom() {
boolean keepGoing = true;
String command = null;
input = new Scanner(System.in);
new_customer(); // Step 3
// Step 3
private void new_customer(){
System.out.println("Are you first time here?");
System.out.print(("Press 1 for yes, and 0 for no"));
input = new Scanner(System.in);
String yes_no;
yes_no = input.next();
if (yes_no == "1"){
create_new_json(); // step 4: because I pretend it is a new user
} else {
load_old_json();
}
}
private void create_new_json(){
System.out.println("Please enter your name without space");
String filename = null;
Scanner input = new Scanner(System.in);
filename = input.next();
this.name = filename; // so I thought the name field in the class
// has not been filled with the actual filename string now.
// so that the field JSON_STORE will not equal
// "./data/ABCworkroom.json"
// if the person enter ABC when asked "Please enter your name without space"
// but somehow I got the file nullworkroom.json
could someone tell me where my mistake could be in the code?
thank you
You need String.equals() in new_customer().
if (yes_no.equals("1"))
AND
You need to reset the JSON_STORE variable in create_new_json() like this:
this.name = filename;
JSON_STORE = "./data/" + name +"workroom.json";
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I am just learning HashMaps, and have just written my first program using them. For some reason, my check to determine if the inputs I've entered match up with the key and it's corresponding value always returns false. Can anyone tell me why that is?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) throws FileNotFoundException {
HashMap<String, String> userPass = new HashMap<String,String>();
HashMap<String, String> userFull = new HashMap<String, String>();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename to read from: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String fullname=inputFile.next()+" "+inputFile.next();
String username=inputFile.next();
String pass=inputFile.nextLine();
userPass.put(username, pass);
userFull.put(username, fullname);
}
inputFile.close();
//initialize variable for use after loop
String inputUsr = null;
//checks if key/value is found
boolean b=false;
int tries=1;
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.next();
System.out.print("\nPassword: ");
String inputPass=keyboard.next();
//if inputted password equals the password of the inputted username
if(inputPass.equals(userPass.get(inputUsr)))
b=true;
System.out.println("Either the username or password is incorrect. You have "+(3-tries)+" more attempts.");
tries++;
//program quits afte 3 tries
if(tries>3){
System.exit(0);
}
}
System.out.println("Welcome "+userFull.get(inputUsr));
}
}
There are two problems in the code inside your while loop as explained below:
(1) keyboard.next() is reading the console output text i.e., reading the printed text 'Password', so replace keyboard.next() with keyboard.nextLine();
(2) You did not handle the else condition for the tries count
You can refer at the below code with inline comments:
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.nextLine();
System.out.print("\nPassword: ");
String inputPass=keyboard.nextLine();
if(inputPass.equals(userPass.get(inputUsr))) {
b=true;
} else {
System.out.println("Either the username
or password is incorrect.
You have "+(3-tries)+" more attempts.");
tries++;
}
if(tries>3){
System.exit(0);
}
}
Please help, I need help on how to check for valid file names.
Here is part of my program...
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BookstoreInventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisherCode;
int totalQuant = 0;
double total = 0;
double totalValue = 0;
double sumOfPriceBook = 0;
//Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the file name from the user
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
//Open the file and set delimiters
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
}
}
So in my program I'm not sure how I would check to see if it's a valid file. For example, when the user enters "inventory" for the name of the file this will produce an error because the filename needs the .txt so the user should have entered "inventory.txt". So is there a way to adding the .txt to the name they entered? Or how do I check to see if a file is valid? Any help would be much appreciated.
You can try this:
if (!fileName.trim().toLowerCase().endsWith(".txt")) {
fileName+= ".txt";
}
Also, if you want to know if the file already exists or not:
File file = new File(filename);
// If file doesn't exist then close application...
if (!file.exists()) { System.exist(0); }
Hope this helps.
Try concatenating the user's input string by adding .txt. It should work.
try {
Scanner Majora = new Scanner(System.in);
System.out.println("what is your name?");
String Link = Majora.nextLine();
Scanner Lenk = new Scanner(System.in);
System.out.println("name of file?");
String Lunk = Lenk.nextLine();
if(Link.equalsIgnoreCase("!addcom");
File ocarina = new File("/Users/Unknown/Desktop/commands/" + Lunk + ".txt");
if (ocarina.exists()) {
ocarina.createNewFile();
}
FileWriter Majoras = new FileWriter(ocarina.getAbsoluteFile());
BufferedWriter Zelda = new BufferedWriter(Majoras);
Zelda.write(Link);
Zelda.close();
}
this is what i got so far :/
i need help on making it like if a certain word is used before the string you wanna save. save the string.
use startswith string method
if(Link.startsWith("!test"))
Zelda.write(Link);
substring will get you the string without !test which is 5 characters
Link = Link.substring(5);
this is what I'm trying to accomplish:
To write a program code such that when the user is allowed to enter an employee name from the given list of employees, the program will search for
the employee’s payroll data and then generate a report in the form of a .txt file,
whose file name is the employee’s first initial of his / her first name, followed by
their complete last name.
For example, if a report is generated for David Davies, the report will be located in the text file bearing the name DDavies.txt.
I've generated the list and I know how to pick the records I'm looking for. My problem is in creating a text file based on the user selection.
i.e How do I create a file DDavies.txt based on a user entering "David Davies" as 1 string.
Since names have different lengths, that means each string length is potentially different so I can't pick out the characters by index alone (or I don't know how).
Since each full name is in 1 string, I was thinking of writing a code to pick the very first character, then the following string after the break(space) BUT since it's all in 1 string and the length isn't fixed, I don't know how to accomplish that.
And Filewriter doesn't help matters cos' I have to specify the .txt extension to create a text file so I don't know how to generate the text file dynamically (having a specified title) without entering the name myself.
I was thinking of breaking the string apart into a first and last name basis but that will change the code fundamentally cos what I'm trying to accomplish is part of a larger program.
Please pardon my long intro, this is my first time so I hope I'm being specific enough.
Below is the code. (Please note that the report doesn't need to be displayed to the user, I just need it to be generated in that firstInitial-LastName format)Thanks guys!
//Report.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
public class Report {
String firstLine = "", secondLine = "", thirdLine = "";
double hours = 0, wages = 0;
DecimalFormat twoDecimal = new DecimalFormat("0.00");
static ArrayList<String> emps = new ArrayList<String>();
public Report() throws Exception {
//code here the logic to create a report for the user
FileReader file = new FileReader("payroll.txt");
BufferedReader buffer = new BufferedReader(file);
String line;
File check = new File("Overtime.txt");
FileWriter file1;
if (check.exists())
file1 = new FileWriter("Overtime.txt", true);
else
file1 = new FileWriter("Overtime.txt");
int count = 0;
while ((line = buffer.readLine()) != null) {
firstLine = line;
secondLine = buffer.readLine();
thirdLine = buffer.readLine();
double grosspay;
emps.add(line);
}//end while
buffer.close();
file1.close();
String empList = "";
Collections.sort(emps);
for (String str : emps) {
empList += str + "\n";
}
//Employee Listing (names)
JOptionPane.showMessageDialog(null, "Name:\n" + empList, "Employee Listing",
JOptionPane.PLAIN_MESSAGE);
//Get input then of desired employee name to save employee data to a file
String userInput = "";
while (userInput == null || userInput.equals("")) {
userInput = JOptionPane.showInputDialog("To get a payroll report, enter a name from the list");
}
if (empList.toLowerCase().contains(userInput.toLowerCase())) {
/*Upon retrieval of a CORRECT employee name that exists from the employee list,
open payroll.txt file, grab the employee data from the name given
and write the emp's data to a file given the employee’s first initial of his / her first name,
followed by their complete last name. **THIS IS WHERE I NEED HELP!!** */
/**Examples of random names to choose from, we have David Davies, Hyacinth Ho, Betty Boop etc**/
// "Report Generated" Notification
JOptionPane.showMessageDialog(null, "Report Generated.", "Result", JOptionPane.PLAIN_MESSAGE);
}
//Error Message
else {
JOptionPane.showMessageDialog(null, "Error!! Name invalid or doesn't exist, please try again.");
}
System.exit(0);
} //END of Public Report ()
public static void main(String[] args) throws Exception {
new Report();
} //End of Main
} // End of Report Class
After checking the user input is not null and is correct. Try this:
String userInput;
....
String filename;
String[] split = userInput.split(" ");
//get the first names first character and gets the last name
filename = userInput.charAt(0)+split[split.length-1];
I was thinking of writing a code to pick the very first character, then the following string after the break(space) BUT since it's all in 1 string and the length isn't fixed, I don't know how to accomplish that.
You can use yourString.charAt(0) to pick first character of String.
To pick string after fist space you can just find index of that first space using yourString.indexOf(' ') and substring after it.
Example
String someString = "Foo Bar";
System.out.println(someString.charAt(0)
+ someString.substring(someString.indexOf(' ') + 1))
//+1 because we don't want to include space in substring
output: FBar
You can also add ".txt" to result.
Perhaps this is what you want:
String name = "Doctor Who";
String[] name_parts = name.split(" ");
String filename = name_parts[0].charAt(0) + name_parts[1] + ".txt");
//filename = DWho.txt