Error searching for word in file - java

In a file of randomly generated passwords my goal is to ask for a password, check the 'codes.txt' file to see if it exists, say 'LOGIN COMPLETE' for 5 seconds, delete the password, then close the files. When I reach the while loop I nothing works the way I need it to. It has all kinds of different results in various situation, none of which I can understand. I haven't even figured out how to delete the stuff on the console after 5 seconds have passed printing 'LOGIN COMPLETE'. If anybody could help me right now I would really appreciate it. My code is located below.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File checkFile = new File("codes.txt");
File tempFile = new File("tempFile.txt");
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(checkFile);
FileWriter fw = new FileWriter(tempFile);
PrintWriter out = new PrintWriter(fw);
System.out.println("What is the password?");
String word = input.nextLine();
while(reader.hasNextLine()) {
String line = input.nextLine();
if(line.equals(word)){
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
checkFile.delete();
tempFile.renameTo(checkFile);
}
}
The main file is below.
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
I am a beginner at java so in order for me to understand the code please use simple beginners code.

In the end I've decided there isn't really a need to clear the console screen in Netbeans, and I'll just leave it as is. I do want to give the solution I got in the end for those confused on what I wanted and for anyone who might have the same problems as I did.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
//Makes 50 random passwords(ten characters using letters and numbers)
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
//prints passwords for 10 seconds
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
//asks for password and if it's correct then states LOGIN COMPLETE and then adds exceptions to a temporary file then readds to main file then closes
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File file = new File("codes.txt");
FileWriter fw = new FileWriter(new File("code.txt"));
PrintWriter out = new PrintWriter(fw);
Scanner reader = new Scanner(file);
Scanner input = new Scanner(System.in);
System.out.println("Enter a password");
String word = input.nextLine();
//prints each line in the file
while (reader.hasNextLine()) {
String line = reader.nextLine();
if (line.equals(word)) {
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
File file2 = new File("code.txt");
Scanner reader2 = new Scanner(file2);
FileWriter fw2 = new FileWriter(new File("codes.txt"));
PrintWriter out2 = new PrintWriter(fw2);
while (reader2.hasNextLine()) {
String line = reader2.nextLine();
out2.println(line);
}
file2.delete();
fw2.close();
System.exit(0);
}
}
Main File Below:
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}

Related

reading and writing files into java

I have to create a file named Lab13.txt. In the file I have 10 numbers. I import the 10 numbers and have to Multiply all the numbers from Lab13.txt by 10 and save all the new numbers a new file named Lab13_scale.txt. so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. Here is what
I have:
import java.io.*;
import java.util.Scanner;
public class lab13 {
public static void main(String[] args) throws IOException{
File temp = new File("Lab13.txt");
Scanner file= new Scanner(temp);
PrintWriter writer = new PrintWriter("Lab13_scale.txt", "UTF-8");
writer.println("");
writer.close();
}
}
How do I multiply the numbers by 10 and export it to the new file?
This code is simple as this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("Lab13.txt"));
PrintWriter print = new PrintWriter(new File("Lab13_scale.txt"));
while(scan.hasNext()){
print.write(10 * scan.nextInt()+"\n");
}
print.close();
scan.close();
}
}
If the numbers are separated by spaces, use
file.nextInt();
Full Code:
int[] nums = new int[10];
for(int i = 0; i < 10; i++){
nums[i] = file.nextInt();
nums[i] *= 10;
}
after writer.println("");
for(int i = 0; i < 10; i++){
writer.println(nums[i]);
}
I'll give you a different approach. I have wrote this from memory, let me know if you have any errors. I assumed the numbers are one on each line.
public static void main(String[] args)
{
String toWrite = "";
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader("Lab13.txt"));
while((line = reader.readLine())!=null){
int x = Integer.parseInt(line);
toWrite += (x*10) + "\n";
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
}catch(Exception e){}
}

Reading from a file using ArrayList in Java

