Changing and using one object array in two methods - java

I'm making a phone class and a phone book class right now. The phone class declares name and phone number fields, and the phone book class has read and run methods. When run() method is executed in the main function, information is input through the read() method, and information is retrieved and output through the run() method. However, I declared an instance array called phonebooks and tried to input the information received from the read() method into the array, but when I tried to output it through the run method, the array instances were not saved properly. There seems to be an issue where something isn't saving properly, how do I fix it?
import java.util.Scanner;
class Phone {
static private String name;
static private String tel;
public String getNum() {
return tel;
}
public String getName() {
return name;
}
public Phone(String name, String tel) {
this.name = name;
this.tel = tel;
}
}
public class PhoneBook {
private Scanner scanner;
static int repeat;
static Phone[] phonebooks;
public PhoneBook() {
scanner = new Scanner(System.in);
}
void read() {
System.out.print("Number of person to store? >> ");
int repeat = scanner.nextInt();
Phone[] phonebooks = new Phone[repeat];
for (int i = 0; i < repeat; i++) {
System.out.print("Name and Tel. No. >> ");
String name = scanner.next();
String tel = scanner.next();
phonebooks[i] = new Phone(name, tel);
if (i == repeat - 1) break;
}
System.out.println("Saved.");
}
void run() {
read();
while (true) {
System.out.print("Who do you wanna search for? >> ");
String search = scanner.next();
if (search.equals("stop")) break;
int i;
for (i = 0; i < repeat; i++) {
if (phonebooks[i].getName() == search)
System.out.println(search + "'s number is " + phonebooks[i].getNum());
break;
}
}
scanner.close();
}
public static void main(String[] args) {
new PhoneBook().run();
}
}

There are few issues in your code, below are some suggestions to make it work--
change member variables from static private to only private in Phone
Don't redeclare repeat & phonebooks in read().
Change if (phonebooks[i].getName() == search) call in run() to if (phonebooks[i].getName().equalsIgnoreCase(search)) so that it will search & match search string.

Related

How can I declare an array in one function and use that same array in another function?

