How to remove duplicate integers in my code? - java

user input a number ,if i repeat same the number and write the number in my text file. how can i stop the duplication. ?
i create a text file and write numbers in my text file.. if i write same number repeatedly that was write in my file..please correct my code.. i want write a number only one time....
public class FileOp extends Thread {
volatile String s = "yes";
void create() throws InterruptedException, IOException {
String filename = "Numberfile.txt";
File file = new File(filename);
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
if (file.createNewFile()) {
System.out.println("\nFile '" + filename + "' has
been created.\n");
} else {
System.out.println("\nFile '" + filename + "'
already exists.\n");
}
}
void write() throws InterruptedException, IOException {
FileWriter fw = new FileWriter("Numberfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a number :");
int a = in.nextInt();
bw.write("" + a + "\n");
System.out.println("Succesfully added in
Numberfile");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
System.out.println("Do you want continue
(yes / no) ? ");
s = in.next();
}
while (s.equalsIgnoreCase("yes"));
bw.close();
}
}
i enter a number 2 and it write in my text file,and i enter the number 2 repeatedly .. its store in text file. i don't want that.. only one time it's write in text file,

You don't need set, just make a list of type Integer that contains the previous numbers added. Use list.add(number) to add and list.contains(number) to check if number already exists in the list before writing to file/adding to list.
declaring a list of type integer: List<Integer> numbers = new ArrayList<>();
Also go check out the Collections in java:
Class Collections
edit: set declaration: Set<Integer> set = new HashSet<>();

Related

How to select one row from multiple rows of strings and store the values separated by commars

I have a csv file thats converted each row into strings and i want a user to select a numbe 1- 5 and it would store what row the user entered.
The string that has been made from the csv file is below.
1,Mazda CX-9,7,Automatic ,Premium,150
2,VW Golf,5,Automatic ,Standard,59
3,Toyota Corolla,5,Automatic ,Premium,55
4,VW Tiguan,7,Automatic ,Premium,110
5,Ford Falcon,5,Manual,Standard,60
public static void carSelection() throws IOException{
String CSVFileName = "CarList.csv";
File file = new File(CSVFileName);
System.out.println("To make a booking:");
System.out.println(" Select the car number from the car list");
try {
//reads file
Scanner scanner = new Scanner(file);
//while the file has lines to read
while (scanner.hasNextLine()) {
// read the line to a string
String line = scanner.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Your question is not clear. But following code will ask user for a number and print the correspondig csv line.
public static void carSelection() throws IOException {
String CSVFileName = "CarList.csv";
System.out.println("To make a booking:");
System.out.println("Select the car number from the car list");
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
Stream<String> lines = Files.lines(Paths.get(CSVFileName));
int inputNr = Integer.parseInt(reader.readLine());
String line = lines.skip(inputNr - 1).findFirst().get();
System.out.println(line);
}

Replacing a string from text file in Java

I've got a text file like this: https://i.stack.imgur.com/nL0Z4.png
The first column represents the user ID and the last column represents balance. I want to iterate through the elements to find a specific user ID and then update their balance. I've managed to match the user ID and access the balance using the Scanner but I'm not sure how to update the balance in the text file with a new value. This is the code I've written so far: I tried to take the elements, modify the balances and put the updated values in an arraylist. Then put them into the text file using PrintWriter. But I keep getting an empty text file when I call this function.
File file = new File("UserInfo.txt");
Scanner sc = new Scanner(file);
ArrayList<String> items = new ArrayList<String>();
while(sc.hasNextLine()){
String info = sc.nextLine();
String data[] = info.split(" ");
if(String.valueOf(currentUser.getAccountNumber()).equals(data[0])){
data[3] = String.valueOf(currentUser.getBorrowBalance());
//Updating the balance in ArrayList
}else{
continue;
}
for(int i=0; i<data.length; i++){
items.add(data[i]);
}
}
PrintWriter pw = new PrintWriter(file);
for(int j=0; j<items.size(); j++) {
pw.printf("%s ", items.get(j));
if(j%3==0) pw.println(); //Going to new line after writing 4 elements to text file
}
pw.close();
sc.close();
I would highly reccomend to use Serialization for this. I am assumming you already have a Customer class with balance,id etc. With Serialization things are just as simple as getting the customer you want,updating his balance,and then writing in your file.For example:
customer = getCustomerById(selectedId);
customer.setBalance(newBalance);
customer.write();
And the write method would look like this
public void write(String filename) {
try {
File temp = new File(filename);
temp.createNewFile(); // create file if not present
FileOutputStream fileOut = new FileOutputStream(filename);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
More on Serialization here

How to sort user input to text files in Java?

I have a program taking user input and setting students in a text file, I want to sort these students in separate text files using the grade average
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class NewClass2
{
public static void main(String[] args)
{
String recOut = "";
String delimiter = ",";
Scanner input = new Scanner(System.in);
final int QUIT = 999;
NewClass1 student = new NewClass1();
try
{
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
while(student.getStudentId() != QUIT)
{
System.out.println("Enter Student Last Name: ");
student.setLastName(input.next());
System.out.println("Enter Student First Name: ");
student.setFirstName(input.next());
System.out.println("Enter Student Grade Point: ");
student.setGradePoint(input.nextDouble());
if(student.getGradePoint()>=3.6)
{
Path fileOut = Paths.get("HonorsStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<3.6 && student.getGradePoint()>=2.0)
{
Path fileOut = Paths.get("GoodStandingStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<2.0)
{
Path fileOut = Paths.get("ProbationStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter
+ student.getLastName() + delimiter
+ student.getFirstName() + delimiter
+ student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
}
}
catch(Exception e)
{
System.out.println("<<Something bad happened!>>");
System.out.println(e.getMessage());
}
}
}
I've been experimenting with if statements but that's not working because I can't close the writer correctly causing it to only take in one line then stopping.
How do I do this correctly?
The problem is not with how you're closing the file but with how your opening the file. Every time you're opening the file you are creating a new file and writing one line, then closing it, which is overwriting the old file that existed before. What you want to do is create the file if it does not exist, but if it does exist append one line.
Simply change
Files.newOutputStream(fileOut, CREATE)
to
Files.newOutputStream(fileOut, CREATE, APPEND)
Alternatively, you could open/close the files outside the loop or use “try with resources” too.
Since these are only three files, it is probably the easiest to open all three writers at once at the start and keep them open until the end.
If you don't want to close the writers manually (ans at least java 7 or 8 i think), you can use a try-with-resources statement.
Btw you probably don't need to wrap the OutputStream in a BufferedOutputStream, since you already use a buffered writer.
Instead of writing each time in file why don't you try to make three lists(one for every grade range you need) and when you have no more students then write them to separate files.
Something like this:
List<Student> honorsStudent = new ArrayList<Student>();
List<Student> goodStandingStudent = new ArrayList<Student>();
List<Student> probationStudent = new ArrayList<Student>();
// ....
if (student.getGrade() >= 3.6) {
honorsStudent.add(student);
} else if (student.getGrade() >= 2) {
goodStandingStudent.add(student);
}
else {
probationStudent.add(student);
}
//while loop end
//write your files

How do I add data to text file and not overwrite what I have in Java

This is my code so far but it overwrites what I have in the text file already. What I want is for it to add it to a new line in the text file.
import java.io.*;
import java.util.Scanner;
public class Login{
public static void main(String[] args) throws IOException {
Scanner s1,s2;
s1 = new Scanner(new FileInputStream("login.txt"));
s2 = new Scanner(System.in);
boolean loggedIn = false;
String name,pword,n,p;
System.out.println("Are you a new user? (Type y for yes or n for no)");
String nU = s2.next();
if (nU.equals("n"))
{
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
while(s1.hasNext()){
name=s1.next();
pword=s1.next();
if(n.equals(name) && p.equals(pword)){
System.out.println("You are logged in.");
loggedIn = true;
break;
}
}
if(!loggedIn)
System.out.println("Incorrect password or username.");
}
else if (nU.equals("y"))
{
Down here is where the problem with my code will be as this is where it is writing it to the file.
PrintWriter out = new PrintWriter("login.txt");
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
out.append(n);
out.append(p);
out.close();
System.out.println("Account has been created and you are logged in.");
}
else
System.out.println("Invalid response.");
It is advised to use chain of BufferedWriter and FileWriter, and the key point is FileWriter will append String to current file when use the one of its constructor that lets appaneding by adding true to last paramter like
new FileWriter("login.txt", true)
and when we surrounding it with BufferedWriter object in order to be more efficient if you are going to write in the file number of time, so it buffers the string in big chunk and write the big chunk into a file and clearly you can save a lot of time for writing into a file
Note :It is possible not to use BuffredWriter ,but it is advised because of better performance and ability to buffer the big chunk of Strings and write them once
Just change your
PrintWriter out = new PrintWriter("login.txt");
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));
Example:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch(IOException e) {
}
It is possible to solve this issue without using BufferedWriter, yet the performance will be low as I mentioned.
Example:
try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", true));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch (IOException e) {
}
Use FileWriter
FileWriter fw = new FileWriter(filename,true);
//the true will append the new data to the existing data
Something like this
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("login.txt", true)))
out.println(n);
out.println(p);
out.close();
Very simple example is this.
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File file = new File(workingDir+"/WebContent/Files/login.txt");
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
printWriter.println(workingDir);
printWriter.println("Good thing");
printWriter.close();
hope it helps.

FileNotFoundException occurs due to my outputStream method

Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.

Categories