Trying to use setVaraible() to make the String "Hometown" equal user input, so it can be called back later. Someone else previously helped me with something of this nature, but it was used in a loop, so I can't exactly see how it worked.
private static String InputName;
private static String Sex;
private static String Age;
private static String input;
private static String Hometown;
It looked like this:
while (sc.hasNext()) {
input = sc.next();
System.out.println("");
setVariable(a, input);
if(input.equalsIgnoreCase("no")){
sc.close();
break;
}
else if(a>questions.length -1)
{
a = 0;
}
else{
a++;
}
if(a>questions.length -1){
System.out.println("Fine, " + InputName
+ ", so, you are " + Age + " years old and " + Sex + "." );
System.out.println("");
sleep();
System.out.println("Do you need to change any information?\n");
}
if(!input.equalsIgnoreCase("no") && a<questions.length){
System.out.println(questions[a]);
}
And, I just need it here (I know this code is wrong):
static public void Intro() {
int a = 0;
setVariable(3, Hometown);
String[] questions = {"What do you want to name your hometown?"};
System.out.println(questions);
input = sc.next();
}
Here is the setVariable() method:
static void setVariable(int a, String Field) {
switch (a) {
case 0:
InputName = Field;
return;
case 1:
Age = Field;
return;
case 2:
Sex = Field;
return;
case 3:
Hometown = Field;
return;
}
}
Basically, you can call setVariable by passing it two values, the first is a int value which represents field to be set and the second is the value to apply, for example
setVariable(0, "This is the input name");
Would set the InputName variable to "This is the input name"
Using 1 would allow you to change the Age variable, 2 the Sex variable and 3 the Hometown variable, so basically, what you need to try is something like...
setVariable(3, "New home town value");
For example...
Currently your code looks something like...
static public void Intro() {
int a = 0;
setVariable(3, Hometown);
String[] questions = {"What do you want to name your hometown?"};
System.out.println(questions);
input = sc.next();
}
Which basically assigns the current value of Hometown to itself...which is probably null, then you try and read a value from the Scanner
Try it the other way round, for example...
static public void Intro() {
System.out.println("What do you want to name your hometown?");
input = sc.nextLine();
setVariable(3, input);
}
Making sure you pass the input value to the method, so it can assign the value to the correct field...
Personally, I don't find this either useful or intuitive. Sure you could use an enum or even define static final variables that would make determine which field you want to change easier, but Java is an Object Oriented language, we might as well make use of it...
I would encourage you to define a Person object (for argument sake) with which you can set/get the individual properties of the object, for example...
public class Person {
private String inputName;
private String sex;
private String age;
private String hometown;
public void setName(String name) {
this.inputName = name;
}
public String getName() {
return inputName;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public void setAge(String age) {
this.age = age;
}
public String getAge() {
return age;
}
public void setHometown(String hometown) {
this.hometown = hometown;
}
public String getHometown() {
return hometown;
}
}
Then you would simply create a new instance of Person
Person person = new Person();
And fill it out...
person.setName("Ruphet");
person.setSex("Male");
person.setAge("18");
person.setHometown("Murembugie");
And when you need to show or "get" some value...
System.out.println("Hello " + person.getName() + " from " + person.getHometown());
ps-
You might like to take a read through Code Conventions for the Java Programming Language, it will make it easier for others to read your code (and for you to read others)...
Try something like this.
// This method should not be static, but your Hometown is.
public static void setHometown(String input) {
// This should not be a static variable, also it shouldn't be capitalized.
if (input == null) {
Hometown = "";
} else {
Hometown = input;
}
}
Related
I'm working on a little project, but I'm having trouble. It has to do with creating classes, constructors, etc. For the class, all data fields have to be private. I must also have two constructors, one default and one parameterized. Here's the class:
public class PetInfo {
private String petName = "na";
private boolean petType = true;
private String petBreed = "na";
private double petAge = 0;
private double petWeight = 0;
private String ownerName = "na";
public PetInfo(){}
public PetInfo(String name, boolean type, String breed, double age, double weight, String owner){
this.petName = name;
this.petType = type;
this.petBreed = breed;
this.petAge = age;
this.petWeight = weight;
this.ownerName = owner;
}
public String getName (){
return petName;
}
public void setName(String name){
petName = name;
}
public boolean getType(){
return petType;
}
public void setType(boolean type){
petType = type;
}
public String getBreed(){
return petBreed;
}
public void setBreed(String breed){
petBreed = breed;
}
public double getAge(){
return petAge;
}
public void setAge(double age){
petAge = age;
}
public double getWeight(){
return petWeight;
}
public void setWeight(double weight){
petWeight = weight;
}
public String getOwner(){
return ownerName;
}
public void setOwner(String owner){
ownerName = owner;
}
}
Here is what I have in my main function:
import java.util.Scanner;
public class Pp1_C00019540 {
public static void main(String[] args) {
PetInfo[] info = new PetInfo[5];
collectInfo(info);
}
public static void collectInfo(PetInfo[] info){
Scanner input = new Scanner(System.in);
for(int i = 0; i < info.length;i++){
System.out.print("Enter pet name: ");
}
}
}
So it prints "Enter pet name: ", but it won't let me input a name. I tried to do:
info[i] = new PetInfo(input.nextLine());
But it tells me "constructor PetInfo.PetInfo(String, boolean, String, double,double, String) is not applicable. Actual and formal arguments differ in length." Is there something wrong with my class that I'm not catching? I tested it and it seemed to work correctly.
And I'm not looking for a definite answer, I could more than likely figure it out myself. I'm just not sure what's going on, especially when it seemed to me like this would work when I passed the constructor the correct parameters.
Basically, your code is trying to call the PetInfo constructor that takes a single string as input. But based on the code you have, no such constructor exists. You just have the large multi-parameter constructor for PetInfo. You need to call the scanner for input several times before you call the constructor. See the code below:
private static void collectInfo(PetInfo[] info) {
Scanner input = new Scanner(System.in);
try {
for (int i = 0; i < info.length; i++) {
System.out.print("Enter pet name: ");
String petName = input.nextLine();
System.out.print("Enter pet type: ");
boolean petType = input.nextBoolean();
input.nextLine();
System.out.print("Enter pet breed: ");
String petBreed = input.nextLine();
System.out.print("Enter pet age: ");
double petAge = input.nextDouble();
input.nextLine();
System.out.print("Enter pet weight: ");
double petWeight = input.nextDouble();
input.nextLine();
System.out.print("Enter pet owner: ");
String petOwner = input.nextLine();
info[i] = new PetInfo(petName, petType, petBreed, petAge, petWeight, petOwner);
}
}
finally {
input.close();
}
}
Hopefully the code above gives you a good illustration of what I'm talking about. Also, don't forget to call input.nextLine() after calls to nextBoolean() and nextDouble(). Lastly, don't forget to close your input scanner to avoid a resource leak.
Hope that helps.
Well it's simple, when you input using scanner. It takes input in a string, since there is no such constructor which takes string as a parameter it is giving you an error.
You need to take the input from scanner in respective datatypes, store them in variables and then call the constructor. I think what you are trying to do is to call the constructor while taking comma separated input from the scanner, that's not possible.
I am quite new to java and am having a problem trying to store user input to an array to later be able to call the list, however I am getting an error when trying to do so. The error comes on the newvoter.add(); line. Sorry if I'm being ignorant in any way, I feel like I'm being stupid!
public class admin {
public static Scanner sc = new Scanner (System.in);
public static List<voter> Voters = new ArrayList<voter>();
public static int promptUserInput() {
System.out.print("\n\tEnter: ");
int option = sc.nextInt();
return option;
}
public static int getOption() {
int option = promptUserInput();
switch(option){
case 1:
addVoter();
break;
case 2:
//deleteVoter();
break;
case 3:
Questions openQuestions = new Questions();
openQuestions.addQuestion();
break;
case 4:
break;
case 5:
System.out.println("Programme Ended");
System.exit(0);
default:
break;
}
return option;
}
public static void main(String[] args) {
printMenu();
}
public static void printMenu(){
System.out.println("\nAdmin Options Menu\n"
+ "\t\nPlease enter an option:\t\n"
+ "\n\t\t1: Create Voter\t\n"
+ "\t\t2:Delete Voter\t\n"
+ "\t\t3:Add Questions\t\n"
+ "\t\t4: View Questions List\t\n"
+ "\t\t5: Delete Question\t\n");
getOption();
}
private static void addVoter(){
voterAdd newvoter = new voterAdd(); // Creates a new voter
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Surname Name: ");
String surname = sc.next();
System.out.println("Enter Voter ID: ");
int voterID = sc.nextInt();
System.out.println("Enter City: ");
String city = sc.next();
newvoter.setVoter(firstName, surname, voterID, city);//calls the 'setVoter' method inherited from 'voter'
newvoter.add();//adds the 'newVoter' to the ArrayList 'voter'
System.out.println("\n New voter identification has been created and stored.\n");
listVoters();
}
Here is the class it calls from..
public class voterAdd {
private String firstName = "";
private String surname = "";
private int voterID = 0; //voterID of the voter
private String city = "";
public void setVoter(String firstName, String surname, int voterID, String city) {
this.firstName = firstName;
this.surname = surname;
this.voterID = voterID;
this.city = city;
}
public String getFirstName()
{
return firstName;
}
public String getsurname()
{
return surname;
}
public int getID()
{
return voterID;
}
public String getCity()
{
return city;
}
}
It's Voters.add(newvoter);, not newvoter.add(). Also, variable names should start with a lowercase letter or an underscore. Classes should start with uppercases.
Well one of your problems is that you are calling in your List the voter class, when maybe it should be the voteradd class like such:
List<voteradd> listName = new List<voteradd>();
Another thing, common java principles expect java classes to start with a capital letter(camel case), it's just good conventions and good practice. Hopefully this helped, best of luck :)
I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar
I am trying to solve an assignment in my Java class. I am stuck and need a little help.
I am trying to create a method in my Group class that will display the group name and the 4 students in the group. My code currently displays the group name and the memory location of my student inside my array.
public class Group {
/**-------Declaring attributes----*/
String groupName;
int newStudentCount;
/**----------------------------*/
/**--------Constructor------------*/
public Group(String givenGroupName) {
groupName = givenGroupName;
}
Student[] students = new Student[4];
/**----------------------------*/
/**--------Method------------*/
void addStudent(Student st) {
students[newStudentCount] = st;
++newStudentCount;
System.out.println("New student: " +st.getName());
}
public String getGroup() {
return "Group = " + groupName;
}
public Student getStudent(){
return students[0];
}
}
In my App class I have this:
public class App {
public static void main(String[] args) {
Group g1 = new Group("Pink Pony Princesses");
Student st1 = new Student("Joshua Mathews");
st1.getName();
g1.addStudent(st1);
Student st2 = new Student("Jame Brooks");
g1.addStudent(st2);
Student st3 = new Student("Mike Myers");
g1.addStudent(st3);
Student st4 = new Student("Christie Richie");
g1.addStudent(st4);
System.out.println(g1.getGroup()+ " " + g1.getStudent());
}
This is my Student class:
public class Student {
/**-------Declaring attributes----*/
String name;
String degree;
int age;
/**----------------------------*/
/**--------Constructor------------*/
Student(String givenName){
name = givenName;
}
Student(String givenName, String givenDegree, int givenAge) {
name = givenName;
degree = givenDegree;
age = givenAge;
}
/**--------- METHODS --------*/
//Array
public final String [] activities = {
"Working on Homework", "Playing a Game", "Taking a Nap"
};
String getInfo(){
return name + age + degree;
}
String getName() {
return name;
}
int getAge(){
return age;
}
String getDegree() {
return degree;
}
String whatsUp(){
Random rand = new Random();
int randomIndex = rand.nextInt(activities.length);
String returnActivity = activities[randomIndex];
return returnActivity;
}
I'm not sure how to call my array to display the 4 names, and not the memory location of them. Any help would be greatly appreciated.
I can deduce a couple of things from your question.
First, you are returning only the student at index 0 of the Student array held within your Group object. If you want to return all students your method signature should have a Student[] as the return type rather than a Student object.
If you follow the above prompt then you will have to iterate through the returned array printing each Student object.
Regardless of which implementation you choose the reason you print out a memory reference rather than a String object is that you have not overridden toString within your Student class.
Something like this will print out Student data when passed to a System.out call:
#Override
public String toString() {
return someStudentData;
}
You can go with what andrewdleach said by implementing toString(). OR
To print all student names your method should be something like:
public String getStudent(){
String studentNames = "";
for(Student stu: students){
studentNames+= stu.getName() + ",";
}
return studentNames;
}
I am required to make an address book application without the use of databases (on memory). I have decided to use ArrayLists to do so. But the problem is that once I input a new name/contact, it overrides any other contacts that I "stored" (or thought I stored) before. I have been trying to figure it out and am outright confused.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
firstActions();
}
static String firstName;
static String lastName;
static String phoneNumber;
static String search = null;
static public int choice = 0;
static Scanner input = new Scanner (System.in);
static ContactInformation contact;
static ArrayList<String> information = new ArrayList<String>();
public static void firstActions()
{
System.out.println("Address Book Menu: What would you like to do? 1) Input data. 2) Search data. 3) Close.");
choice = input.nextInt();
switch (choice) {
case 1:
inputData();
case 2:
System.out.println("Search by: 1) First Name 2) Last Name 3) Phone Number 4) Zip Code.");
choice = input.nextInt();
switch (choice) {
case 1:
searchName();
break;
case 2:
searchLastName();
case 3:
searchPhoneNumber();
case 4:
//execute search by Zip Code
default:
System.out.println("Please compile again.");
break;
}
break;
case 3:
System.out.println("Application terminated.");
System.exit(0);
default:
System.out.println("Please compile again.");
break;
}
}
public static void inputData ()
{
information = new ArrayList<String>();
contact = new ContactInformation(firstName, lastName, phoneNumber, information);
System.out.println("What is your first name?");
contact.setFirstName(input.next());
information.add(contact.getFirstName());
System.out.println("What is your last name?");
contact.setLastName(input.next());
information.add(contact.getLastName());
System.out.println("What is your phone number?");
contact.setPhoneNumber(input.next());
information.add(contact.getPhoneNumber());
System.out.println("Saved.");
System.out.println("What would you like to do next?");
firstActions();
}
public static void searchName()
{
System.out.println("What is the first name you are looking for?");
search = input.next();
if (search.equals(information.get(0)))
{
System.out.println(information);
System.out.println("What would you like to do next?");
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
public static void searchLastName()
{
System.out.println("What is the last name you are looking for?");
search = input.next();
if (search.equals(information.get(1)))
{
System.out.println(information);
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
public static void searchPhoneNumber()
{
System.out.println("What is the last name you are looking for?");
search = input.next();
if (search.equals(information.get(2)))
{
System.out.println(information);
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
}
Here is my contact information class:
import java.util.ArrayList;
public class ContactInformation {
public String firstName;
public String lastName;
public String phoneNumber;
ArrayList <String> information = new ArrayList<String> ();
public ContactInformation(String firstName, String lastName,
String phoneNumber, ArrayList<String> information) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.information = information;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
You first create the ArrayList here:
static ArrayList<String> information = new ArrayList<String>();
but every time you go to the inputData() method, you create a NEW ArrayList:
information = new ArrayList<String>();
From how you wrote the code, I would assume you have a ContactInformation object that you should be placing into the ArrayList.
Change the ArrayList to: static ArrayList<ContactInformation> information = new ArrayList<ContactInformation>();
Then you can create each object and ADD the object to the ArrayList INSTEAD of all the information separately.
EDIT:
Your "ContactInformation" object contains String variables. After you add this object to the ArrayList, you can use a loop to find if the data in the object matches what you are looking for. It should look something like this:
for (int i = 0; i != information.size(); i++) {
if (information.get(i).getFirstName().matches(search)) {
System.out.println("found");
}
}
The if statement says that "if the element 'i's variable 'firstName' in ArrayList 'information' matches the variable 'search', print the word 'found'."
You can obviously change what happens if the name is found, I just simplified it.
everytime you want to insert a name you are creating a new Object from ArrayList
information = new ArrayList<String>();
initizalize this arraylist in your main method and then access it via its variable(information)
The immediate problem is with the first line in your inputData() method:
information = new ArrayList<String>();
You're creating a new ArrayList object every time the method is called, which means the old object, and the data it contained, is lost.