Java read from a text file - java

I'm trying to load some data to a GUI from a text file using a scanner. I have two sections in my text file: Clubs and Members. The code runs okay for the Clubs section. For example, if I have 4 clubs in my list, all of them will be displayed, but for the Members section doesn't matter how many members are in the list, only the first member will be displayed. Here is my code:
public void load (String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream("Clubs.txt");
Scanner scan = new Scanner(fileIn);
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.equals("Members")){
String firstName = scan.next();
String lastName = scan.next();
Pupil p1 = new Pupil( firstName, lastName);
pupils[nbrPupils] = p1;
nbrPupils ++;
}
else if(line.equals("Clubs")){
while (scan.hasNext()){
String club = scan.nextLine();
Club aNewClub = new Club(club);
clubs[nbrClubs] = aNewClub;
nbrClubs ++;
}
}

Hint: you're doing while (scan.hasNext()) in the Clubs section, but you don't do so in the Members section.

convert from while loop to if condition because you just want to check if there is a next line
else if (line.equals("Clubs")) {
if (scan.hasNext()) {/////here if you use while loop , it will loop until the file is finish
String club = scan.nextLine();
}

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new ReadFile().load("");
}
public void load (String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream("C:\\Clubs.txt");
Scanner scan = new Scanner(fileIn);
boolean membersfound =false;
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.equals("Members") || membersfound){
String firstName = scan.next();
String lastName = scan.next();
System.out.println("Member "+firstName +":"+ lastName);
}
else if(line.equals("Clubs") ){
while (scan.hasNext()){
String club = scan.nextLine();
if( club.equals("Members")){
membersfound = true;
break;
}
System.out.println("Clubname :" + club
);
}
}
}
}
}
I could have modified the whole program . But i wanted to show you your mistake
Sample clubs.txt file
Members
member1
member2
member3
Clubs
club1
club2
club3

When you do scan.nextLine() it moves the scanner to the line after the one you currently read in. So if you continue to do scan.next() the scanner will start from the end of your current line (in this case line) and reads what's after it.
See here it says:
"Advances this scanner past the current line and returns the input that was skipped"
What you can to is just call split() or substring() on line and extract the information you need.

Related

Output an array to the console from a .txt file

I am trying to copy the contents of a .txt file to an array and print it to the console.
The code requires a main method with two scanners (one to read input from the user, and the second to read the file), a method to make the array, and a method to print the array.
I have successfully managed to make an array and print it, but the output is not ideal. It is scattered and difficult to read. Can someone help me to improve my output so it reads more like a list?
Here is my code:
public class CutupSongCreator {
// Creates two Scanner objects; one reads input from console, the other scans a file
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in); // SCANNER ONE (reads input)
System.out.print("What is the input filename? ");
String filename = console.next();
File f = new File(filename);
while (!f.exists()) {
System.out.print("That file does not exist. Try again: ");
filename = console.next();
f = new File(filename);
}
Scanner input = new Scanner(f); // SCANNER TWO (reads file)
SongLine[] arr = makeArray(input);
printArray(arr);
// Sort by genre
// System.out.print("What genre are you looking for: ");
// String genretype = console.next();
// if (genretype == input.next()) {
// System.out.print("You can't just make up a genre. Try again: ");
// genretype = console.next();
// }
// listLinesByGenre(arr, genretype);
}
// Creates an array of SongLines from a set of lines
public static SongLine[] makeArray(Scanner reader) {
int total = reader.nextInt(); // First int = # of lines
SongLine[] arr = new SongLine[total]; // New array to hold the length of the file
for(int i = 0;i < total; i++) {
String genre = reader.next();
int lineNumber = reader.nextInt();
String words = reader.nextLine();
SongLine temp = new SongLine(genre, lineNumber, words);
arr[i] = temp;
}
reader.close();
return arr;
}
// Prints out the elements of an array
public static void printArray(SongLine[] songs) {
System.out.println(Arrays.toString(songs));
}
}
My code makes use of a constructor class, which I could post if needed, but I think I just do not understand how to read or use the constructor file. Below are the current and desired output. The desired shows the genre, lineNumber, and script, and I would like to print it looking as so.
Current Output
Desired Output
Thank you.

