Automatically Store String Data Externally For Later Use in Java - java

I have a basic User Input and System Output program using strings, and at the start of the program it asks for the user's name, which it saves as a string variable inside the program.
Scanner input = new Scanner(System.in);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
What I want is for the program to save all new names it receives in an external file (like a
text file), and whenever a name is input it checks to see if it has encountered that name before. I want to use an if / else statement to have it display a different output depending on whether or not it has seen that name before. How do I go about accomplishing this?
~
My apologies if this is a basic problem (or if it has been answered before), but I am relatively new to java and I wasn't able to find a solution. Thank you for your help! ^-^

I think this program may accomplished your requirement
public static void main(String as[]) throws Exception{
int i=0;
File f1=new File("D:\\Name.txt");
FileWriter fw=new FileWriter(f1,true);
Scanner input = new Scanner(System.in);
Scanner output=new Scanner(f1);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
if(!f1.exists()){
f1.createNewFile();
}
else{
while(output.hasNext()){
String na=output.next();
if(na.equals(name)){
++i;
break;
}
}
if(i==0)
fw.write(name+" ");
else{
System.out.println("Please enter some different name");
}
}
fw.close();
input.close();
output.close();
}

Related

Java Properties: How to update two keywords consecutively? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have a rudimentary piece of code that's meant to update a properties file. However, it seems that of the two possible keywords to update, only the second is updated by the user's input, as opposed to one after the other.
Here is the full code:
import java.io.*;
import java.util.Properties;
import java.util.Scanner;
public class UpdateProperty{
private static int choice;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream("Stats.properties");
Properties props = new Properties(); //creates a Properties object named prop
props.load(in); //loads in as value of prop
in.close(); //no idea
System.out.println("1- BlackBerryIzzie: " + props.getProperty("BlackBerryIzzie"));
System.out.println("2- GrapeFruitIzzie: " + props.getProperty("GrapeFruitIzzie"));
System.out.println("");
String blackAmount = props.getProperty("BlackBerryIzzie");
String grapeAmount = props.getProperty("GrapeFruitIzzie");
//System.out.println("Selling BlackBerry Izzie");
//blackAmount = itemSold(blackAmount);
System.out.println("Do you wish to update inventory? Type 2");
choice = sc.nextInt();
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
}
public static String itemSold(String s){
int i=Integer.parseInt(s);
i -= 1;
String ret=Integer.toString(i);
return ret;
}
}
The bit that seems to be malfunctioning:
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
This is meant to ask the user for blackberry amount, then update the BlackBerryIzzie keyword to that amount. Then, it is meant to do the same for grapefruit after blackberry is done. However, it skips blackberry and only asks for one scanner input and sets grapefruit to that.
Thanks for your time!
Don't mix nextLine and nextAnythingElse.
The solution is to set your scanner's delimiter to what you want. You want 'user presses enter' to be the delimiter, surely. So, tell scanner that. Run scanner.useDelimiter("\\R") immediately after making it. Then, to get 'an entire line', call .next(), if you want that line to be read as e.g. an int, call .nextInt(), etc. Don't call nextLine() for anything.
Explaining why mixing nextLine and nextAnythingElse is bad is a bit of a story - this SO answer explains part of it. Unfortunately the 1000-vote accepted answer is not the right solution (.useDelimiter("\\R") and then .next() to read a line is the right solution).

I can't manipulate name of the file that filewriter class creates