Here is my code
class Employee{
private String Animal;
private int Quantity;
Employee(String Animal, int Quantity){
this.Animal=Animal;
this.Quantity=Quantity;
public String getAnimal{
return animal;
}
public void setAnimal{
this.Animal=Animal;
}
public String getQuantity{
return Quantity;
}
public void setQuantity{
this.Quantity=Quantity;
}
public static void Input(){
Scanner sc = new Scanner(System.in);
int n = 0;
Employee[] list = new Employee[20];
list[no] = new Employee(" ", 0);
String nameOfAnimal = sc.nextLine();
list[n].setAnimal(nameOfAnimal);
String numberOfAnimal = sc.nextLine();
list[n].setQuantity(numberOfAnimal);
++n;
}
public static void Output(){
...
for(int i=0; i<n; ++i){
System.out.println(" -" + list[i].getAnimal + " - " + list[i].getQuantity);
}
}
}
In the Output method, I dot 3 points because I don't know how to get the array declared in the Input method and print its content within the Output method. It always shows an error that the first element is null when I create the same array in the Output function. Concisely, how can I keep an array that both functions can be used?

Returning and displaying contents of ArrayList in different class?

I'm working on a project where I will tally a Student's choices and add them to a count array (still working on this part). For now, I'm trying to retrieve the choices that have been sent and added to a Student ArrayList in my Student class.
Student class:
public class Students {
private String name;
private ArrayList<Integer> choices = new ArrayList<Integer>();
public Students(){
name = " ";
}
public Students(String Name){
name = Name;
}
public void setName(String Name){
name = Name;
}
public String getName(){
return name;
}
public void addChoices(int Choices){
choices.add(Choices);
}
public ArrayList<Integer> getChoices(){
return choices;
}
Here is my main driver class:
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
String[] choices = new String[100];
int[] count;
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices[choicesIndex] = line;
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int countIndex = 0;
for(int i = 0; i < students.size(); i++){
if(students.get(i).getChoices(i) == -1){
}
}
The last part is where I am now. It's nowhere near done obviously (I'm right in the middle of it) but during my construction of a for loop to get the choices from the students, I'm getting an error that says, "The method getChoices() in the type Students is not applicable for the arguments (int)." Can someone explain what this means, where me error is, and possibly how to fix it? Thanks all.
getChoices(int i) is not a method you've defined.
if(students.get(i).getChoices(i) == -1){
}
getChoices() returns a list, so you can just use the get method on the list:
if(students.get(i).getChoices().get(i) == -1){
}
Alternatively, make a getChoice method:
public Integer getChoice(int i){
return choices.get(i);
}
Have you tried getChoices()[i] instead of getChoices(i)

Read File to Print to Screen

I have a file Inventory.txt that I am trying to print to the screen. Each line from the file goes into an object array. My code compiles with no errors but when I run it, nothing prints nothing to the screen. Im using Mac and TextEdit/Terminal.
import java.util.Scanner;
import java.io.*;
public class VendingMachineSimulator
{
to be imported
public static void main(String[] args) throws FileNotFoundException
{
File InventoryFile = new File("Inventory.txt");
Scanner input = new Scanner(InventoryFile);
//This code block will count the number of lines(products) are in the text file
int counter = 0;
while (input.hasNextLine())
{
counter = counter + 1;
}
Inventory[] InventoryObject = new Inventory[counter];
String line = "";
for (int i = 0; i < counter; i++)
{
String[] ProductArray = line.split("-");
InventoryObject[i] = new Inventory(Integer.valueOf(ProductArray[0]), ProductArray[1], ProductArray[2],
ProductArray[3],Double.valueOf(ProductArray[4]), ProductArray[5],
Integer.valueOf(ProductArray[6]));
}
for (int i = 0; i < counter; i++)
{
System.out.println();
InventoryObject[i].PrintInventory();
}
}
public static void PrintMenu()
{
System.out.println();
System.out.println("Display Inventory: <1>");
System.out.println("Display Currency: <2>");
System.out.println("Purchase Item: <3>");
System.out.println("Exit: <4>");
System.out.println();
}
}
class Inventory
{
private int ID;
private String Type;
private String Name;
private String PriceText;
private double Cost;
private String QuantityText;
private int StockAmount;
//Constructor method. values passed to it from the main method.
public Inventory(int ID, String Type, String Name, String PriceText, double Cost, String QuantityText, int StockAmount)
{
this.ID = ID;
this.Type = Type;
this.Name = Name;
this.PriceText = PriceText;
this.Cost = Cost;
this.QuantityText = QuantityText;
this.StockAmount = StockAmount;
}
public void setID(int ID)
{
this.ID = ID;
}
public void setType(String Type)
{
this.Type = Type;
}
public void setName(String Name)
{
this.Name = Name;
}
public void setPriceText(String PriceText)
{
this.PriceText = PriceText;
}
public void setCost(double Cost)
{
this.Cost = Cost;
}
public void setQuantityText(String QuantityText)
{
this.QuantityText = QuantityText;
}
public void setStockAmount(int StockAmount)
{
this.StockAmount = StockAmount;
}
public int getID()
{
return ID;
}
public String getType()
{
return Type;
}
public String getName()
{
return Name;
}
public String getPriceText()
{
return PriceText;
}
public double getCost()
{
return Cost;
}
public String getQuantityText()
{
return QuantityText;
}
public int getStockAmount()
{
return StockAmount;
}
public void PrintInventory()
{
System.out.println(ID + " " + Type + " " + Name + " " + PriceText
+ " " + Cost + " " + QuantityText + " " + StockAmount);
}
}
You never read a line, you only count them:
while (input.hasNextLine())
{
counter = counter + 1;
}
You have to place line = input.readLine(); inside this loop somewhere and change your logic accordingly, otherwise, it will always stay in the while loop. Think about when you would need to update or read the counter.
This is an endless loop. If there is text in the file, the input has a next line.
Since that line isn't read in the loop, input.hasNextLine() is always true.
while (input.hasNextLine())
{
counter = counter + 1;
}
You should rather use a List to read the Objects, that way you don't need to know the size initially.
You can remove the first while loop as its infinite loop.
Change the for loop to a while loop and do itererate as long as you have a next line and within the loop read the nextline and assign to line string and change the inventoryObject to an ArrayList and add items.
This should ideally resolve the issue.
You are blocking the input from the Inventory.txt file in you while loop. You are only checking if a next line exists without actually reading the next line. So you're going to an infinite loop here:
int counter = 0;
while (input.hasNextLine())
{
counter = counter + 1;
}
You need to call this at some point inside your whilte loop:
input.nextLine();
Tip: You can consolidate all the actions that you are performing inside this while loop. You probably don't need as many loops:
Assigning to line; Declare line before the while loop.
Splitting line into ProductArray. This will be line.split assigned to ProductArray.
Creating the new Inventory object. You may not need an array of Inventory Objects. Simply create one using the ProductArray variable.
Printing the inventory. Simply call the PrintInventory method on the the object created in step 3.
Hope this helps!

getting input from user for different types of data and storing it as an object in an ArrayList in java

I need to get the input from the user for my "MailCostumer" class.
as you can see there are 3 types: String, int and boolean.
this is the class:
class MailCostumer {
private String name;
private int id;
private String address;
private boolean isPack;
public MailCostumer(String name, int id, String address, boolean isPack) {
this.name=name;
this.id=id;
this.address=address;
this.isPack=isPack;
}
/*in the rest of the class there are the set and get methods
for class fields, if you need to see them, I will post them.*/
My ArrayList is in the class "Queue", like this:
import java.util.ArrayList;
public class Queue
{
private ArrayList<MailCostumer> waiting = new ArrayList<MailCostumer>();
private Boolean isEmpty;
public Queue ()
{
this.waiting = new ArrayList<MailCostumer>();
this.isEmpty=true;
}
public void addClient(MailCostumer MC)
{
this.waiting.add(MC);
this.isEmpty=false;
}
public void delClient(MailCostumer MC)
{
if(waiting.size()!=0)
{
this.waiting.remove(0);
if(waiting.size()==0)
{
this.isEmpty=true;
}
}
}
and this is my main class with the main method:
import java.util.Scanner;
public class Costumer
{
public static void main(String[] args)
{
MailCostumer c1 = new MailCostumer("gabriel", 1234, "ashqelon", true);
MailCostumer c2 = new MailCostumer("tal", 1235, "ashdod", true);
Queue q1 = new Queue();
Scanner scan = new Scanner(System.in);
for(int i=0;i<5;i++)
{
c1.setName(scan.nextLine());
}
q1.addClient(c1);
q1.addClient(c2);
System.out.println(q1.waiting.get(1).getName());
}
}
my question is, how do i get input from the user about different types of data and storing them in my "waiting" ArrayList, as an object of "MailCostumer"?
i need only the ones that isPack==true to be added to the Queue.
im trying to do this from the 'main' method ofcourse, but with no luck.
the 'c1 and c2' i have build, i need the user to input this information.
You can have the user type in a line :
gabriel 1234 ashqelon true
And write your for loop like this (note the extra hasNextLine condition)
This will check that the user typed 4 space separated words and that the last one is "true". In that case it will append a new object to the c1 queue.
for(int i = 0; i < 5 && scan.hasNextLine(); i++) {
String line = scan.nextLine();
String[] data = line.split(" ");
if (data.length() == 4 && "true".equals(data[3])) {
q1.addClient(new MailCostumer(
data[0],
Integer.parseInt(data[1]),
data[2],
true
);
}
}
Third option make a static construction method in MailCostumer that takes a line as argument. That's good design because code specific to generating a MailCostumer object should be packaged in the class and not in main :
public static MailCostumer valueOf(String line) {
String[] data = line.split(" ");
if (data.length() == 4 && "true".equals(data[3])) {
return new MailCostumer(
data[0],
Integer.parseInt(data[1]),
data[2],
true
);
}
return null;
}
The for loop would look very lean then
for(int i = 0; i < 5 && scan.hasNextLine(); i++) {
String line = scan.nextLine();
MailCostumer c = MailCostumer.valueOf(line);
if (c != null)
q1.addClient(c);
}

Add static method to class takes array Athletes as argument and returns total nums of medals won by all

i already have the athelete class and i just dont know how to go about the rest of the problem ive been trying to do things that havent work at all but heres what i have for now. im still a beginner this is my first semester taking java so i may not understand some of the things you guys will add so if u can please explain.
This is what they are asking for me to do.
Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. test in method.
package homework;
import java.util.Arrays;
public class Athlete {
private String name; // the name of the athlete
private String sport; // the sport the athlete does
private int numMedals; // the number of medals that the athlete has won
// constructor
public Athlete(String n, String s, int num) {
name = n;
sport = s;
numMedals = num;
}
// getters and setters for all instance variables
// (also called accessors and mutators)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getNumMedals() {
return numMedals;
}
public void setNumMedals(int numMedals) {
this.numMedals = numMedals;
}
/* Returns a String with information about the athlete.
*/
public String toString() {
return name + " does " + sport + " and has won " + numMedals + " medal(s).";
}
public static void AthMedals(int[][]numMedals){
for(int i = 0; i < numMedals.length;i++){
int total = 0;
for(int j = 0; j < numMedals.length; i++);
total = numMedals.getNumMedals();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Athlete SA = new Athlete("Socrates","Baseball",5);
Athlete CC = new Athlete("Cesar","Baseball",3);
Athlete JA = new Athlete("Juan","Soccer",2);
System.out.println(SA);
System.out.println(CC);
System.out.println(JA);
System.out.println("SA has " +SA.getNumMedals()+ " medals.");
}
}
}
The assignment is to write a method like
public static int sumOfAllMedals(Athlete[] all)
which returns all[0].numMedals + all[1].numMedals + ... + all[n].numMedals.
I assume AthMedals is your attempt at doing this, but it's in fact only consuming processing power while not doing anything.
I'm not gonna do your homework for you, but here's a hint:
public static int sumOfAllMedals(Athlete[] all)
{
int total = 0;
// For every Athlete in `all`, add the number of medals (s)he's won
// Should be four lines at most ;)
return total;
}
The static method have to iterate the array and add each medals to a final return variable.
static public int totalMedals(Athlete[] athelte) {
int totalMedals = 0;
for(int i=0;i<athelte.length;i++) {
totalMedals += athelte[i].numMedals;
}
return totalMeadls;
}

Categories

Resources