The program I am writing needs to read 4 lines of data from a text file containing an ID, Name, Level, and Salary for an employee. It then needs to create a formatted email address and print all of this to standard output. The text file can contain an unknown number of employees, so a while loop must be used with the hasNext() method to confirm there is more data to read.
My program freezes (using Dr. Java) as soon as the while loop begins, and I cant figure out why.
Here is my code so far
public static void main(String[] args) throws IOException {
File file = new File("employeeInput.txt");
if (file.exists()) { //check if file exists
Scanner inputFile = new Scanner(file); //opens file
String companyName = inputFile.nextLine();
System.out.println(companyName);
System.out.println();
System.out.println("----------------------------");
while (inputFile.hasNext()); {
String studentID = inputFile.nextLine();
System.out.println(studentID);
String studentName = inputFile.nextLine();
System.out.println(studentName);
String employeeLevel = inputFile.nextLine();
System.out.println(employeeLevel);
double salary = inputFile.nextDouble();
System.out.println(salary);
}
inputFile.close();
}
else {
System.out.println("The file employeeInput.txt does not exist");
}
}
}
I understand this code is not complete and does everything the program needs to, but I do not get why it's freezing at the while loop..
Any help or advice would be appreciated. This is my first class ever in programming language, so go easy on me :)
Related
I'm trying to read the contents of a text file and print them. I cannot figure out why the content is not displayed when I run the program.
This is my code:
import java.io.*;
import java.util.Scanner;
public class ReadTxtfile{
public static void main (String [] args) throws IOException{
Scanner input = new Scanner(System.in);
//Open the file
File file = new File("chessfile.txt");
//Open files for reading
Scanner inputFile = new Scanner(file);
while(!file.exists()){
System.out.println("The file chessfile.txt is not found.");
System.exit(0);
}
//Read lines from the file
while(inputFile.hasNext());
//Read next
String piece = inputFile.nextLine();
String color = inputFile.nextLine();
String column = inputFile.nextLine();
String row = inputFile.nextLine();
//Display File
System.out.printf(piece, color, column, row);
//Close file
inputFile.close();
}
}//End of main
A few things first you dont want to loop while the file exists and then use system.exit if you really need to just use an if statement
if(!file.exists()){
System.out.println("The file chessfile.txt is not found.");
System.exit(0);
}
Second your going to want to use file.hasNextLine() instead of hasNext and also where are the curly braces for your loop this is what it should look like.
while(inputFile.hasNextLine()){
String piece = inputFile.nextLine();
String color = inputFile.nextLine();
String column = inputFile.nextLine();
String row = inputFile.nextLine();
}
Finnnaly i guess with printf your trying to display them neatly well you cant do that outside of the loop so instead of doing all that nonsense create a String array and store each of the lines in that as you get the different values. Assuming that your data is on seperate lines it should look somewhat like this.
ArrayList<String> peices = new ArrayList<String>();
while(inputFile.hasNextLine()){
String peice = "";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peices.add(peice);
}
And finnaly to display them on multiple lines you should use a simple enhanced loop.
for(String i : peices) {
System.out.println(i);
}
your while loop is not working. so next line data not coming in a string object.
and if you want getting all your text file data in one line try below loop.
String line ="";
while(scanner.hasNextLine())
line += scanner.nextLine();
System.out.printf(line );
I'm trying to read in a file and change some lines.
The instruction reads "invoking java Exercise12_11 John filename removes the string John from the specified file."
Here is the code I've written so far
import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {
public static void main(String[] args) throws Exception{
System.out.println("Enter a String and the file name.");
if(args.length != 2) {
System.out.println("Input invalid. Example: John filename");
System.exit(1);
}
//check if file exists, if it doesn't exit program
File file = new File(args[1]);
if(!file.exists()) {
System.out.println("The file " + args[1] + " does not exist");
System.exit(2);
}
/*okay so, I need to remove all instances of the string from the file.
* replacing with "" would technically remove the string
*/
try (//read in the file
Scanner in = new Scanner(file);) {
while(in.hasNext()) {
String newLine = in.nextLine();
newLine = newLine.replaceAll(args[0], "");
}
}
}
}
I don't quite know if I'm headed in the correct direction because I'm having some issue getting the command line to work with me. I only want to know if this is heading in the correct direction.
Is this actually changing the lines in the current file, or will I need different file to make alterations? Can I just wrap this in a PrintWriter to output?
Edit: Took out some unnecessary information to focus the question. Someone commented that the file wouldn't be getting edited. Does that mean I need to use PrintWriter. Can I just create a file to do so? Meaning I don't take a file from user?
Your code is only reading file and save lines into memory. You will need to store all modified contents and then re-write it back to the file.
Also, if you need to keep newline character \n to maintain format when re-write back to the file, make sure to include it.
There are many ways to solve this, and this is one of them. It's not perfect, but it works for your problem. You can get some ideas or directions out of it.
List<String> lines = new ArrayList<>();
try {
Scanner in = new Scanner(file);
while(in.hasNext()) {
String newLine = in.nextLine();
lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
}
in.close();
// save all new lines to input file
FileWriter fileWriter = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(fileWriter);
lines.forEach(printWriter::print);
printWriter.close();
} catch (IOException ioEx) {
System.err.println("Error: " + ioEx.getMessage());
}
I keep getting an error and I am unsure why. This is my code
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner inscan = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputfilename = inscan.nextLine();
File inputfile = new File(inputfilename);
Scanner in = new Scanner(inputfile);
String inputline = in.nextLine();
ArrayList<String> Names = new ArrayList<String>();
in.nextLine();
in.nextLine();
int total = 0;
while(in.hasNextLine()){
in.nextInt();
String Mname = in.next();
int Number = in.nextInt();
Names.add(Mname);
total += Number;
}
in.close();
for (String Mname : Names) {
System.out.println(Mname);
}
System.out.println("total number is " + total);
}
}
Prints:
hi
total number is 38
This is what the text file looks like.
test
test
1 mike 34
2 hi 38
I am first skipping the first two lines. Then getting all the names. Then printing the total number of all those names. It is now working with no errors but only prints one thing.
You're not pointing to the file properly. In order for your program to read names.txt, names.txt must be in the program's root directory. If you're running this from eclipse, that's the project's main folder. If you're running this from something like Dr. Java, this would be wherever your .java file is. Depending on what ide you're using to compile and run this, you can Google where the root directory of your project should be.
When you export this as a .jar file, the root directory becomes the directory from which the .jar is being run.
Edit: nevermind, disregard that, I see that the error is occurring on a different line of code. My bad :/
Edit 2: actually, do NOT disregard that, I just realized I was looking at the right line of code - the txt file's location is likely the problem (I think)
Part of your input routine is done in a loop. I'm guessing it is that way to facilitate the lines which (probably) all follow the same pattern (after the first two lines).
The problem is that your loop reads one line an "bits" of the second line. It is the "bits" of the second line being read that is problematic. Those bits prevent the beginning of the loop from reading where you probably want it to start reading.
I would recommend the loop reading just one line, or doing away with the loop and reading both lines before processing (depending on if the file has many or 2 lines of input).
Your code has three calls to in.nextLine() before it starts scanning line for tokens (ie int ID, name and number). This means it skips the two header lines, but also the first line of data.
I also noticed that you are not advancing to the next line once you have finished scanning tokens. So at the end of your while loop another call to in.nextLine() should get you in the right position for the next iteration.
This seems to work with my local testing:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner inscan = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputfilename = inscan.nextLine();
File inputfile = new File(inputfilename);
Scanner in = new Scanner(inputfile);
String inputline = in.nextLine();
ArrayList<String> Names = new ArrayList<String>();
in.nextLine();
int total = 0;
while(in.hasNextLine()){
in.nextInt();
String Mname = in.next();
int Number = in.nextInt();
Names.add(Mname);
total += Number;
in.nextLine();
}
in.close();
for (String Mname : Names) {
System.out.println(Mname);
}
System.out.println("total number is " + total);
}
}
I'm currently in an Introductory Java class at University and I'm having a bit of trouble. Last semester we started with Python and I became very acquainted with it and I would say I am proficient now in writing Python; yet Java is another story. Things are alot different. Anyway, Here is my current assignment: I need to write a class to search through a text document (passed as an argument) for a name that is inputted by the user and output whether or not the name is in the list. The first line of the text document is the amount of names in the list.
The text document:
14
Christian
Vincent
Joseph
Usman
Andrew
James
Ali
Narain
Chengjun
Marvin
Frank
Jason
Reza
David
And my code:
import java.util.*;
import java.io.*;
public class DbLookup{
public static void main(String[]args) throws IOException{
File inputDataFile = new File(args[0]);
Scanner stdin = new Scanner(System.in);
Scanner inFile = new Scanner(inputDataFile);
int length = inFile.nextInt();
String names[] = new String[length];
for(int i=0;i<length;i++){
names[i] = inFile.nextLine();
}
System.out.println("Please enter a name that you would like to search for: ");
while(stdin.hasNext()){
System.out.println("Please enter a name that you would like to search for: ");
String input = stdin.next();
for(int i = 0;i<length;i++){
if(input.equalsIgnoreCase(names[i])){
System.out.println("We found "+names[i]+" in our database!");
break;
}else{
continue;
}
}
}
}
}
I am just not getting the output I am expecting and I cannot figure out why.
Try this
You should trim() your values as they have extra spaces
if(input.trim().equalsIgnoreCase(names[i].trim()))
I have run your example it runs perfectly after using trim(), you have missed to trim()
Create a seperate scanner class to read line by line.You can use BufferedReader also.
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String str= scanner.nextLine();
if(str.contains(name)) {
// Found the input word
System.out.println("I found " +name+ " in file " +file.getName());
break;
}
}
If you use Java 8:
String[] names;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
names = stream.skip(1).toArray(size -> new String[size]);
} catch (IOException e) {
e.printStackTrace();
}
I was having trouble getting my program to read from a file "lexicon.txt"
My task was to have the program scan a user input and getting the word count for the program in return. Do you guys know what's going on in my code?
import java.io.*;
import java.util.Scanner;
public class searchFile {
public static void main (String args[]) throws IOException {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the file name (e.g: nonamefile.txt)");
String objective = reader.nextLine();
if (!(objective.equals("lexicon.txt"))) {
System.out.println("ERROR: Missing File");
}
else {
Scanner reader2 = new Scanner(System.in);
Scanner lexicon = new Scanner(new File("lexicon.txt"));
int wordCount = 0;
System.out.println("What word do you need to look up?");
String objective2 = reader2.nextLine();
while (lexicon.hasNext()) {
String word = lexicon.next();
if (word.equalsIgnoreCase(objective2)){
wordCount++;
}
}
System.out.println("Word count = " + wordCount);
}
} // end main method (String Args[])
} // end class searchFile
I ran your code on my computer. It is to help you. may be you are not doing same.
Please enter the file name (e.g: nonamefile.txt)
lexicon.txt
What word do you need to look up?
three
Word count = 3
The text I used in lexicon.txt was that :
one
two two
three three three
And it is working fine.
Remember, just copy paste is not like what you think it. there could be any character in clipboard when you copy that you cannot see, and pasting it also pastes these code too in your text file.
Scanner.next() looks for the next string delimited by word boundries.
Suppose there is a text that you copy pasted :
which is not visible in notepad :
So when you will search for "Hello", it will not be there.
You will have to search for instead, but you cannot write this easily.