I am working on a simple program that takes input from user and then saves it with specific file name.
To be more precise:
public static Scanner in = new Scanner(System.in);
public static boolean quit = false;
public static String name;
public static FileWriter fw;
public static void main(String[] args) throws IOException {
System.out.print("File name: ");
name = in.nextLine();
fw = new FileWriter(name + ".txt", false);
System.out.println("Continue typing/type save to quit");
while(!quit) {
String word = in.nextLine();
if(word.equals("save")) {
fw.close();
quit = true;
}
else {
fw.write(word + "\n");
}
}
Program asks for file name.
User is typing words until he types "save" which saves the file
As you can see program ask user for file name at the beginning, before he starts to type. This is my problem. I want my program to ask the user for a file name at the end, after he typed all words. Unfortunately I cant do this because filewriter class creates the file when new object is created and name cannot be changed later.
I would like to know is there any solution to my problem or what kind of information should I look for.
You have two options:
Store all the user input in memory (in a List<String> for instance) and then write out the words after seeing the save keyword and getting the output filename from the user.
Open the output file as you are doing, but with a temporary name, and write the words as you read them. Upon seeing the save keyword, close the file, get the user's chosen filename, and then rename the temporary file to the user's choice.
Unless you need to process millions of words I'd go with option 1 for its simplicity.

Make one extra variable, program doesn't work

My task is to create a program which asks the user to enter a year, a first name and a last name. It then takes the last 2 numbers of the year, the whole last name, and the first letter of the first name and formats them into an email like this: 16SmithJ#mymail.co.uk. It places this email in a text file, which doesn't need to be printed. At the end, it asks if the user wishes to repeat the process again to make a new email.
This is my program, and it isn't fully complete yet. I have it working, but when I go to implement the part which repeats it if wanted, the email is no longer made in the file:
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter (new FileWriter("7D_mail.txt"));
boolean done = false;
while (done==false){
Scanner kb = new Scanner (System.in);
System.out.print ("Enter the year (e.g 2016) > ");
String year = kb.nextLine();
System.out.print ("Enter your first name > ");
String fname = kb.nextLine();
System.out.print ("Enter your last name > ");
String lname = kb.nextLine();
pw.write (year.substring(2)+lname+fname.charAt(0)+"#mymail.co.uk");
System.out.print ("*** Email created - another one? (Y/N)");
pw.close();
}
}
This program above works, but if I then add one line after the last one (String answer = kb.nextLine();), to make a new string for the answer, it no longer works.
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter (new FileWriter("7D_mail.txt"));
boolean done = false;
while (done==false){
Scanner kb = new Scanner (System.in);
System.out.print ("Enter the year (e.g 2016) > ");
String year = kb.nextLine();
System.out.print ("Enter your first name > ");
String fname = kb.nextLine();
System.out.print ("Enter your last name > ");
String lname = kb.nextLine();
pw.write (year.substring(2)+lname+fname.charAt(0)+"#mymail.co.uk");
System.out.print ("*** Email created - another one? (Y/N)");
String answer = kb.nextLine();
pw.close();
}
}
Any idea why this doesn't work? Thanks
I don't think it stopped working. You are unconditionally setting "done" to true after you take the user's repsonse, so it exits. Wrap "done = true" in a condition that checks for the value of "answer" to be "Y".
This is because the value 'done' is set to true after the first iteration of the loop and the loop never gets a chance to run again.
Besides, you close the PrintWriter after one iteration as well.
What I would suggest is this change:
if(answer.equals("N")){
done = true;
pw.close();
}
Try using System.out.println (); after printing the question to avoid exceptions (you can read the api here https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()).

Please help, FileNotFound Exception among other prblems

I'm utterly lost in Arrays and need help...Here is the end objective of this program....
In a file called AccountArray.java, write a client program (your main method) that reads from the file called customers.txt. Read the first number in the file and create an
array of Account objects, with that number of elements. Use a “for” loop to create an Account object for each line of information you read from the file and store that into an element of the array
Here's where I am at so far... my main concern is the FileNotFound Exception Error.... I have a file named customers.txt saved in the program folder but do I need to initialize it somehow or something?
Any other input regarding things I am doing wrong in this program would be greatly accepted, I'm just beginning to learn this stuff.
public class AccountArray {
/**
* #param args
*/
public static void main(String[] args) {
List<Account> accountsArray = new ArrayList <Account>();
String name, accountnumber, balance;
Scanner diskScanner = new Scanner(new File("customers.txt"));
Scanner scanner= new Scanner ("customers.txt");
scanner.useDelimiter(" ");
int objects= scanner.nextInt();
Account[] accounts=new Account[objects];
while (objects>0){
name = scanner.nextLine();
accountnumber = scanner.nextLine();
balance = scanner.nextLine();
for(int i = 1; i < objects; i++) {
accountsArray.add(new Account(i, name, accountnumber, balance));
}
objects=objects-1;
System.out.println(name+ " " + accountnumber + " " + balance +"\n"); }// just for debugging
}
}
sample of file :
4
John Anderson
4565413
250.00
Louise Carter
2323472
1250.45
Paul Johnson
7267881
942.81
Sarah Wilson
0982377
311.26
Well, first of all, you're using the wrong Scanner object:
Scanner diskScanner = new Scanner(new File("customers.txt")); // Scans through your file --Use this one
Scanner scanner= new Scanner ("customers.txt"); // Scans through the String "customers.txt" --Not helpful
To fix the FileNotFound Exception, you need to move the file customers.txt to the folder that is output by new File("customers.txt").getAbsoultePath(); as suggested by Freaky Thommi.
You will also run into a few other errors further down, but I'll let you figure those out on your own...
Is this run form eclipse. If yes you need to have this file under your project root folder. You can always find out the absolute path by using
new File("customers.txt").getAbsoultePath();
Print this to console and see if file is present at this location

Finding and replacing words in a text file with Scanner and Printwriter classes

I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.

Categories

Resources