Trouble Passing an Array to an Arraylist [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Ok, so I have an assignment where we must create a java program which asks the user a contacts' name and and a variable amount of the numbers and number types(work, voip..) associated with the contact. The toString() method is suppose to print the contacts name and associated numbers and number types.
Am I passing my Array correctly from my main method to the phoneBookEntry constructor correctly? ( I know there are compile errors, etc, but I want to make sure I am passing the Arrays correctly. Also, is my approach correct?
Suppose to follow UML table accordingly here:
Phone book entry
name : String
phoneNumbers : String[]
phoneTypes : String[]
PhoneBookEntry()
PhoneBookEntry(nam : String) :
PhoneBookEntry(nam : String, numbers : String[], types : String[]) :
getName() : String
setName(nam : String) : void
getPhoneNumber(type : String) : String
setNumbers(numbers : String[], types : String[]) : void
toString() : String
Thanks!
Here is what I have so far:
package phonebookentry;
import java.awt.List;
import java.util.*;
public class PhoneBookEntry
{
private String name;
private String[] phoneNumbers,phoneTypes;
/**
* #param args
*/
public PhoneBookEntry()
{
}
public PhoneBookEntry(String nam, String[]numbers, String[]types)
{
phoneNumbers = numbers;
name = nam;
phoneTypes = types;
toString();
}
public String getName()
{
return name;
}
public void setName(String nam)
{
}
public String[] getPhoneNumber(String type)
{
return phoneTypes;
}
public void setNumbers(String[] numbers, String[] types)
{
this.phoneNumbers = numbers;
this.phoneTypes = types;
}
public String toString()
{
for (int index = 0; index < phoneNumbers.length; index ++ )
return System.out.println(nam, this.phoneNumbers, this.phoneTypes) ;
}
public static void main(String[] args)
{
String phoneN = "0";
ArrayList<String> Ptypes = new ArrayList<String>();
ArrayList<String> Pnumbers = new ArrayList<String>();
while (!phoneN.equals("-1"))
{
String phoneT;
Scanner input = new Scanner(System.in);
// Create an ArrayList to hold some names.
System.out.println("Phone number of Contact: (Input -1, to end)");
phoneN = input.nextLine();
if (phoneN.equals("-1"))
break;
Pnumbers.add(phoneN);
System.out.print("Type of phone number(mobile,home,VOIP,work,etc..):");
phoneT = input.nextLine();
Ptypes.add(phoneT);
}
String nam = "fas";
String[] types = Ptypes.toArray(new String[Ptypes.size()]);
String[] numbers = Pnumbers.toArray(new String[Pnumbers.size()]);
PhoneBookEntry passPhone = new PhoneBookEntry(nam,numbers,types);
passPhone.setNumbers(numbers,
types);
}
}

for (int index = 0; index < phoneNumbers.length; index ++ )
return System.out.println(index) ;
That returns nothing . println() returns void . Again , you are returning at the first iteration of the loop . You should construct a String and return it after the loop. Your public String toString() should return a String to avoid the compilation error.
Something like this :
public String toString()
{
StringBuilder str = new StringBuilder();
for (int index = 0; index < phoneNumbers.length; index ++ )
str.append(...) ; // append whatever you want to display
return str.toString();
}

The toString() method should concatenate out all the phone numbers(I presume)
#Override
public String toString() {
StringBuilder phoneBook = new StringBuilder();
//Generate comma separated entries of phone book
for (int i = 0; i < phoneNumbers.length && i < phoneTypes.length; i++ ) {
if (i > 0) {
phoneBook.append(',');
}
phoneBook = phoneBook.append(phoneNumbers[i])
.append(':')
.append(phoneTypes[i])
}
return phoneBook.toString();
}
Other comments
There is no point calling the toString() method in the constructor.
You should also check whether the lentgh of phoneTypes and phoneNumbers are equal in the constructor.
An empty constructor should be an empty phoneBook. By default the private fields are null. So the toString() method might blow up.
Separate get/set methods for phone numbers/types along with constructors are a bad choice. Instead keep a List where phone numbers could be added/deleted/updated. I guess that is the next assignment. Good Luck !

Related

Using ArrayList as function call Java

public class TestClass extends BaseClass {
public void getquote() {
String FirstName = "Sam";
String LastName = "Gayle";
String Email = "somename#somename.com";
String Password = "test1234";
CallGetQuote(FirstName, LastName, Email, Password);
}
private void CallGetQuote(String... var) {
for (int i = 0; i < var.length; i++) {
driver.findElement(By.id("first-name")).sendKeys(var[i]);
driver.findElement(By.id("last-name")).sendKeys(var[i]);
driver.findElement(By.id("join-email")).sendKeys(var[i]);
driver.findElement(By.id("join-password")).sendKeys(var[i]);
// driver.findElement(By.name("btn-submit")).click();
}
}
}
`I would like to fill in the objects using a loop rather than hard coded index number as mentioned. Above is what I wrote, at the moment, all text boxes are filling with all values. Please help :(
Thanks.`
You can use varargs, more informations could be found in the JLS:
You can use a construct called varargs to pass an arbitrary number of
values to a method. You use varargs when you don't know how many of a
particular type of argument will be passed to the method.
So, your code will be something like:
public void getquote() {
String firstName = "Sam";
String lastName = "Gayle";
String email = "somename#somename.com";
String password = "test1234";
CallGetQuote(FirstName, LastName, Email, Password);
}
public void CallGetQuote(String... var) {
// add your elements to a List
List<MyElements> inputElements = new ArrayList<MyElements>;
inputElements.add(driver.findElement(By.id("first-name")));
inputElements.add(driver.findElement(By.id("last-name")));
inputElements.add(driver.findElement(By.id("join-email")));
inputElements.add(driver.findElement(By.id("join-password")));
// iterate over the List to send keys
for (int i = 0; i < var.length; i++) {
inputElements.get(i).sendKeys(var[i]);
}
}
May be instead of passing array/list you can create a class containing all the variable and accessors and modifier functions for each variable. Create the object of the class in getQuote() and append the values in the same function. Later you can simply pass the object.
And whenever you have new attribute you can simply add the attributes to the class and use the object anywhere.
considaring that you have only specified number of inputs on web page you may try like this.
public void getquote() {
String FirstName = "Sam";
String LastName = "Gayle";
String ZipCode = "10104";
String PhoneNumber = "212-225-8558";
CallGetQuote(FirstName, LastName, ZipCode, PhoneNumber);
}
public void CallGetQuote(String... var) {
List<Webelement> inputs = driver.findElements(By.tagName("input"));
for (int i = 0; i < var.length; i++) {
inputs.get(i).sendKeys(var[i]);
}
}
You may have to change the order of strings you are sending.

Java storing both line number and value from a file

I have a set of data that look like this.
1:2:3:4:5
6:7:8:9:10
I have manage to use array list to store the information using a delimiter of ":".
However i would like to store the information of their line numbers together in the array list.
class test
{
String items;
String linenumber;
}
Example:
test(1,1)
test(2,1)
test(6,2)
test(7,2)
Here is my current code.
Scanner fileScanner = new Scanner(new File(fname));
fileScanner.useDelimiter("\n");
int counter = 0; String scounter;
String test;
String events;
while(fileScanner.hasNext())
{
events = fileScanner.next();
scounter = Integer.toString(counter);
Base obj = new Base(scounter, events);
baseArrayList.add(obj);
}
fileScanner.close();
I have try using delimiter "\n" and then trying to split out the string and it is not very successful.
Any advice would be appreciated.
public void Base_Seperator()
{
String temp, temp2;
String[] split;
String days, events;
for(int i = 0; i < baseArrayList.size(); i++)
{
temp = baseArrayList.get(i).events;
temp2 = baseArrayList.get(i).days;
split = temp.split(":");
}
}
Despite the code in #Alex's answer that may solve your problem, your attempt is almost close to get what you want/need. Now you only need to create Test instances and store them in a container, usually a List. I'll add the necessary code to start this from your code:
//it is better to return the List instead of declaring it as a static field
public List<Test> Base_Seperator() {
//try to declare variables in the narrower scope
//String temp, temp2;
//String[] split;
//String days, events;
//this variable must be recognized in all the paths of this method
List<Test> testList = new ArrayList<Test>();
for(int i = 0; i < baseArrayList.size(); i++) {
//these variables should only work within the for statement
String temp = baseArrayList.get(i).events;
String temp2 = baseArrayList.get(i).days;
String[] split = temp.split(":");
//you have splitted the String by :
//now you have every element between : as an item stored in split array
//go through each one and create a new Test instance
//first, let's create the lineNumber variable as String
String lineNumber = Integer.toString(i+1);
//using enhanced for to go through these elements
for (String value : split) {
//now, let's create Test instance
Test test = new Test(value, lineNumber);
//store the instance in testList
testList.add(test);
}
}
//now just return the list with the desired values
return testList;
}
Not part of your question, but some advices:
There are plenty other ways to write code to achieve the same solution (take #Alex's answer as an example). I didn't posted any of them because looks like you're in learning phase, so it will be better for you to first achieve what you're looking for with your own effort (and a little of help).
Not sure if you're doing it (or not) but you should not use raw types. This is, you should always provide a generic type when the class/interface needs it. For example, it is better to define a variable as ArrayList<MyClass> myClassList rather than ArrayList myClass so the class become parameterized and the compiler can help you to avoid problems at runtime.
It is better to always program oriented to interfaces/abstract classes. This means, it is better to declare the variables as an interface or abstract class rather than the specific class implementation. This is the case for ArrayList and List:
List<String> stringList = new ArrayList<String>();
//above is better than
ArrayList<String> stringList2 = new ArrayList<String>();
In case you need to use a different implementation of the interface/abstract class, you will have to change the object initialization only (hopefully).
More info:
What is a raw type and why shouldn't we use it?
What does it mean to "program to an interface"?
Looks like you want to store days instead of lineNumber in your Test instances:
//comment this line
//Test test = new Test(value, lineNumber);
//use this one instead
Test test = new Test(value, days);
First of all you don't need to keep line number info in the test object because it can be inferred from the ArrayList that holds them. If you must though, it should be changed to an int. So,
class test
{
ArrayList items<Integer>;
int linenumber;
public test(int line, String[] input){
items=new ArrayList();
linenumber=line;
//populate with the line read by the Scanner
for(int i=0; i<input.lenth; i++)
items.add(Integer.parseInt(input[i]));
}
}
I use an ArrayList inside test because you don't know how many elements you'll be handling. Moving on to the scanner
Scanner fileScanner = new Scanner(new File(fname));
// fileScanner.useDelimiter("\n"); You don't need this!
String tmp[];
int line=0; //number of lines
while(fileScanner.hasNext()) {
line++;
//this returns the entire line, that's why you don't need useDelimeter()
//it also splits it on '.' I'm not sure if that needs to be escaped but
//just to be sure
tmp=fileScanner.nextLine() . split(Pattern.quote("."));
baseArrayList.add(new test(line, tmp));
}
fileScanner.close();
Here I use test to store the objects you read, I'm not sure what Base is supposed to be.
A Java Bean/construct is required that will hold the day and the item together. The following code will read the text file. Each line will be converted to a List where finally the application will populate the List DayItems collection properly.
public class DayItem {
private int day;
private String item;
public int getDay() {
return day;
}
public void setDay(final int day) {
this.day = day;
}
public String getItem() {
return item;
}
public void setItem(final String item) {
this.item = item;
}
}
And main code
public class ReadFile {
private static final List<DayItem> dayItems = new ArrayList<DayItem>();
public static void main(String args[]) throws FileNotFoundException{
final BufferedReader bufferReader = new BufferedReader(new FileReader("items.txt"));
int lineNumber=0;
try
{
String currentLine;
while ((currentLine = bufferReader.readLine()) != null) {
lineNumber++;
List<String> todaysItems = Arrays.asList(currentLine.split(":"));
addItems(todaysItems,lineNumber);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void addItems(final List<String> todaysItems,final int day){
int listSize = todaysItems.size();
for(int i=0;i<listSize;i++){
String item = todaysItems.get(i);
DayItem dayItem = new DayItem();
dayItem.setDay(day);
dayItem.setItem(item);
dayItems.add(dayItem);
}
}
}

Declaring an object array in java (code included)?

public class Pig {
private int pigss;
private Pig[] pigs;
public Pig[] pigNumber (int pigss)
{
pigs = new Pig [pigss];
return pigs;
}
Code that includes main method:
public class animals{
public static void main(String[] args){
Pig cool = new Pig();
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int pigss = Integer.parseInt( keyboard.nextLine() );
cool.pigNumber(pigss);
//This is where I have trouble. I want to use the array pigs here in the main method, this is what i tried:
Pig[] pigs = cool.pigNumber(pigss);
I then tried to use a for loop and assign values (String) to the index of arrays (pigs[]). But the error that gives me is: cannot convert from String to Pig. Any tips are appreciated. THank you.
for(int j = 0; j < pigs.length; j++)
{
System.out.println("What is the pig " + (j+1) + "'s name");
pigs[j] = keyboard.nextLine();
}
Your pigs will need an attribute to contain the string values you are trying to pass:
public class Pig {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
Then when you want to assign this string value to your pig:
int indexOfPig = 0; // Or whatever it is supposed to be
pigs[indexOfPig].setName("I am a string");
In java you can only use ints as the indexes of arrays
It is saying 'cannot convert from String to Pig' because you can't do that!
If you want somehow convert a String to a Pig, you are going to need to write some code to do the conversion. For example, you might write a constructor that creates a new Pig from some kind of description. Or you might write a method that looks up a Pig by name or number or something.
It is hard to offer any more concrete advice because you don't tell us what is in the string values ... or how you expect the strings to become pigs. (The only suggestion I have is to try Macrame :-) )
Pig doesn't have a name member or even method that accepts a string. Also you are trying to assign a String(keyboard.nextline() to a Pig(pigs[j].
Add an attribute name to your pig.
class Pig{
public String name:
public void Pig(String name){
this.name = name;
}
}
Then assign a new instance of Pig in the loop.
pigs[j] = new Pig(keyboard.nextLine());
Also get rid of the useless class pigNumber. All you need is an ArrayList of Pigs. The array list can be dynanically sized.
List<Pig> pigs = new ArrayList<Pig>
so your loop could be something like
String name = ""
while(true){
name = keyboard.readline();
if(name== "stop"){
break;
}
pigs.add(new Pig(names);
}
Then getting the number of pigs is a simple
System.out.println(pigs.length());

Error: Constructor Room in class Room cannot be applied to given types

I am completely new to java. I have searched for hours upon hours for the solution to this problem but every answer involves passing args or using a void which I do not do in this situation.
I have two java files, one for Room class, and one for TourHouse class. I am trying to create a new Room in the TourHouse class. Here is my error, it's driving me nuts, I've tried everything I am capable of understanding. Thank you in advance.
HouseTour.java:15: error: constructor Room in class Room cannot be applied to given
types;
{
^
required: String, String
found: no arguments
reason: actual and formal arguments differ in length
Here is the Room class, will have 7 rooms total once I can figure this out
// Room.java
import java.util.*;
public class Room
{
// Define Instance Variables
private String name;
private String description;
// Define Constructor
public Room(String theName, String theDescription)
{
name = theName;
description = theDescription;
}
public String toString( )
{
return "The " + name + "\n" + description + "\n";
}
}
Here is the HouseTour class
import java.util.*;
public class HouseTour extends Room
{
// Define Variables
public Room[ ] rooms = new Room[7];
//Define Constructor
public HouseTour( )
{
rooms[0] = new Room("Living Room", "Mayonnaise and Brill Grates, Michaelsoft");
rooms[1] = new Room("Basement", "Hopefully no dead bodies down here...");
}
// this is horrible and not right
public String rooms( )
{
for (int i = 0; i <=7; i++)
{
String output = "House Rooms included in tour\n";
String output2 = output + rooms.toString() + "\n";
return output2;
}
}
}
EDIT: Solved but still need help here because I am complete n00b, :(
// this is horrible and not right
public String rooms( )
{
output = "House Rooms included in tour\n";
for (int i = 0; i <=7; i++)
{
output += rooms[i]; // I can't do this but how do i?
}
return output.toString(); // do I do this?
}
}
What I am doing is trying to learn java by converting the ruby projects I have created. So in ruby you say:
def rooms
output = "House Rooms included in tour\n"
#rooms.each do |r|
output += r.to_s + "\n"
end
return output
end
Edit: Still trying, any ideas?
added public String s; and public String output; to declarations
// this is horrible and not right
public String rooms( )
{
s = ""
output = "House Rooms included in tour\n";
for (int i = 0; i <=7; i++)
{
s += rooms[i];
}
s.toString() // I don't know
return output + s; // do I do this?
}
}
Edit: Solved thanks to Hovercraft Full Of Eels
Ah, I see your problem: HouseTour extends Room. Don't do this! HouseTour is not a more specific case of a Room type and so should not extend this class. It does not fulfill the "is-a" rule, and would be similar to trying to define Bus as a child class of SchoolKid. Just like a Bus isn't a type of SchoolKid but rather contains SchoolKids, a HouseTour isn't a Room but rather contains Rooms. It fulfills the has-a relationship, not the is-a relationship.
If the inheritance were proper in this situation, your HouseTour constructor would need to call the Room super constructor and pass in two String parameters:
// Don't do this!!!
public class HouseTour extends Room {
public HouseTour() {
super("foo", "bar");
....
}
But having said that, again inheritance is not proper here -- just get rid of extends Room, and you're home free.
e.g.,
public class HouseTour { // no extends!
private Room[] rooms; // has-a not is-a
public HouseTour() {
// don't call super here
}
Also, as per my comment, this will give you ugly output: rooms.toString()
Instead iterate through the Array and get the toString() result from each Room item in the array.
Edit
Suggestions on your rooms() method:
Create a String or StringBuilder before the loop.
Build up the String or StringBuilder inside the loop.
Return the String or StringBuilder#toString after the loop.
Inside of the loop get the toString() from the current Room item in the list.
You will need to check that the rooms[i] item isn't null before calling a method on it.
Edit 2
You state that this:
public String rooms( )
{
output = "House Rooms included in tour\n";
for (int i = 0; i <=7; i++)
{
output += rooms[i]; // I can't do this but how do i?
}
return output.toString(); // do I do this?
}
is causing problems, but you don't specify the problem.
Myself, I'd do something like:
public String rooms( ) {
// declare your String locally, not globally in the class
String output = "House Rooms included in tour\n";
// again, avoid using "magic" numbers like 7
for (int i = 0; i < rooms.length; i++) {
output += rooms[i].toString(); // **** you must extract Room's String
}
return output; // no need to call toString() on a String
}

How do you return an array object in java?

How do you return an array object in Java? I have an object that has an array in it and I want to work with it in my main class:
// code that does not work
class obj()
{
String[] name;
public obj()
{
name = new string[3];
for (int i = 0; i < 3; i++)
{
name[i] = scan.nextLine();
}
}
public String[] getName()
{
return name;
}
}
public class maincl
{
public static void main (String[] args)
{
obj one = new obj();
system.out.println(one.getName());
}
I am sorry if the answer is simple but I am teaching myself to code and I have no idea how you would do this.
You have to use the toString method.
System.out.println(Arrays.toString(one.getName()));
toString is a built-in function in Java (it might need library import; if you are using Netbeans, it will suggest it).
If the problem is to print it use
System.out.println(Arrays.toString(one.getName()));
//note System, not system
When you do getName() you are returning a reference to an array of strings, not the strings themselves. In order to access the individual strings entered, you can use the array index
String enteredName = name[index] format.
From your program, it looks like you want to print each item entered. For that, you could use a method like the following
public void printName() {
// for each item in the list of time
for(String enteredName : name) {
// print that entry
System.out.println(enteredName);
}
}

Categories

Resources