How should I add a search method in this code - java

Scanner scanner = new Scanner(System.in);
int weight;
int age;
//arrays
List<String> last = new ArrayList<String>();
List<Integer> zage = new ArrayList<Integer>();
List<Integer> zweight = new ArrayList<Integer>();
int i = 0;
int userInput = 0;
//menu options
while(userInput != 2) {
userInput = scanner.nextInt(); // collects the user inputs
//several switch statements to answer each menu options
switch(userInput) {
case 1:
it saves and stores all the user inputs.
System.out.println("Enter a last name, age, weight"); //stores all the user information
String lastName = scanner.next();
last.add(lastName);
age = scanner.nextInt();
zage.add(age);
weight = scanner.nextInt();
zweight.add(weight);
break;
Need to add a search code where it will retrieve the user inputs and display it, but i'm not sure on how to do it.
case 5:
System.out.println("Enter the name; Enter DONE to exit");
System.out.println("FOUND!!! Last Name: " +last+ " Age: " +zage+ " Weight: " +zweight);

Your names are stored in a list so you can try this:
if (last.contains(searchName)) {
String foundName = last.get(last.indexOf(searchName));
System.out.println("FOUND!!! Last Name: " +foundName);
} else{
System.out.println("Last Name: " +searchName+ " NOT FOUND!!! ");
}
Note that duplicate names may be in the list so you may want to loop over the indexes.

you can do this:
String enteredLastName = scanner.next();
for (String name : last){
if (name.equals(enteredLastName ){
//do something
}
}

Related

How to create items for ArrayList based on user input

I'm making an inventory program for my class. I have an Item class, Inventory class with an ArrayList, and an Inventory tester class. I want to ask the user how many items they want to add to inventory and then add those items based on their parameters. This is what I have but it isn't working:
import java.util.Scanner;
public class InventoryTester
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Inventory myInventory = new Inventory();
System.out.println("Enter 1 to print all inventory data");
System.out.println("Enter 2 to add items to the inventory");
System.out.println("Enter 3 to ");
System.out.println("Enter 4 to ");
int choice = input.nextInt();
if (choice == 1)
{
myInventory.printAllData();
}
else if (choice == 2)
{
System.out.println("How many items are you adding?");
int numOfItemsToAdd = input.nextInt();
for (int i = 0; i < numOfItemsToAdd; i++)
{
System.out.println("Enter the name of item " + i);
input.nextLine();
String tempName = input.nextLine();
System.out.println("Enter the type of item " + i);
String tempType = input.nextLine();
System.out.println("Enter the price of item " + i);
double tempPrice = input.nextInt();
Item newItem = new Item(tempName, tempType, tempPrice);
myInventory.addItem(newItem);
}
}
input.close();
}
}
EDIT: What I thought my problem was, wasn't actually my problem. I got this piece working.
If you are using nextInt() and nextLine() together, you need to consume the last new line character before calling nextLine(). So you need to add an extra .nextLine() before your for loop like so:
int numOfItemsToAdd = input.nextInt();
input.nextLine(); //ADDED CODE
for (int i = 0; i <= numOfItemsToAdd; i++)
{
System.out.println("Enter the name of item " + i + 1);
String tempName = input.nextLine();
System.out.println("Enter the type of item " + i + 1);
String tempType = input.nextLine();
System.out.println("Enter the price of item " + i + 1);
double tempPrice = input.nextInt();
Item newItem = new Item(tempName, tempType, tempPrice);
myInventory.addItem(newItem);
}

Java iterate through array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.
I have the following code although struggling to loop around and ask user for names and ages x10.
Any suggestions?
Thank you.
import java.util.Scanner;
public class AgeName {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numTried = 1;
int ageTried = 1;
boolean stop = false;
String name = "";
String[] num = new String[10];
int[] age = new int[10];
while(numTried <= 10 && ageTried <=10 && !stop){
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
if(name.toUpperCase().equals("DONE")){
stop = true;
}else{
num[numTried - 1] = name;
age[ageTried -1] = userAge;
}
numTried ++;
ageTried ++;
}
for(String output : num){
if(!(output == null)){
System.out.print(output + "," );
}
}
input.close();
}
}
You can use a Map<String,Integer>:
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
num[i] = name;
map.put(name, userAge);
}
for (String output : num) {
if (!(output == null)) {
System.out.print(output + ","+ map.get(output));
}
}
Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int. The String has to be UNIQUE!!
You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.
System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
break;

ArrayList<String> delete query

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
}
}

