read a file and determine a String - java

assume that my text file consist this:
NOT VOTED/1/gello/18
NOT VOTED/2/tara/24
arrangements is like status if user already voted or not/voter's number/name/age i divided the information line into array so it is like this
info[0]=status/info[1]=voters number/info[2]=name/info[3]=age
here is the function of my program:
read a file
let the user enter a voters number
if voters number matches info[1], proceed to step 3
while info[0] contains "VOTED" it will get an error message that that voter's number already voted and enter another voters number. if false it will proceed to the voting process
now info[0] will changed in to "VOTED"
here is my code:
File original = new File("C:\\voters.txt");//open the original file
File temporary = new File("C:\\tempvoters.txt");//create temporary file
BufferedReader infile = new BufferedReader(new FileReader(original));//read the file
PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));//write the data
vNum=JOptionPane.showInputDialog("Enter voters number: ");
String line=null;
String something="VOTED";
while((line=infile.readLine())!=null){
String [] info=line.split("/");
if(info[1].matches(vNum)){
while(info[0].matches(something)) {
JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
vNum=JOptionPane.showInputDialog("Enter voters number: ");
}
President();
Vice_President();
info[0]="VOTED";
all=info[0]+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
}
else{
outfile.println(line);
outfile.flush();
}
}
infile.close();
outfile.close();
original.delete();//delete the original file
temporary.renameTo(original);//rename the temporary file to original file
now this happens in the code that i made:
assume i enter 1 as voters number. and because the info[0] still contains "NOT VOTED", it will proceed to voting process and after that the element of info[0] now contains "VOTED". now after that process it will go back to main menu. now when i go back entering another voters number again, i tried entering 1 again to see if it will appear the error message. it did. so i entered the other voter's number again which is 2 and its info[0] still contains "NOT VOTED" BUT the error message will still appear!! i am really stuck with that process and i don't know what to do with that anymore because i am really clueless what is wrong. to think the functions in this method of my program are just the same with the other methods that i had. please please please help

while(info[0].matches(something))
It looks to me as though you're not breaking out of this while loop, since info[0] will always be true since variable "something" isn't being changed. What I would suggest is this:
{
JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
vNum=JOptionPane.showInputDialog("Enter voters number: ");
something = "NOT VOTED"; //This will break the loop
}

Related

How can I update contents of a text file

My assignment requires me to make a simple mathGame that generates random math problems. The program has to record the amount correct and the amount incorrect in a text file. It also has to update the statistics of an existing file instead of overwrite them.
This is how I am creating each file:
try {
writer = new FileWriter(userName + " Stats.txt", true);
outputfile = new PrintWriter (writer);
} catch (IOException e) {
}
Here is what is being written to the file:
public static void saveStats () {
outputfile.println();
outputfile.println("Correct Answers:"+ correct);
outputfile.println("Incorrect Answers:" + incorrect);
if (money > 0) {
outputfile.printf("Earnings: $%.2f", money);
outputfile.println();
}
else {
float moneyNegative = Math.abs(money);
outputfile.printf("Earnings: -$%.2f", moneyNegative);
outputfile.println();
}
outputfile.flush();
}
Here is a sample output of the text file after quitting the program:
Correct Answers:0
Incorrect Answers:1
Earnings: -$0.03
correct, incorrect, and money are all global variables and are initialized to 0. If I restart the program, my file will still exist but the values of Correct Answers, Incorrect Answers, and Earnings will be overwritten or a new entry to the file will be added. I just want to update it.
Here is all of my code: https://pastebin.com/1Cmg5Rt8
Have you tried getting the original text first, then writing it before you start writing what you need to?
Basically, you take the input from the file you have at the beginning
Scanner s = new Scanner(new File("FileName.txt"));
Then, you can loop through it and write to the file.
while(s.hasNextLine())
{
outputfile.println(s.nextLine());
}
After you have all of your previous file rewritten into the text, you can run the rest of your code and not have the information overwritten.
Also, instead of try-catch you can just throw IOException