I have an assignment that ask me to read from a file, us an ArrayList to organize and declare the numbers, and then calculate the average of those numbers and print them in a new file. I know that I need 3 parts for this which would be the Reader, Writer and the Array List but i get an error when compiling when I try to read from the scaner. Can someone help with how to read from the file with the ArrayList and likewise, how to write into a new file.
import java.util.ArrayList;
import java.util.Collections;
import java.io.*; //Replaces the scanner
import java.io.BufferedReader;
import java.util.Scanner;
import java.io.FileReader; // Used by the BufferedReader import java.util.Scanner;
import java.io.FileNotFoundException; //
import java.io.IOException; //
class SD9 {
public static void main( String[] args ) {
try{
FileReader Fr = new FileReader( "Patriots.txt" );
// the file reader bridges the program and the .txt file together.
BufferedReader Br = new BufferedReader( Fr );
String line = Br.readLine();
// BufferredReaders can only read one line at a time.
FileWriter fw = new FileWriter( "PatriotsStat.txt" );
BufferedWriter bw = new BufferedWriter( fw );
while( line != null ) {
//BufferredReaders return null once they've reached the end of the file.
ArrayList<Double> Patriots = new ArrayList<Double>();
for(int i = 0; i < 23; ++i ) {
Patriots.add( scan.nextDouble() );
}
/* String Line1 = "2014 PreSeason:";
bw.write( " " );
bw.newLine();
/*String Line3 = " FinalAvg: " + finalAvg;
bw.write( Line3 );
bw.newLine();*/
}
bw.close();
}catch( FileNotFoundException F ) {
//.....
} catch( IOException I ) {
}
}
}
This should work:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
class SD9 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("Patriots.txt"));
PrintWriter writer = new PrintWriter(new File("PatriotsStat.txt"));
ArrayList<Double> Patriots = new ArrayList<Double>();
double sum = 0;
while (scanner.hasNext()) {
double num = scanner.nextDouble();
sum += num;
Patriots.add(num);
}
scanner.close();
for (int i = 0; i < Patriots.size(); i++) {
writer.write(Patriots.get(i)+"\n");
}
double average = sum / Patriots.size();
writer.write("Average : "+average);
writer.close();
}
}
I believe this will help.
File fr = new File("Patriots.txt");
Scanner sc = new Scanner(fr);
ArrayList<Double> patriots = new ArrayList<Double>();
while(sc.hasNextDouble()){
patriots.add(sc.nextDouble);
}
sc.close();
The code is failing to compile because your code does not follow the correct Java syntax for a try...catch block
In Java, a try...catch block follows the following form:
try {
// do something...
} catch (Exception e) {
// handle the exception...
}
In your code, you will see that you have code in between your try block and your catch block:
The bw.close() line is the culprit.
try {
// code
}
bw.close();
} catch( FileNotFoundException F ) {
//.....
} catch( IOException I ) {
}
Assuming you are doing this in an IDE (NetBeans, Eclipse, etc.), this relevant information can be found in the 'Build Output' window

Bidimensional array input

I have a homework were the user have to input 10 word inside an array, but i cant find a way to do that
like for example if the user input this words:
abigail
wilbert
steve
android
lucky
hello
help
htc
matrix
kim
the output should be when i print the array
abigail
wilbert
steve
android
lucky
hello
help
htc
matrix
kim
this my program
import java.io.*;
class example
{
public static void main(String[] args) throws IOException
{
matrix obj=new matrix();
obj.practice();
}
}
class matrix
{
void practice() throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
char A[][]=new char[10][10];
int r,c,i,j;
String x;
char b;
for(r=0;r<10;r++)
{
System.out.println("Enter the "+(r+1)+" word");
x=br.readLine();
for(c=0;c<x.length();c++)
{
A[r][c]=x.charAt(c);
}
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
System.out.print(A[i][j]);
}
} System.out.print("\n");
}
}
I'm not sure why your are using a multi-dimensional array. Here is a solution that will work for you that demonstrates some OO concepts.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
public class StringArrayOfWords {
//instance variables
private ArrayList<String> lines = new ArrayList<>();
private static StringArrayOfWords arr = new StringArrayOfWords();//declare object
public static void main(String[] args) throws Exception {
String [] printArray = arr.readFile();//use an array to hold contents of arr.readFile for easy printing
System.out.println(Arrays.toString(printArray));//Arrays.toString will print the contents of an Array
}
//method to read a file and call on object
public String [] readFile() throws Exception{
//display a gui window to choose a file to read in
JOptionPane.showMessageDialog(null, "Please choose a question file");
JFileChooser input = new JFileChooser();
int a = input.showOpenDialog(null);
String file = "";
if (a == JFileChooser.APPROVE_OPTION) {
File selectedFile = input.getSelectedFile();
file = selectedFile.getPath();
}
//use file input to read in line one at a time
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
//convert ArrayList to array
String[] arr = lines.toArray(new String[lines.size()]);
return arr;
}
}

Computing a text file

