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

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.

Related

Driver Java Animal Reserve

Unsure of where my code is failing, and where I should be going next with it. I need a fully functional loop menu, that seems to work so far, in which I am able to do the options the menu displays. This includes adding to lists and checking lists. I also am having an issue in which the dog list is not displaying the list of dogs by their name or information, but rather their space. Any help would be greatly appreciated.
// Complete intakeNewMonkey
//Instantiate and add the new monkey to the appropriate list
// For the project submission you must also validate the input
// to make sure the monkey doesn't already exist and the species type is allowed
public static void intakeNewMonkey(Scanner scanner) {
System.out.println("What is the new monkey's name?");
String name = scanner.nextLine();
for (Monkey monkey: monkeyList) {
if(monkey.getName().equalsIgnoreCase(name)) {
System.out.println("\n\nThis monkey is already in our system.\n\n");
return;
}
}
System.out.println("What is the monkey's tail length?");
String tailLength = scanner.nextLine();
System.out.println("What is the monkey's gender?");
String gender = scanner.nextLine();
System.out.println("What is the monkey's age?");
String age = scanner.nextLine();
System.out.println("What is the monkey's weight?");
String weight = scanner.nextLine();
System.out.println("What is the monkey's acquisition date?");
String acquisitionDate = scanner.nextLine();
System.out.println("What is the monkey's acquisition country?");
String acquisitionCountry = scanner.nextLine();
System.out.println("What is the monkey's training status?");
String trainingStatus = scanner.nextLine();
System.out.println("Is the monkey reserved? <enter true or false>");
boolean reservedBoolean = scanner.nextBoolean();
System.out.println("What is the monkey's service country?");
String serviceCountry = scanner.nextLine();
System.out.println("What is the monkey's body length?");
String bodyLength = scanner.nextLine();
System.out.println("What is the monkey's height?");
String height = scanner.nextLine();
System.out.println("What is the monkey's species?");
String species = scanner.nextLine();
}
// Complete reserveAnimal
// You will need to find the animal by animal type and in service country
public static void reserveAnimal(Scanner scanner) {
System.out.println("Enter animal type");
String type = scanner.nextLine();
if (type.equals("Monkey") || type.equals("monkey")) {
for (int i = 0; i < monkeyList.size(); i++) {
if (!monkeyList.get(i).getReserved());
System.out.println(monkeyList.get(i));
}
System.out.println("Enter name: ");
String name = scanner.nextLine();
for (Monkey obj: monkeyList) {
if (obj.name.equals(name)) {
obj.reserved = true;
return;
}
}
System.out.println("Monkey not found in list");
}
if (type.equals("Dog") || type.equals("dog")) {
for (int i = 0; i < dogList.size(); i++) {
if (dogList.get(i).getReserved())
System.out.println(dogList.get(i));
}
System.out.println("Enter name: ");
String name = scanner.nextLine();
for (Dog obj: dogList) {
if (obj.name.equals(name)) {
obj.reserved = true;
return;
}
}
System.out.println("Dog not found in list");
}
}
// Complete printAnimals
// Include the animal name, status, acquisition country and if the animal is reserved.
// Remember that this method connects to three different menu items.
// The printAnimals() method has three different outputs
// based on the listType parameter
// dog - prints the list of dogs
// monkey - prints the list of monkeys
// available - prints a combined list of all animals that are
// fully trained ("in service") but not reserved
// Remember that you only have to fully implement ONE of these lists.
// The other lists can have a print statement saying "This option needs to be implemented".
// To score "exemplary" you must correctly implement the "available" list.
public static void printAnimals() {
System.out.println("The method printAnimals needs to be implemented");
}
You need to override the toString() class provided by the Object class. You can do this by writing something like
#Override
public String toString() {
return "Name: " + this.name + ". Gender " + this.gender "." // and so on
}

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");
}

ReplaceAll with string builder with user input

I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little

Java read from a text file

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.

Categories

Resources