jump out of recursive function in a loop but let the loop continue

I am trying to read from a text file that have names and phone numbers that can also have other text files in it (including it self)
myBook.txt:
7
name1 123-456-7890
name2 098-765-4321
name3 135-792-4680
name4 246-801-3579
PHONEBOOK-FILE myBook2.txt
name5 147-025-8369
name6 150-263-7495
myBook2.txt:
1
Name7 000-222-3332
The first line is the number of items in the file, then it has PHONEBOOK-FILE to signify another file.
I cannot use arrays, I cannot change myBook.txt, I cannot use try / catch, and I have to use recursion
This is the code I have:
import java.util.*;
import java.io.*;
public class Phonebook
{
private boolean DEBUG = true;
private Scanner scan;
private Scanner input;
private File file;
private File holder;
private String query;
private boolean bottomOut;
private int nameCount;
private String fileNameHold;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file, 0));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName, int level)throws IOException
{
scan = new Scanner(fileName);
//Grabs item count fom begining of file
//if(!bottomOut)
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
debug("file: " +file);
debug("line: " + line);
debug("nameCount: " + nameCount);
if(line.toLowerCase().contains(query.toLowerCase()))
{
return line;
}
//Recursion is used to searth through linked files
else if(line.contains("PHONEBOOK-FILE"))
{
//System.out.println("Sanity Check");
holder = new File(line.replace("PHONEBOOK-FILE ", ""));
if(level < 2 || (level > 0 && bottomOut))
return doWork(query, holder, ++level);
else if(level >= 2 && !bottomOut)
bottomOut = true;
else
return "not found (REC)";
}
}
return "not found";
}
private void debug(String stuff)
{
if(DEBUG)
System.out.println("[[--DEBUG--]] " + stuff);
}
}
I assume the issue is in doWork but I could be wrong. What it is doing is it recurses through the file until it hits a specified bottom where if it hasn't found the name it should break out of the recursion and continue passed the PHONEBOOK-FILE line.
Currently if you search for a name passed that line if returns not found. It doesn't seem to be coming out of the recursion.
As you can probably tell I an not great with this.
Thanks for any help.
For each line in your file, you are going to compute a value. Either not found, or a line of your phonebook. If you get a line, you can break out of the loop. Either way, after the loop you return the value: either the line you got or not found;
What is trickier is how you compute a line which references another phonebook, the answer is that you just call your method with that phonebook. That's the recursion part.
import java.util.*;
import java.io.*;
public class Phonebook
{
private Scanner input;
private File file;
private String query;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName)throws IOException
{
Scanner scan = new Scanner(fileName);
int nameCount;
File recurFile;
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
String value = "Not found";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
// if the line is a file, then the value of that line
// is the result to your function applied to that new file
if(line.contains("PHONEBOOK-FILE")) {
recurFile = new File(line.replace("PHONEBOOK-FILE ", ""));
line = doWork(query, holder, ++level);
}
// the file will either return Not found or
// a line corresponding to your query
if(line.toLowerCase().contains(query.toLowerCase()))
{
// Your line is correct. The function doesn't care where it comes from
value = line;
break;
}
}
return value;
}
}

java find a specific line in a file based on the first word