I am new to programming and for my class we were given an assignment where in java eclipse, we had to write a program that selects a text file(notepad) which has four numbers and computes it's average. We are required to use different methods and I am stuck, I researched everywhere and could not find anything, this is as far as I got and I don't know if I am at all close, the "getTheAverage" method is my issue.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week04 {
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is; ");
}
public static String getTheFileName(){
String theFile;
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
return theFile = jfc.getSelectedFile().getAbsolutePath();
}
public static double getTheAverage(String s) throws IOException{
double theAverage = 0;
FileReader fr = new FileReader(s);
BufferedReader br = new BufferedReader(fr);
String aLine;
while ( (aLine = br.readLine()) != null) {
theAverage = Double.parseDouble(s);
}
return theAverage;
}
public static void displayTheResult(double x, String s){
JOptionPane.showMessageDialog(null,s + x);
}
}
Try using a Scanner object instead. It seems like you are making this more difficult than it has to be.
// Get file name from user.
Scanner scnr = new Scanner(System.in);
System.out
.println("Please enter the name of the file containing numbers to use?");
String fileName = scnr.next();
scnr.close();
// Retrieve File the user entered
// Create File object
File file = new File(fileName);
try {
// Create new scanner object and pass it the file object from above.
Scanner fileScnr = new Scanner(file);
//Create values to keep track of numbers being read in
int total = 0;
int totalNumbers = 0;
// Loop through read in file and average values.
while (fileScnr.hasNext()) {
total += fileScnr.nextInt();
totalNumbers++;
}
//Average numbers
int average = total/totalNumbers;
// Close scanner.
fileScnr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
// Quit Program if file input is bad.
System.exit(0);
}
Assuming that "average" indicates the arithmetic mean, you need to sum all the values parsed and then divide by the number of values you found. There are at least 4 problems with your code in this regard:
Double.parseDouble() is reading from the uninitialized variable s, instead of the value of the line you just read (which is in aLine)
You are not summing the values found
You are not keeping a tally of the NUMBER of values found
You are not dividing the sum by the tally
Based on your code, here's an example of how you might have done it.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Week04 {
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is; ");
}
public static String getTheFileName() {
String theFile;
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
return theFile = jfc.getSelectedFile().getAbsolutePath();
}
public static double getTheAverage(String s) throws IOException {
double value = 0, numValues = 0;
FileReader fr = new FileReader(s);
BufferedReader br = new BufferedReader(fr);
String aLine;
while ( (aLine = br.readLine()) != null) {
if (aLine.equals("")) continue;
value += Double.parseDouble(aLine);
numValues++;
}
if (numValues > 1) {
return value/numValues;
} else {
return value;
}
}
public static void displayTheResult(double x, String s){
JOptionPane.showMessageDialog(null,s + x);
}
}

Reading numbers from a text file into an ArrayList in Java

Can anyone show me a basic guideline for how to do this sort of thing? Would you use an Array or an ArrayList, and why? Anything else I've found online is too complicated to understand for my level of experience with Java. The file is a simple text file with seven decimal values per line, and contains three lines. Here is what I have so far and am just testing it to see if I'm doing the ArrayList properly. It keeps printing an empty ArrayList that is just two brackets.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextDouble())
{
salesData.add(salesDataFile.nextDouble());
}
salesDataFile.close();
System.out.println(salesData);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
}
salesDataFile.close();
System.out.println(salesData);
}
}
Read lines from file, then for each file get doubles using Scanner.
And for per line basis, you can just create Lists for every line, like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
System.out.println(salesData);
}
salesDataFile.close();
}
}
As you are getting per line values inside first while() loop, you can do whatever with line.
// number of values in file
int totalNumValues = 0;
// total sum
double totalSum = 0;
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
// total values in this line
int numValuesInLine = 0;
// sum in this line
double sumLine = 0;
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
double value = scanner.nextDouble();
sumLine = sumLine + value;
numValuesInLine++;
totalNumValues++;
totalSum = totalSum + value;
}
scanner.close();
System.out.println(salesData);
}
I'd do something like this:
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<ArrayList< double > > salesData = new ArrayList<>();
while(salesDataFile.hasNextLine() )
{
String stringOfNumbers[] = salesDataFile.nextLine().split(",");
ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
for( int i = 0; i < stringOfNumbers.length; ++i )
aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
//... Perform your row calculations ...
salesData.add( aux );
}
salesDataFile.close();
System.out.println(salesData);
As #Justin Jasmann said, you have comma separated values, so technically they are more than just double values, why not read them as String and then parse them using Double.parseDouble(String s) after you have your comma separatad value by using string.split(","); on every line.
This is what you are looking for,
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FileRead {
public static void main(String args[])
{
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
List<Double> saleNumbers= new ArrayList<Double>();
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Add number from file to list
saleNumbers.add( parseDecimal(strLine));
}
//Close the input stream
in.close();
System.out.println(saleNumbers);
}catch (Exception e){
e.printStackTrace();
}
}
public static double parseDecimal(String input) throws NullPointerException, ParseException{
if(input == null){
throw new NullPointerException();
}
input = input.trim();
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
ParsePosition parsePosition = new ParsePosition(0);
Number number = numberFormat.parse(input, parsePosition);
if(parsePosition.getIndex() != input.length()){
throw new ParseException("Invalid input", parsePosition.getIndex());
}
return number.doubleValue();
}
}

Categories