I’m trying to ask the user if they want to add another person to array list, "list". My thought was to loop to ask, then add those inputs into an array, "inf" and then put that array within an array list. Right now when I repeat the code it just erases the previous inputs; how would I make it so it adds to the array list after each iteration?
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
String ask = "no";
do {
System.out.println("Add? (yes/no)");
ask = scan.nextLine();
if (ask.equals("yes")){
//gather user info
System.out.println("Last Name: ");
String LastN = scan.nextLine();
System.out.println("First Name: ");
String FirstN = scan.nextLine();
System.out.println("# of Children:");
String Children = scan.nextLine();
System.out.println("Address:");
String Adr = scan.nextLine();
System.out.println("Phone #:");
String Pho = scan.nextLine();
Date dategather = new Date();
String Date = String.format("%tD", dategather);
//Input the data into an array
String[] inf = {LastN,FirstN,Children,Adr,Date,Pho};
ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list,inf);
System.out.println(list);
}
} while (ask.equals("yes"));
}
}
You'd want to declare the list outside the do-while structure, and if you want to print each line entry - then you do that right at the end of the do-while structure:
//here you declare the list OUTSIDE:
ArrayList<String> list = new ArrayList<String>();
do {
System.out.println("Add? (yes/no)");
ask = scan.nextLine();
if (ask.equals("yes")){
//gather user info
System.out.println("Last Name: ");
String LastN = scan.nextLine();
System.out.println("First Name: ");
String FirstN = scan.nextLine();
System.out.println("# of Children:");
String Children = scan.nextLine();
System.out.println("Address:");
String Adr = scan.nextLine();
System.out.println("Phone #:");
String Pho = scan.nextLine();
Date dategather = new Date();
String Date = String.format("%tD", dategather);
//Input the data into an array
String[] inf = {LastN,FirstN,Children,Adr,Date,Pho};
Collections.addAll(list,inf);
//so here you want to display what the person just entered:
System.out.println("You Have Entered : \n Last Name: "+LastN+" First Name: "+FirstN+" Children : "+Children+" Address: "+Adr+" Date of Birth: "+Date+" Phone Number: "+Pho);
}
} while (ask.equals("yes"));
I hope this helps you. Please give it a try and let me know.
You can create a class Person which has all the details of each person and add them to an ArrayList. Something like that:
(tip: you could make #children as integer instead of String)
public class test
{
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Person> list = new ArrayList<Person>();
do
{
System.out.println("Add? (yes/no)");
ask = scan.nextLine();
if (ask.equals("yes")){
System.out.println("Last Name: ");
String lastName= scan.nextLine();
System.out.println("First Name: ");
String firstName= scan.nextLine();
System.out.println("# of Children:");
String children = scan.nextLine();
System.out.println("Address:");
String address= scan.nextLine();
System.out.println("Phone #:");
String phone= scan.nextLine();
Date dategather = new Date();
String date = String.format("%tD", dategather);
list.add(new Person(lastName, firstName, children,address, phone,date));
}
}while (ask.equals("yes"));
}
}
public class Person
{
String lastName, firstName, children,address, phone,date
public Person(String lastName,String firsName,String children,String address,String phone, String date)
{
this.lastName=lastName;
this.firsName=firsName;
this.children=children;
this.address=address;
this.phone=phone;
this.date=date;
}
}
In your code in every loop the arrayList is reseting as you reinitialize every time.
Related
I'm very new to java and finding it hard to get used to the terms, I have searched the internet but everything I try doesn't work because I dont know how to properly implement it into my code... how can I simply get the console to display what I have entered into the array list? thanks
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Account {
List<String> name = new ArrayList<>();
List<String> address = new ArrayList<>();
List<String> createOption = new ArrayList<>();
List<String> sortCode = new ArrayList<>();
List<Integer> deposit = new ArrayList<>();
List<Double> accountNumber = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
public void accountCreation() {
String name = "", address = "", createOption = "", sortCode = "", deposit = "";
double accountNumber = 0;
boolean valid = false;
while (!valid) {
System.out.println("What account would you like to create?");
System.out.println("Current or savings?");
createOption = keyboard.nextLine();
if (createOption.equalsIgnoreCase("current") || createOption.equalsIgnoreCase("savings")) {
valid = true;
} else {
System.out.println("Please enter checking or savings");
}
}
System.out.print("Please enter your name:");
name = keyboard.nextLine();
System.out.print("Please enter your address");
address = keyboard.nextLine();
System.out.print("Please enter an initial deposit");
deposit = keyboard.nextLine();
System.out.print("Please enter an sort code ");
sortCode = keyboard.nextLine();
System.out.print("Please enter an account number");
accountNumber = Double.parseDouble(keyboard.nextLine());
valid = false;
System.out.println();
}
}
I changed your complete for the case of the name because your code cannot print anything as the main method is missing:
public class Account {
public static void main(final String[] args) {
new Account().accountCreation();
}
List<String> names = new ArrayList<String>();
public void accountCreation() {
final Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your name:");
names.add(keyboard.nextLine());
for (final String name : names) {
System.out.println("Name: " + name);
}
}
}
You can do the rest in a similar fashion. (ArrayList makes sense only if you want to have a lot entries; in case you need that you should loop.) ....
You are doing it incorrectly. You'll have to use add() to add an item to the ArrayList.
For Example:
name.add(keyboard.nextLine());
In order to display the items in the ArrayList you can use a loop as follows:
for(String n : name) {
System.out.println("Name: " + n);
}
You'll have to correct it for all other ArrayLists in your program.
I have a class where a user inputs information about an employee (first and last name, address, hire date) for a user determined number of employees.
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
public static void main(String [] args){
String employeeName = null;
String employeeAddress = null;
String hireDate = null;
Scanner userInput = new Scanner(System.in);
System.out.println("How many employees would you like to enter information for?");
int numEmployees = userInput.nextInt();
for( int i = 0; i < numEmployees; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter employees first name: ");
String firstName = input.nextLine();
System.out.println("Enter employees last name: ");
String lastName = input.nextLine();
System.out.println("Enter street employee lives on:");
String street = input.nextLine();
System.out.println("Enter city employee lives in:");
String city = input.nextLine();
System.out.println("Enter state employee lives in:");
String state = input.nextLine();
System.out.println("Enter employee's zip code:");
String zip = input.nextLine();
System.out.println("Enter month employee was hired:");
String month = input.nextLine();
System.out.println("Enter day employee was hired:");
String day = input.nextLine();
System.out.println("Enter year employee was hired:");
String year = input.nextLine();
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
employeeName = name.getName();
employeeAddress = address.getAddress();
hireDate = date.getDate();
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
System.out.println(obj);
}
}
}
I'm trying to get the program to go through the user prompts, take that info and put it in a position in an ArrayList, then repeat for however many times the user determined earlier and display all at once at the end. Something like this:
FirstName LastName, Address, Hire Date
FirstName LastName, Address, Hire Date
And so on. Right now, my code will run through the user prompts, display that, then run through the next round of prompts and display that:
Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date
[Name, Address, Hire Date]
Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date
[Name, Address, Hire Date]
I realize this is because my array and array display are within the for loop, but when I move the array outside the loop I get no display. When I move just the array display outside the loop, my code doesn't compile.
Move this line:
System.out.println(obj);
out of the for loop. And use List to contain the ArrayList. Then you display it in a separate for loop:
List<ArrayList<String>> objs = new ArrayList<ArrayList<String>>(); //use list of objs
for( int i = 0; i < numEmployees; i++ )
{
//all the inputs
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
objs.add(obj);
}
for( int i = 0; i < numEmployees; i++ ) //for loop just to display
System.out.println(objs.get(i)); //display each element here
What you are printing out is a tuple of type [string, string, string]. This can be represented as a List. Then for each employee you want to store this tuple in another List of type List<List<String>>.
public static void main( String [] args )
{
String employeeName = null;
String employeeAddress = null;
String hireDate = null;
Scanner userInput = new Scanner(System.in);
System.out.println("How many employees would you like to enter information for?");
int numEmployees = userInput.nextInt();
List<List<String>> employesInfo = new ArrayList<List<String>>();
for( int i = 0; i < numEmployees; i++ )
{
Scanner input = new Scanner(System.in);
System.out.println("Enter employees first name: ");
String firstName = input.nextLine();
System.out.println("Enter employees last name: ");
String lastName = input.nextLine();
System.out.println("Enter street employee lives on:");
String street = input.nextLine();
System.out.println("Enter city employee lives in:");
String city = input.nextLine();
System.out.println("Enter state employee lives in:");
String state = input.nextLine();
System.out.println("Enter employee's zip code:");
String zip = input.nextLine();
System.out.println("Enter month employee was hired:");
String month = input.nextLine();
System.out.println("Enter day employee was hired:");
String day = input.nextLine();
System.out.println("Enter year employee was hired:");
String year = input.nextLine();
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
employeeName = name.getName();
employeeAddress = address.getAddress();
hireDate = date.getDate();
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
employeesInfo.add(obj);
}
for (int i = 0; i < numEmployees; i++ ) {
System.out.println(emploeesInfo.get(i));
}
}
Here's my output:
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query:1
Enter Your Student ID:1
Enter Your First Name: Respo
Enter Your Middle Name: Topher
Enter Your Last Name: Raspo
Do you want to back to Query?(Yes/No)
Yes
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query: 4
12
Christopher
Reposo
Porras
1
Respo
Topher
Raspo
As you can see in the picture I'm trying to make a simple little system without database but using ArrayList to contain those data now my problem is in the Delete Query. Now in Delete Query I tell the user to type the student number which is 1 then delete the information of it and its contain which is first name, middle name, last name But I don't have much logic in ArrayList to do such thing. By the way is it possible to use only One ArrayList in this case or I need to make many array list to solve my problem.
public static void main(String[] args) {
//initialize Scanner for input process
Scanner scan = new Scanner(System.in);
//initialize needs variable
List<String> list = new ArrayList<String>();
int choose,chooseQuery;
String chooseYesOrNo = " ";
String chooseYesOrNo2 = " ";
do {
//Startup Program
System.out.println("=====-----LibrarySystem-----=====");
System.out.println("[1]Student Information");
System.out.println("[2]Book Information");
System.out.print("Choose Table:");
choose = scan.nextInt();
do {
if(choose == 1) {
System.out.println("-----Query-----");
System.out.println("[1]Update");
System.out.println("[2]Delete");
System.out.println("[3]Search");
System.out.println("[4]Show");
//reserved
//reserved
System.out.print("Choose Query:");
chooseQuery = scan.nextInt();
if(chooseQuery == 1) {
System.out.print("Enter Your Student ID:");
String id = scan.next();
list.add(id);
System.out.print("Enter Your First Name:");
String name = scan.next();
list.add(name);
System.out.print("Enter Your Middle Name:");
String middle_name = scan.next();
list.add(middle_name);
System.out.print("Enter Your Last Name:");
String last_name = scan.next();
list.add(last_name);
System.out.println("Do you want to back to Query?(Yes/No)");
chooseYesOrNo = scan.next();
} else if (chooseQuery == 2) { //Delete Query
System.out.print("Enter Student ID:");
String find_id = scan.next();
} else if(chooseQuery == 3) { //Search Query
} else if(chooseQuery == 4) { //Show Query
for (String s : list) {
System.out.println(s);
}
}
}
} while(chooseYesOrNo.equals("Yes"));
System.out.println("Do you want to get back at tables?(Yes/No)");
chooseYesOrNo2 = scan.next();
} while(chooseYesOrNo2.equals("Yes"));
System.out.println("-----=====Program Terminated=====-----");
}
Create Student object which contains all the fields you need (student id, name, etc)
class Student {
int studentId;
String firstname;
String middlename;
String lastname;
}
Have one array list for Student objects
java.util.List<Student> list = new java.util.ArrayList<Student>();
When Delete operation is selected, iterate through your list to find the object and remove it. Here's nice blog about ways to iterate through arraylist. My favorite method is as follows:
for (Student std:list) {
if (std.studentId == targetId) {
list.remove(std);
break; //since you've removed target, you can exit the loop
}
}
Scanner one = new Scanner(System.in);
System.out.print("Enter Name: ");
name = one.nextLine();
System.out.print("Enter Date of Birth: ");
dateofbirth = one.nextLine();
System.out.print("Enter Address: ");
address = one.nextLine();
System.out.print("Enter Gender: ");
gender = //not sure what to do now
Hi I've tried to figure this out myself but I can't quite get it from looking at other examples, most are either only accepting certain characters or A-Z+a-z
I'm trying to make the program only accept input of male or female ignoring the case and if the input is wrong to repeat the "Enter Gender:" until a correct value is entered.
You can put the piece of code in a while and validate each time. for instance:
String gender;
do
{
System.out.print("Enter Gender ('male' or 'female'): ");
gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))
do {
System.out.print("Enter Gender (M/F): ");
gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));
You can add an if check after gender assignment to display a invalid message
One way to do this is to use infinite loop and a label to break out.
Like this:
//Start
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
String str = one.nextLine();
switch (str.toUpperCase()){
case "MALE":
System.out.println("Cool");
break here;
case "FEMALE":
System.out.println("Nice");
break here;
default:
System.out.println("Genders variants: Male/Female");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = readValue(scanner, null);
System.out.print("Enter Date of Birth: ");
String dateofbirth = readValue(scanner, null);
System.out.print("Enter Address: ");
String address = readValue(scanner, null);
System.out.print("Enter Gender: ");
String gender = readValue(scanner, createGenderMatcher());
}
private static IMatcher createGenderMatcher() {
return new IMatcher() {
#Override
public boolean isMatch(String value) {
return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
}
};
}
private static String readValue(Scanner scanner, IMatcher matcher) {
String value = null;
do {
value = scanner.nextLine();
} while (matcher != null && !matcher.isMatch(value));
return value;
}
private interface IMatcher {
public boolean isMatch(String value);
}
Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}