Validity via comparing strings while iterating through an array

Sorry if my question seems a little vague.
Basically what I am trying to do is error check using string comparison on a constructor object, which is stored in an array. I think I have the right idea: (Count is a static int that iterates whenever an employee is added in another method)
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
for (int i = 0; i < count; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID) == true) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID
+ "'s current title is: "
+ searchArray[i].getEmployeeTitle());
System.out.println(" ");
System.out
.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine().toUpperCase();
if (answer.equals("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
searchArray[i].setEmployeeTitle(newTitle);
searchArray[i].updateTitle(newTitle);
}
if (answer.equals("N")) {
break;
}
} else if (searchID.equals(arrayID) == false) {
System.out.println("Please enter a valid ID!");
}
}
}
This successfully error checks, however because it is iterating through the array, it will display an error message before a validation message if the array element is > 0 and is found in the array. Is there any way to analyse every element of the array and produce the error message if and only if the ID is not found in any elements?
you definitely should read a book how to program in Java.
All code below should be rewritten, but I leave it for understanding the error.
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
Employee found = null;
for (int i = 0; i < searchArray.length; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID)) {
found = searchArray[i];
break;
}
}
if (found != null) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID + "'s current title is: " + found.getEmployeeTitle());
System.out.println(" ");
System.out.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
found.setEmployeeTitle(newTitle);
found.updateTitle(newTitle);
}
} else {
System.out.println("Please enter a valid ID!");
}
}

Using a scanner to accept String input and storing in a String Array

Can someone help me please. I have done numerous searches but can't find a solution anywhere.
I'm a beginner to Java and currently practicing some code while on a break from college.
I am trying to make a Phonebook program. At the moment I am trying to add a new contact, below is the code i have but i am not sure how to store the information in an array can someone give me some pointers please.
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
//inputs
String name = "";
String phone = "";
String add1 = "";
String add2 = "";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (name.equals(""))
{
System.out.println("Enter contacts name: ");
name = input.nextLine();
name += contactName[];
}
while (add1.equals(""))
{
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[];
}
while (add2.equals(""))
{
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[];
}
while (phone.equals(""))
{
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[];
}
}
}
A cleaner approach would be to create a Person object that contains contactName, contactPhone, etc. Then, use an ArrayList rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index.
The second problem you have is that you don't have the variable index.
What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)
//go through this code I have made several changes in it//
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (i<11)
{
i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}
while (i<12)
{
i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}
}
}
Would this work better?
import java.util.Scanner;
public class Work {
public static void main(String[] args){
System.out.println("Please enter the following information");
String name = "0";
String num = "0";
String address = "0";
int i = 0;
Scanner input = new Scanner(System.in);
//The Arrays
String [] contactName = new String [7];
String [] contactNum = new String [7];
String [] contactAdd = new String [7];
//I set these as the Array titles
contactName[0] = "Name";
contactNum[0] = "Phone Number";
contactAdd[0] = "Address";
//This asks for the information and builds an Array for each
//i -= i resets i back to 0 so the arrays are not 7,14,21+
while (i < 6){
i++;
System.out.println("Enter contact name." + i);
name = input.nextLine();
contactName[i] = name;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact number." + i);
num = input.nextLine();
contactNum[i] = num;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact address." + i);
num = input.nextLine();
contactAdd[i] = num;
}
//Now lets print out the Arrays
i -= i;
while(i < 6){
i++;
System.out.print( i + " " + contactName[i] + " / " );
}
//These are set to print the array on one line so println will skip a line
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactNum[i] + " / " );
}
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactAdd[i] + " / " );
}
System.out.println();
System.out.println("End of program");
}
}
Please correct me if I'm wrong.`
public static void main(String[] args) {
Scanner na = new Scanner(System.in);
System.out.println("Please enter the number of contacts: ");
int num = na.nextInt();
String[] contactName = new String[num];
String[] contactPhone = new String[num];
String[] contactAdd1 = new String[num];
String[] contactAdd2 = new String[num];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num; i++) {
System.out.println("Enter contacts name: " + (i+1));
contactName[i] = input.nextLine();
System.out.println("Enter contacts addressline1: " + (i+1));
contactAdd1[i] = input.nextLine();
System.out.println("Enter contacts addressline2: " + (i+1));
contactAdd2[i] = input.nextLine();
System.out.println("Enter contact phone number: " + (i+1));
contactPhone[i] = input.nextLine();
}
for (int i = 0; i < num; i++) {
System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
}
}
`
There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.

Categories

Resources