Java help JOptionPane Madness

Really needing help on this have been trying for the past hour playing around and can't seem to get it. Have looked for the question online and getting a lot of solutions that are similar but not quite accomplishing the task would appreciate if someone could help me with this?
I am currently working on a dropBox API and am trying to create a JOptionPane that prompts the user to enter the code generated from dropBox API and the program to read the input and verify.. I have done the System.in with success but this is for a GUI so obviously not helpful.
System.out.println("Enter Your auth code in this prompt and hit enter and wait..");
String result = JOptionPane.showInputDialog(null, "Enter Code Here: ");
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
// Want JOptionPane to function the same way this ^ would behave
String info = JOptionPane.showInputDialog(code +" test " );
if(code == null){
System.exit(1);
return;
}
code = code.trim();
// This will fail if the user enters an invalid authorization code.
DbxAuthFinish authFinish = webAuth.finish(code);
String accessToken = authFinish.accessToken;
DbxClient client = new DbxClient(config, accessToken);
System.out.println("Linked account: " + client.getAccountInfo().displayName);
JOptionPane.showMessageDialog(null, "Hello..."+
client.getAccountInfo().displayName+
" And Welcome To Our Community!");
The String 'result' should hold the code they entered into the JOptionPane.
EDIT #1:
String result = JOptionPane.showInputDialog(null, "Enter your auth code here:"); //Prompt for the auth code.
//If they didn't enter anything into the JOptionPane then close the program with code 1.
if (result.isEmpty()) {
System.exit(1);
}
System.out.println(result.trim()); //For testing purposes print the trimmed auth code to console.
// [Omitted Code] //
Also, you don't need to call return after a System.exit(#) because the program will never get to that code anyway.

Deleting a specific line from a text file in Java

I am setting up a rank system where each member has a username and a rank. The program reads the username and rank from a text file and assigns it to the user.
One username and rank per line, such as:
user1 1
user2 2
user3 3
I have set up a program to add usernames and ranks to the text file, however I cannot seem to figure out how to delete a specific user from the list, such as if I wanted to only delete user 2 and his/her rank and leave the other two, however it is important that afterwards there isn't a blank line left behind.
Just for reference here is the code for how I write it to the file in the first place:
try {
BufferedWriter out = new BufferedWriter(new FileWriter("stafflist.txt", true));
for (int i = 0; i < 1; i++) {
out.newLine();
out.write(target.getUsername() + " " + target.getRights());
}
out.close();
SerializableFilesManager.savePlayer(target);
if (loggedIn) {
target.getPackets().sendGameMessage(modString + Utils.formatPlayerNameForDisplay(member.getUsername()) + "!", true);}
member.getPackets().sendGameMessage(successString + Utils.formatMemberNameForDisplay(target.getUsername()) + " to a Moderator.",true);
loggedIn = false;
} catch (IOException e) {
System.out.println("GiveMod - Can't find stafflist.txt");
}
return true;
You cannot delete data from the middle of a file (without leaving nulls). You need to rewrite at least what underneath it. A Simple solution would be loading everything in memory, remove that line and dump the collection again.
An alternative solution would be to:
Open a FileChannel from a RandomAccessFile
read the file line by line and keep the file-pointer of the line head. fileChannel.position();file.readLine(); load what comes after that into a collection. truncate the file from that position file.setLength(linePosition); and then dump the collection at the end of the file.
If your data doesn't fit in memory then you can use a temp file instead of a collection. Create a temp-file File.createTempFile(...), read the remaining data line by line and write to temp, truncate the original file ,read temp line by and write to original.
OR, guess what, use a database.
There seems to be an issue in your for loop. It is looping between 0 and 1, so I think the output you posted is incorrect. Anyway, if you want to only print out certain lines you can filter it as follows:
for (int i = 0; i < 1; i++) {
if(!target.getUsername().equals("user2")){
out.newLine();
out.write(target.getUsername() + " " + target.getRights());
}
}
Read the file into some Collection, remove desired users and rewrite the file using the modified Collection.