I have a file that I am importing and what I want do is ask for the user's input and use that as the basis for finding the right line to examine. I have it set up like this:
public class ReadLines {
public static void main(String[] args) throws FileNotFoundException
{
File fileNames = new File("file.txt");
Scanner scnr = new Scanner(fileNames);
Scanner in = new Scanner(System.in);
int count = 0;
int lineNumber = 1;
System.out.print("Please enter a name to look up: ");
String newName = in.next();
while(scnr.hasNextLine()){
if(scnr.equals(newName))
{
String line = scnr.nextLine();
System.out.print(line);
}
}
}
Right now, I am just trying to get it to print out to see that I have captured it, but that's not working. Does anyone have any ideas? Also, if it matters, I can't use try and catch or arrays.
Thanks a lot!
You need to cache the line in a local variable so you can print it out later. Something like this should do the trick:
while(scnr.hasNextLine()){
String temp = scnr.nextLine(); //Cache variable
if (temp.startsWith(newName)){ //Check if it matches
System.out.println(temp); //Print if match
}
}
Hope this helps!
I'd do something in the lines of:
Scanner in = new Scanner(System.in);
System.out.print("Please enter a name to look up: ");
String name = in.next();
List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();
if (firstResult.isPresent) {
System.out.print("Line: " + firstResult.get());
} else {
System.out.print("Nothing found");
}

Getting Scanner from your Constructor to a method within the class?

Note: This is an assignment, and I am asking to be pushed in the right direction, this is also more of a question about technique rather than logic.
So I have this class called AnimalHospital, and in the Constructor takes a filename String as a parameter:
public AnimalHospital(String inputFile) throws FileNotFoundException {
// this is required
In the constructor, I read in a file that I have placed through my main, and the constructor should be able to read this file in. My issue is that I need to use the variable from the constructor that represents the scanner, in another method within the same class. This class should not have any variables, so I am unsure about what to do.
here is the AnimalHospital class:
import java.util.*;
import java.io.*;
public class AnimalHospital {
public AnimalHospital(String inputFile) throws FileNotFoundException {
Scanner input = new Scanner(new File(inputFile));
// how do I get input, into printPetInfoByName()?
}
public void printPetInfoByName(String petName){
// this is only here to show you that I need input in order for
// the program to work
String pName = "";
String oName = "";
String color = "";
String hLength = "" ; // for cat only
String size = ""; // dog only
String dog = "";
String bird = "";
/* This is how my file looks that is being read in
CAT
Ginger Owen Brown female medium
CAT
Busker Samantha male short*/
while(!(input.next().equals("END"))) {
if(input.next().equals("CAT")) {
pName = input.next(); // searching for inserted name
if(pName.equals(petName)) { // if found
oName = input.next();
color = input.next();
hLength = input.next();
Cat cat = new Cat(pName, oName,color, hLength);
// have to grab every word in the line to get each variable
cat.toString();
}
}
if(input.nextLine().equals("DOG")){
pName = input.next();
if(pName.equals(petName)) {
oName = input.next();
color = input.next();
size = input.next();
Dog d = new Dog(pName, oName, color, size);
// have to grab every word in the line to get each variable
d.toString();
}
}
if(input.nextLine().equals("BIRD")){
pName = input.next();
if(pName.equals(petName)){
oName = input.next();
color = input.next();
//size = input.next();
Bird b = new Bird(pName, oName, color);
//have to grab every word in the line to get each variable
b.toString();
}
}/*else{
throw new IllegalArgumentException("Pet Not Found." );
}*/
}
}
here is my tester:
public class Tester {
public static void main (String[]args)throws FileNotFoundException {
AnimalHospital a = new AnimalHospital("data.txt");
a.printPetInfoByName("Ginger");
}
}
I feel as though this is a very simple issue, yet I have no idea how to solve it.
As Alexander alluded to in the comments, you cannot use the scanner while its scope does not reach outside of the constructor. If the only requirement is that you pass the text file in the constructor, then you simply need to declare the scanner in the AnimalHospital class and initialize it within the constructor like this:
import java.util.*;
import java.io.*;
public class AnimalHospital{
Scanner input;
public AnimalHospital(String inputFile)throws FileNotFoundException{
input = new Scanner(new File(inputFile));
// how do I get input, into printPetInfoByName()?
}
public void printPetInfoByName(String petName){
// this is only here to show you that I need input in order for
// the program to work
String pName = "";
String oName = "";
String color = "";
String hLength = "" ; // for cat only
String size = ""; // dog only
String dog = "";
String bird = "";
/* This is how my file looks that is being read in
CAT
Ginger Owen Brown female medium
CAT
Busker Samantha male short*/
while(!(input.next().equals("END"))){
if(input.next().equals("CAT")){
pName = input.next(); // searching for inserted name
if(pName.equals(petName)){ // if found
oName = input.next();
color = input.next();
hLength = input.next();
Cat cat = new Cat(pName, oName,color, hLength);
// have to grab every word in the line to get each variable
cat.toString();
}
}
if(input.nextLine().equals("DOG")){
pName = input.next();
if(pName.equals(petName)){
oName = input.next();
color = input.next();
size = input.next();
Dog d = new Dog(pName, oName, color, size);
// have to grab every word in the line to get each variable
d.toString();
}
}
if(input.nextLine().equals("BIRD")){
pName = input.next();
if(pName.equals(petName)){
oName = input.next();
color = input.next();
// size = input.next();
Bird b = new Bird(pName, oName, color);
// have to grab every word in the line to get each variable
b.toString();
}
}/*else{
throw new IllegalArgumentException("Pet Not Found." );
}*/
}
}
As a side note, I think you forgot to define a variable for the gender, since I noticed you had "female" in your example input.

how to save inputs to file and call the inputs later (after closing app)

guys iam new to java so please help me
iam making a simple app of exam app which that the teacher can input the Questions
and save it
when the student open the app they will be asked if they are students then the
app will start the Questions
i made 2 files Teacher file and Student file
here is the code
package com.belal.teacher;
import java.io.*;
import java.util.Scanner;
public class Teacher {
public static void main(String[] args) {
// 1 is the Q
// 2 choice 1
// 3 choice 2
// 4 choice 3
// 5 correct choice
// 6 grade of the Q
String userinput1;
String userinput2;
String userinput3;
String userinput4;
String userinput5;
String userinput6;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
Scanner input5 = new Scanner(System.in);
Scanner input6 = new Scanner(System.in);
System.out.println(" enter the question: ");
userinput1 = input1.nextLine();
System.out.println(" enter answer 1 : ");
userinput2 = input2.nextLine();
System.out.println(" enter answer 2 : " );
userinput3 = input3.nextLine();
System.out.println(" enter answer 3 : " );
userinput4 = input4.nextLine();
System.out.println(" enter the correct answer : " );
userinput5 = input5.nextLine();
System.out.println("enter the grade of this Q : ");
userinput6 = input6.nextLine();
}
}
i want to call the input methods from this class under else i want to call the inputs from there under Else
package com.belal.student;
import java.util.Scanner;
import com.belal.teacher.Teacher;
public class Student {
public static void main(String[] args) {
System.out.println(" type (a) if u are a student type (b) if u are a teacher");
Scanner input = new Scanner(System.in);
input.nextLine();
if (input != input ) {
Teacher.main(args);
}else {
System.out.println();
}
}
}
It's a little hard to understand exactly what you're trying to do. At a minimum, it seems like you're trying to read/write to a database. If this is just for learning purposes and the read/write part isn't the main focus, you could just read/write to a text file. (Though if this is ever supposed to be multi-threaded that's a shoddy solution). Here's some code I wrote a while back for quick 'n' dirty reading/writing text.
import java.io.*;
import java.util.ArrayList;
public class TextIO {
/** Write a string to a text file at the given directory.
* #param f - directory, a string
* #param s - text to write
* #throws IOException
*/
public static void write(String f, String s) throws IOException {
write(new File(f), s);
}
/** Write a string to a text file at the given directory.
* #param f - directory, a file
* #param s - text to write
* #throws IOException
*/
public static void write(File f, String s) throws IOException {
FileWriter fr= new FileWriter(f);
BufferedWriter br= new BufferedWriter(fr);
br.write(s);
br.flush();
br.close();
}
/** Reads File f as a text file.
* #param f - the File to read
* #return - a String[], each entry of which is a line of text in f
* #throws IOException - if the file reading goes bad.
*/
public static String[] read(File f) throws IOException {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(f);
br = new BufferedReader(fr);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayList<String> s = new ArrayList<String>();
while(br.ready()){
s.add(br.readLine());
}
br.close();
String[] sArray = new String[s.size()];
sArray = s.toArray(sArray);
return sArray;
}
}
If you want more specific help beyond this, try to break your question up into discrete tasks you're trying to accomplish.

Categories

Resources