appending part of the filename using user input [duplicate] - java

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

Related

How to store multiple usernames in one textfile [duplicate]

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.

How do I store data read in from a CSV into a collection

I have been tasked with creating a game called Taboo. It consists of a main word and 3 banned words. The aim of the game is for the words to display on the screen and the user then has to describe the main word without using the word itself or the banned words.
I have so far been able to read in the data that I have stored in a CSV and have it so that when I choose to output BannedWords, it does so. The problem now, is that when it outputs either MainWord or BannedWord1, etc... it outputs the data for each record in the CSV.
Below is the data from my CSV (it is just a test with few records so that when it works I can introduce the rest).
Tree,Brown,Green,Nature
Lake,Blue,Water,Wet
Apple,Green,Fruit,Healthy
If I chose to output MainWord, which is the first word, it outputs like this:
Tree
Lake
Apple
I need to somehow store the data being read in from the CSV individually in a collection so that when I need to use them, they output properly and they in a such a way that I can display them later on in a GUI JLabel.
It might also be useful to note that I am using NetBeans so I am able to use any of the built in functions as well.
public class Card
{
private String sMainWord;
private String sBannedWord1;
private String sBannedWord2;
private String sBannedWord3;
public Card(String sMW, String sBW1, String sBW2,String sBW3)
{
sMainWord = sMW;
sBannedWord1 = sBW1;
sBannedWord2 = sBW2;
sBannedWord3 = sBW3;
}
public void setsMainWord(String sMW)
{
sMainWord = sMW;
}
public String getsMainWord()
{
return sMainWord;
}
public void setsBannedWord1(String sBW1)
{
sBannedWord1 = sBW1;
}
public String getsBannedWord1()
{
return sBannedWord1;
}
public void setsBannedWord2(String sBW2)
{
sBannedWord2 = sBW2;
}
public String getsBannedWord2()
{
return sBannedWord2;
}
public void setsBannedWord3(String sBW3)
{
sBannedWord3 = sBW3;
}
public String getsBannedWord3()
{
return sBannedWord3;
}
public static void main(String[] args) throws FileNotFoundException
{
String fileNameDefined = "/Users/student/NetBeansProjects/TabooGameComplete/CSData.csv";
File file = new File(fileNameDefined);
try
{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext() != false)
{
String TabooCardWords = inputStream.nextLine();
String[] information = TabooCardWords.split(",");
String MainWord = information[0];
String BannedWord1 = information[1];
String BannedWord2 = information[2];
String BannedWord3 = information[3];
Card TBC = new Card (MainWord, BannedWord1, BannedWord2, BannedWord3);
System.out.println("*" + BannedWord1 + "*");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You are executing the output statement in the loop that generates your Cards so that everytime a card is created, you are outputting its BannedWord1. As you are creating them all, one after another, they will all output, one after another.
i.e.
//For each line in file
while(inputStream.hasNext() != false)
{
//Create Card
//Output BannedWord1 used to create Card
}
If you want to output one element of one Card, you will need to keep the Card objects you create to be used outside the loop:-
Card[] cards = new Cards[3];
int i=0;
//For each line in file
while(inputStream.hasNext() != false)
{
//Create Card
cards[i++] = newlyCreatedCardObject; //Store card object for later
//Output BannedWord1 used to create Card
}
//Output BannedWord1 from the Card created from the second line
System.out.println(cards[1].getsBannedWord1());
Additional Point
By convention, java variables begin with lowercase letters and classes with uppercase, so this can be confusing
String TabooCardWords; //Should really be 'tabooCardWords'
...
String MainWord = information[0]; //-> 'mainWord'
String BannedWord1 = information[1]; //-> 'bannedWord1'
String BannedWord2 = information[2]; //-> 'bannedWord2'
String BannedWord3 = information[3]; //-> 'bannedWord3'

Read from txt file - Save when a line-break occurs

I want to read from .txt file, but I want to save each string when an empty line occurs, for instance:
All
Of
This
Is
One
String
But
Here
Is A
Second One
Every word from All to String will be saved as one String, while every word from But and forward will be saved as another. This is my current code:
public static String getFile(String namn) {
String userHomeFolder = System.getProperty("user.home");
String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
int counter = 0;
Scanner inFil = new Scanner(new File(filnamn));
while (inFil.hasNext()) {
String fråga = inFil.next();
question.add(fråga);
}
inFil.close();
}
What and how should I adjust it? Currently, it saves each line as a single String. Thanks in advance.
I assume your question is regarding java.
As you can see I changed return type of your method to List because returning single String doesn't make sense when splitting full text into multiple Strings.
I also don't know what question variable so I switched it with allParts being list of sentences separated by empty line(variable part).
public static List<String> getFile(String namn) throws FileNotFoundException {
String userHomeFolder = System.getProperty("user.home");
String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
int counter = 0;
// this list will keep all sentence
List<String> allParts = new ArrayList<String>(); s
Scanner inFil = new Scanner(new File(filnamn));
// part keeps single sentence temporarily
String part = "";
while (inFil.hasNextLine()) {
String fråga = inFil.nextLine(); //reads next line
if(!fråga.equals("")) { // if line is not empty then
part += " " + fråga; // add it to current sentence
} else { // else
allParts.add(part); // save current sentence
part = ""; // clear temporary sentence
}
}
inFil.close();
return allParts;
}

Input Mismatch Exception Error,

Program compiles and runs perfectly until I try to execute my load method in main. Program crashes and gives me an input mismatch exception at
part number = scan.nextInt(); ..... Anyone know why?
public static InventoryManager load(String fileName) throws IOException,ClassNotFoundException
{
Scanner fileScan = new Scanner (new File(fileName));
Scanner stringScan;
InventoryManager StockChart = new InventoryManager();
// Part variables
String record = "";
int partNumber=0;
String description="";
int qty=0;
double cost = 0.00;
while(fileScan.hasNext())
{
record = fileScan.nextLine();
stringScan = new Scanner (record);
stringScan.useDelimiter(" "); //allows for separation when reading
partNumber = stringScan.nextInt(); // scans part number
description = stringScan.next(); // scans description
qty = stringScan.nextInt(); // scans the qty on hand
cost = stringScan.nextDouble(); // scans the item cost
//create new part object for each line in file
StockChart.addStock(new Stock(partNumber,description, qty,cost));
}
return StockChart; // return new list back to InventoryClerk program
}
Text File is formatted as follows (disregard spaces in between):
1117[tab]1/2-13 FHN[tab]450[tab]6.11
1118[tab]1/2-13 FHN[tab]100[tab]0.23
1119[tab]1/2-13 FHN[tab]100[tab]4.11
A better way rather than using the stringScan Scanner object is to simply to use String.split on the record String
e.g.
while(fileScan.hasNext())
{
record = fileScan.nextLine();
String el[] = record.split (" ");
partNumber = Integer.parseInt (el[0]);
description = el[1];
// etc

Java Delete a line from txt after reding the file [duplicate]

This question already has answers here:
Java - delete line from text file by overwriting while reading it
(3 answers)
Closed 8 years ago.
I have this file
1007 book1 5 3
1004 book2 4 1
1003 book3 3 0
1002 book4 2 1
and I am trying to delete the book number 1004 from the file, but before that I let the user enter the number of the book that he wants to delete.
First check if the book exists in the file or not, if the book is exists I delete it if not show "the book does not exists".
Scanner kb = new Scanner(System.in);
FileInputStream book = new FileInputStream("input.txt");
Scanner infile = new Scanner(book);
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter pw = new PrintWriter(out);
boolean found = false;
System.out.print("Enter the bookID : ");
int bID = kb.nextInt();
while(infile.hasNext()){
int id = infile.nextInt();
String title = infile.next();
int quantity = infile.nextInt();
int bQuantity = infile.nextInt();
if(bID == id){
found = true;
}
if(found == true){
pw.printf("%8d\t%-30s\t%8d\t%8d", infile.nextInt(), infile.next(), infile.nextInt(), infile.nextInt());
infile.nextLine();
System.out.println("The book has been deleted");
break;
}
}
if(found == false)
System.out.print("Not found");
pw.close();
infile.close();
I am trying to print all the file with out the book I have deleted.
You will need a book class, like this:
public class Book {
private int series;
private String name;
private int intA;
private int intB;
public Book(int series,String name, int intA, int intB) {
this.series = series;
this.name = name;
this.intA = intA;
this.intB = intB;
}
....
.... (add other methods as needed, you will definitely need a
toString() method, and getIntA(), getIntB(), getSeriesNum(),
getName() etc.)
}
When you use scanner to read the file, read them into an arraylist of type Book. When user enter a number, use a for loop to find the Book that matches that number, and remove that book object from your arraylist.
Also, try to keep data in memory and not write files too often. Writing files to disks is very inefficient comparing with changing data in memory. Once user is done with all his/her operations, you can use a printwriter to write the data to your file.
To read your file into this array of objects, you can do this:
public static ArrayList<Book> readbooklist() {
ArrayList<Book> booklist = new ArrayList<Book>();
File file = new File("path/filename.fileextension");
try {
Scanner scnr = new Scanner(file);
while (scnr.hasNextLine()) {
String entry = scnr.nextLine();
String [] parts = entry.split("\t"); // Depends on how data was delimited
int series = Integer.parseInt(parts[0]);
int intA = Integer.parseInt(parts[2]);
int intB = Integer.parseInt(parts[3]);
Book single = new Book(series, parts[1], intA, intB);
booklist.add(single);
}
scnr.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}
return booklist;
}
Remember to import proper dependency at the beginning of your class. Wish it helps!
I'd recommend to use a Map to store each line as value and the Id as the key only once. That way you don't have to reopen the file and read it each time you want to remove or add an entry, all you have to do is remove it and add it to the map. Once you are done, you can overwrite the old file you have by the values stored in the map or just create a new temp file to hold the data, delete the old file and then rename the temp file with old file's name
Store all the lines you would like to save in a String and close the scanner. Create a printwriter, print the string to the file and close it.
Example code:
File file = new File("yourTextFile.txt");
Scanner in = new Scanner(file);
String saveThisToFile = "";
while (in.hasNext()) {
String temp = in.nextLine();
if (condition to be true if you whant to keep this line) {
saveThisToFile += temp + "\n";
}
}
in.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(saveThisToFile);
printWriter.close();

Categories

Resources