Trying to use Try catch in a while loop until the user answers correctly without entering invalid data(Java)

I am trying to create a program which asks the user to guess a number which is randomly generated and the loop exits when the input is correct. I am also trying to stop user from entering an invalid data and want the loop to repeat until user enters a valid data. The problem is when is type in an alphabet as an input, the program repeats. thank you for helping in advance. I am using eclipse kepler
Output:
Try guessing the number:
k
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
while(true){
try{
System.out.println("Try guessing the number: ");
guess=input.nextInt();
if(guess==sum){
System.out.println("You have guessed it correctly");
break;
}
}catch(InputMismatchException e){
System.out.println("You have entered invalid data. Please try again");
}
}
You don't have to use try/cathc structure. A while loop would be enough
while(true){
System.out.println("Try guessing the number: ");
guess=input.nextInt();
if(guess==sum){
System.out.println("You have guessed it correctly");
break;
}
if(!(guess instanceof Int)){
System.out.println("You have entered invalid data. Please try again");
}
}
This worked for me...
It fixes the while(true) issue and uses a simpler way to check for incorrect data that is easier to debug! Enjoy and good luck with your game!
String guessString="";
int guess = 0;
Scanner input = new Scanner(System.in);
int sum = 12;
//just used 12 as a placeholder, you'll have to connect your
//random number generator, as well as changing the default of
//guess=0 if 0 is in your range for the random number
while(sum!=guess){
System.out.println("Try guessing the number: ");
guessString=input.next();
try {
guess = Integer.parseInt(guessString);
} catch(Exception e) {
System.out.println("Invalid Data.");
guess=0;
}
}
System.out.println("You have guessed it correctly");

What is the best way to handle an exception for an invalid file?

I have a java class where a user provides a file path and if the path doesn't exist I ask them to try again. My professor says we should use an exception to handle this.
Here is a snippet of how I'm currently doing it:
public class SalesUtil {
public static void processSales() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sales file name: ");
String salesFile = keyboard.nextLine();
try {
Scanner scanFile = new Scanner(new File(salesFile));
//do stuff
}
} catch(FileNotFoundException fnfe) {
System.out.println("Invalid file name supplied, please try again.");
processSales();
}
}
}
Well in the do stuff section, I'm calculating values and printing data to the console. If I enter the correct file name correctly on the first try all the data is correct. If it is incorrect one or more times the data is not correct.
I imagine this is because of adding function calls on top of my initial stack and never 'getting out' of the initial stack while supplying subsequent stack calls until the correct file is supplied?
I'm still new to java and would appreciate some tips in understanding how to solve this using an exception.
The FileNotFoundException is the correct one to catch, however I gather that you're worried about the stacks building up? I tested reading back the file after multiple failed attempts and it was fine. The recursive call is at the end of the method so it is the last line of code and therefore the stacks shouldn't have any effect.
However, if you want, you could use a while loop instead of recursion to avoid stack buildup:
public static void processSales() {
Scanner scanFile = null;
Scanner keyboard = new Scanner(System.in);
while (scanFile == null) {
System.out.println("Enter sales file name: ");
String salesFile = keyboard.nextLine();
try {
scanFile = new Scanner(new File(salesFile));
while (scanFile.hasNextLine()) {
System.out.println(scanFile.nextLine());
}
} catch(FileNotFoundException fnfe) {
System.out.println("Invalid file name supplied, please try again.");
}
}
}
use the file.exist() method to check, if that what you want to do is to make sure it exist then this is the codes:
File sfile = new File(salesFile);
if (sfile.exists()) {
// ok, file exist do something.
...
}
On the other hand, when you say "invalid file" could be anything, if it is bad filename, then it is another animal (well, different exeception)...
To use try/catch for a readonly file then:
try {
FileInputStream sfile = new FileInputStream(salesFile);
...
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}

Categories

Resources