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.
Related
I'm writting a simple model of a social media where a users friends is represented as an array of Friend objects.
I am getting the titled error with the use of the method toStringFriends used in the main method. Doe anyone know how to fix this problem?
public class Friend {
private String name;
private String password;
private int uid;
private Friend [] friends;
public Friend (String name, String password, int uid, Friend [] friends) {
this.name = name;
this.password = password;
this.uid = uid;
this.friends [0] = friends [0];
}
public Friend [] getFriends () {
return friends;
}
public String toStringFriends (Friend [] friends) {
String s = "";
for (int i = 0; i <= friends.length; i++) {
s = s + (friends [i]).getName();
}
return s;
}
}
public class Main {
public static void main(String[] args) {
Friend [] noFriends = new Friend [0];
Friend [] laurasFriends = new Friend [1];
Friend jack = new Friend ("jack","liverpool",1,noFriends);
laurasFriends [0] = jack;
Friend laura = new Friend ("laura","everton",2,laurasFriends);
String s = toStringFriends(laurasFriends);
System.out.println(s);
System.out.println(toStringFriends(laura.getFriends()));
}
}
You need to call it from laura's instance of the object:
String s = laura.toStringFriends(laurasFriends);
toStringFriends has access to friends and name so I would pass a separator if I passed anything. I would also prefer a StringBuilder to using String concatenation in a loop. And I don't see a getName() in your class, but Friend has access to its' own data. Then <= is going to cause an array index out of bounds exception, because valid array indices are 0 to friends.length - 1. So you can do something like,
public String toStringFriends(String sep) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < friends.length; i++) {
if (i != 0) {
sb.append(sep);
}
sb.append(friends[i].name);
}
return sb.toString();
}
And then change this.friends [0] = friends [0]; to this.friends = friends; in your constructor, and finally call toStringFriends like
String s = laura.toStringFriends(",");
Use it by creating Friend class object-
Friend friend=new Friend(<constructor input
parameters>);
friend.toStringFriends(<function input
parameters>);
Or make toStringFriends() static and call it by using Friend class.
You can't call an instance or non static method without object. You should use some instance object and then you can call via . operator.
Like object.method()
Either make toStringFriends() static or instantiate a Friend object and call that method on it.
I am having issues with objects and classes.
I had to define two classes:
Course: a course has a code, an name and a number of credits
Teacher: a teacher has a first name and last name. He can be asked his full name.
So far so good, I got no issue with them, but I have to do next assignment which I was trying to do in the last 2 days and I could not find a proper answer:
Extend the code of the class teacher. A teacher also has a list of courses he can teach. Add an array of Courses to the code. Also add a function addCourse(Course aCourse) to the code. Courses can also be removed from teachers.
I could do everyting in my way but no clue on how to create the addCourse(Course aCourse) method.
Find below my coding, but it must be according to the method described:
public class Course {
private String courseCode;
private String courseName;
private String numberOfCredits;
public Course(String courseCode, String courseName, String numberOfCredits) {
super();
this.courseCode = courseCode;
this.courseName = courseName;
this.numberOfCredits = numberOfCredits;
}
public void print() {
System.out.println(courseCode + "\t" + courseName + "\t" + numberOfCredits);
}
public static void main(String[] args) {
Course[] courseArray = new Course[4];
System.out.println("Code" + "\t" + "Name" + "\t" + "Credits");
courseArray[0] = new Course("001", "Hist", "3");
courseArray[1] = new Course("002", "Phy", "3");
courseArray[2] = new Course("003", "Math", "3");
courseArray[3] = new Course("004", "Log", "3");
for (int i = 0; i < courseArray.length; i++) {
courseArray[i].print();
}
}
}
Arrays are fixed length collections of objects, so you'll need to decide how big your array should be. Let's call the length of your array MAX_COURSES. A more advanced solution might resize the array when required, but I get the impression this is beyond the scope of your course.
So you need to define the Course[] array as a field of your Teacher class. The syntax of array declarations is quite easy to research, so I won't put that in here. Just make sure your array length is equal to MAX_COURSES.
Now, to add courses to the array, you need to know where to put them. To keep track of the next free position of the array, the easiest thing to do is to declare a field in your class:
private int numCourses = 0;
Now, when you add a new course, insert the course into the index specified by numCourses. Make sure you increment numCourses after you've added the course.
Finally, you ought to test to see if your array is full before you agree to insert a new course into the array, i.e. check if numCourses is smaller than MAX_COURSES. If it's not, you need to throw an exception.
I would recommend using a collection (such as a List) rather than an array. The code would look something like:
public class Teacher {
private final String firstName;
private final String lastName;
private final List<Course> courses = new ArrayList<Course>();
public Teacher(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void addCourse(Course course) {
courses.add(course);
}
}
Based on that example, you should be able to add the removeCourse method yourself, and any other method you need to operate on the list of courses.
If you want to return the list as an array, you could always convert it, e.g:
public Course[] getCourses() {
return courses.toArray(new Course[courses.size()]);
}
If you really need to use an array for the data structure based on your assignment, something you can try when adding and removing courses, is to construct a list from the array of courses, add or remove a course from that list, the convert the list back to an array of courses.
There's really 3 options here.
Option 1
If you're allowed to use List constructs:
private List<Course> courses = new ArrayList<Course>();
public void addCourse(Course aCourse)
{
if (aCourse == null)
{
return;
}
courses.add(aCourse);
}
Option 2
The uses arrays, but it doesn't scale. Assume that a teacher can only have a maximum of X courses, in my example 10:
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
return;
}
courses[numCourses] = aCourse;
numCourses++;
}
Option 3
This is identical to the previous item, but is a bit smarter in that it can resize the array... by creating a new one using the static method Arrays.copyOf
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
int size = courses.length * 2;
courses = Arrays.copyOf(courses, size);
}
courses[numCourses] = aCourse;
numCourses++;
}
I currently have two arrays containing usernames and passwords.
String[] UsernameArray = {"John","Per","Daniel","Jonathan"};
String[] PasswordArray = {"Davis","Harring","Smith","West"};'
Now i have an if statement looking like this:
if(Arrays.asList(UsernameArray).contains(LoginPanel.Username)&& Arrays.asList(PasswordArray).contains(LoginPanel.Password)) {
//Do something
}
Everything is working fine, except for the fact i only want respective people to use their respective last names as passwords. I want for example the username to be "John" and the password to be "Davis" ONLY.
As of now if i enter John and then enter the second persons last name "Harring" i get "Success!" and is logged on. How can i change this so the persons passwords can only be their own lastname and not anyone else's?
You need to make sure that the strings are at the same index in their respective arrays. Use the indexOf method:
if (Arrays.asList(UsernameArray).contains(LoginPanel.Username) &&
Arrays.asList(PasswordArray).contains(LoginPanel.Password) &&
//this way me make sure the username and password are at the same position.
Arrays.asList(UsernameArray).indexOf(LoginPanel.Username) == Arrays.asList(PasswordArray).indexOf(LoginPanel.Password)
)
{
//Do something
}
You may want to use a few local variables to avoid so many calls to Arrays.asList, which will create a new list every time you call it.
You don't need ArrayLists for that purpose, it's a waste of memory, you can use just arrays.
Loop over the array and check if the username given is right, save the index of that username and check if the password at that index is the same entered by the user. Something like this:
for (int i=0; i<usernameArray.length; i++) {
if (LoginPanel.username.equals(usernameArray[i]) && LoginPanel.password.equals(passwordArray[i])) {
//right credentials
}
}
To be clear: inputUser and inputPassword are username and password entered by the user
Note: As you can see, i used usernameArray, passwordArray, LoginPanel.username and LoginPanel.password with lowercase u and p: this is because of java naming conventions, you should start variable names with a lowercase letter.
Use indexOf:
List<String> usernames = Arrays.asList(UsernameArray);
if (usernames.contains(LoginPanel.Username) &&
PasswordArray[usernames.indexOf(LoginPanel.Username)].equals(LoginPanel.Password)) {
// Do something
}
From the API documentation
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
In your case, UsernameArray contains John and PasswordArray contains Harring and hence Arrays.asList(UsernameArray).contains(LoginPanel.Username)&& Arrays.asList(PasswordArray).contains(LoginPanel.Password) returns true.
You can use a Map of user name password like
Map<String,String> map = new HashMap<String,String>();
map.put("John","Davis");
and then this can be validated
String password= map.get(LoginPanel.Username);
if(LoginPanel.Password.equals(password0){
//Do something
}
Please note that in a real web application, password would be stored encrypted in some data store and not in a program.
you could do:
for(int i=0;i< UserNameArray.length; i++){
if(UserNameArray[i].equals(LoginPanel.Username)&& PasswordArray[i].equals(LoginPanel.Password)){
//do something
}
Easy way is that
public class LoginTestEasy {
public static void main(String[] args) {
String[] UsernameArray = {"John","Per","Daniel","Jonathan"};
String[] PasswordArray = {"Davis","Harring","Smith","West"};
String loginToCheck = "John";
String passwordToCheck = "Herring";
boolean loggedIn = false;
for(int i = 0; i < UsernameArray.length; i++) {
String currentLogin = UsernameArray[i];
String currentPass = PasswordArray[i];
if(currentLogin.equals(loginToCheck) && passwordToCheck.equals(currentPass)) {
loggedIn = true;
break;
}
}
System.out.println("Is logged in: " + loggedIn);
}
}
but the better way is to join login and password pair in single object. smth like
class LoginData {
String login;
String pass;
LoginData(String login, String pass) {
this.login = login;
this.pass = pass;
}
String getLogin() {
return login;
}
String getPass() {
return pass;
}
}
and then to loop among them.
So I'm writing a program for an assignment where I store Patients into a TreeSet. The problemn I'm having is I have to implement a method to discharge a specefic patient from the TreeSet.
for(int i = 0; i < 10 ; i++){
Random ag = new Random();
int age = ag.nextInt(99) + 1;
Names randomname = Names.getRandom();
String name = randomname.name();
String sex;
if(Math.random() > 0.5)sex = "female";
else sex = "male";
Random sn = new Random();
int serial = sn.nextInt(10000) + 1;
Address randomAddress = Address.getRandom();
String address = randomAddress.name();
Hospital.admitPatient(new Patient(age, name, sex, serial, Birthday.produceBirthday(), address));
}
So Thats how I am looping to get the Patients info and stats for the Patient Object. The admit patient method adds them to the TreeSet.
public static void admitPatient(Patient obj){
if(numofPatients < maxPatients){
patientList1.add(obj);
}
}
The Problem I'm having is withbthe Discharge patient method. Where I don't know what to put in the method
public static void dischargePatient(What do i put here in the driver when i call this method?){
patientList1.remove(w/e i put up there);
}
Since I didn't name the Objects of patients when creating them but just inserted them straight into the TreeSet I'm not sure exactly how to call them when i call the discharge patient method.
As you usually want to work with selected objects (patients) and not the whole list, you need a way to identify them somehow (for example by name or ID).
Since add and remove are similar, your dischargePatient method will be similar as well. Try
public static void dischargePatient(Patient patient) {
patientList1.remove(patient);
}
To retrieve a patient with a certain ID, you may iterate through your set and return it:
public Patient getPatientByID(String id) {
for (Patient patient : patientList1) {
if (patient.getID().equals(id)) {
return patient;
}
}
}
To remove a patient with ID "1234abc", you could do the following:
dischargePatient(getPatientByID("1234abc"));
Using this pattern, you rebuild the functionality of the map datastructure. Thus it might be better to use a Map (e.g. HashMap<>). Code will be reduced to operations like:
Map<String, Patient> patients = new HashMap<>();
patients.put("1234abc", patient1);
patients.remove("1234abc");
Full code for your example:
public static void admitPatient(Patient patient) {
if(numofPatients < maxPatients){
patients.put(patient.getID(), patient);
}
}
public static void dischargePatient(String id) {
patients.remove(id);
}
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 !