Validity via comparing strings while iterating through an array - java

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!");
}
}

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

Output prints first and part of second string. String sizes not set correctly

I've been writing this program that is supposed to build accounts for people inputted, saving their info all together in as one "superString" string, so it can be written and read from a txt file. I thought I had it all together correctly, but after testing various inputs and then reading back, it seems as though it isn't setting up the string lengths correctly.
If I only want account number 1, it will print out the account number 1.
If I put more accounts in and then try to only print out account 1, it'll print out account 1 and part of 2.
The output changes based on the size of the inputs, even though I put loops in there to have strict sizes.
I've been looking at the same problem for too long now and hopefully I'm just overlooking an easy fix. Can anyone help me out with this?
public class FirstTr {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
File loc = new File("C:\\Users\\Desktop\\Exc2.1.txt");
RandomAccessFile store = new RandomAccessFile(loc, "rw");
for(int i=0; i<20; i++)
{
String dummy = "12345678901234567890123456789012345678901234567890123456789012345678901";
store.writeUTF(dummy);
}
String userChoice = GettingUserInput();
System.out.println("The choice you entered: " +userChoice);
while(true){
if(userChoice.equals("new"))
{
String playerID = PlayerIDMethod();
System.out.println("The playerID you entered: " +playerID);
String playerName = PlayerNameMethod();
System.out.println("The playerName you entered: " +playerName);
String playerTeamName = PlayerTeamNameMethod();
System.out.println("The playerTeamName you entered: " +playerTeamName);
String playerSkillLevel = PlayerSkillLevelMethod();
System.out.println("The playerSkillLevel you entered: " +playerSkillLevel);
String todaysDate = TodaysDateMethod();
System.out.println("The date you entered: " +todaysDate);
String superString = "";
superString = playerID + playerName+ playerTeamName + playerSkillLevel + todaysDate;
//System.out.println("Combined string is: "+superString);
int playerIDDigit = Integer.parseInt(playerID);
store.seek((playerIDDigit-1)*73);
store.writeUTF(superString);
System.out.println("Length of string: " +superString.length());
userChoice = GettingUserInput();
}
if(userChoice.equals("old"))
{
System.out.println("Please enter player ID: ");
String desiredID = input.next();
int recLocation;
recLocation = Integer.parseInt(desiredID);
store.seek((recLocation-1)*73);
String printed = store.readUTF();
System.out.println("String: "+printed);
userChoice = GettingUserInput();
}
if(userChoice.equals("end"))
{
System.out.println("Program Closed.");
store.close();
System.exit(0);
}
}
}
public static String GettingUserInput()
{
System.out.println("Please type in a command: new, old, or end to exit");
String userChoice = input.next();
while(!userChoice.equals("New") && !userChoice.equals("new") && !userChoice.equals("Old") && !userChoice.equals("old") && !userChoice.equals("End") && !userChoice.equals("end"))
{
System.out.println("Looks like you didn't enter a correct choice.");
System.out.println("Please type in a command: new, old or end");
userChoice = input.next();
}
return userChoice;
}
public static String PlayerIDMethod()
{
String playerID = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please input Player ID: ");
playerID = input.next();
int playerIDDigit = Integer.parseInt(playerID);
if (playerID.length()> 5){
playerID.substring(0,5);
}
if (playerID.length()< 5){
StringBuilder paddedName = new StringBuilder(playerID);
while(paddedName.length()<5){
paddedName.append(" ");
}
playerID = paddedName.toString();
}
while(Pattern.matches("[a-zA-Z]+", playerID)|| playerID.startsWith("-")|| playerIDDigit>20 || playerIDDigit<0)
{
System.out.println("Player ID cannot have characters, negatives, and must be within 1-20!");
System.out.println("Please input Player ID: ");
playerID = input.next();
}
loop = false;
}
catch(Exception e)
{
System.out.println("No way Hosay! Only Integers!");
}
}
return playerID;
}
public static String PlayerNameMethod ()
{
String playerName = "";
try{
System.out.println("Enter Player's Name: ");
playerName = input.next();
while(Pattern.matches("^\\d+", playerName))
{
System.out.println("No cool names include numbers! Try again.");
System.out.println("Enter Player's Name: ");
playerName = input.next();
}
if (playerName.length()> 26){
playerName.substring(0,26);
}
if (playerName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerName = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerName;
}
public static String PlayerTeamNameMethod ()
{
String playerTeamName = "";
try
{
System.out.println("Please enter Team name: ");
playerTeamName = input.next();
if (playerTeamName.length()> 26){
playerTeamName.substring(0,26);
System.out.print("The Player Name is" + playerTeamName);
}
if (playerTeamName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerTeamName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerTeamName = paddedName.toString();
}
}
catch(Exception e)
{
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerTeamName;
}
public static String PlayerSkillLevelMethod ()
{
String playerSkillLevel = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
while(Pattern.matches("[a-zA-Z]+", playerSkillLevel))
{
System.out.println("Player skill level must be an integer!");
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
}
loop = false;
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN ");
}
}
return playerSkillLevel;
}
public static String TodaysDateMethod (){
String todaysDate = "";
try{
System.out.println("Please enter todays date: ");
todaysDate = input.next();
if (todaysDate.length()> 9)
{
todaysDate = todaysDate.substring(1,9);
}
if (todaysDate.length()< 9)
{
StringBuilder paddedName = new StringBuilder(todaysDate);
while(paddedName.length()<26){
paddedName = paddedName.append(" ");
}
todaysDate = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR ");
}
return todaysDate;
}
//CONVERT TO STRING
public static String RecordtoFile (RandomAccessFile store){
return null;
}
//WRITE INTO FILE AT RECORD LOCATION INDICATED BY ID
public static String WriteToFile (RandomAccessFile store){
return null;
}
}
The way I see it resolved is creating a Person class with a constructor that would take an int id and a String name as parameters.
This class would have a private void recordToFile method and you would only record one person per line in the id space name format.
Aditionally, in the FirstTr class you would have a private Person retrieveFromFile(int id) that would verify every line in the file and would return the Person with the given id or null if no person was found. That method could get a String name too in the parameters but it's really your call.
The way using a String[ ] could be useful too but you should decide.
I found what was causing the problem. When parsing, three of the five values that make up the string had been set to length 26, so this already created a string of length 78. The desired size is 71, and when the other two values are added, it can reach to 80 or 81. Changing what the strings are parsed or added to changed the length of the super string and no longer run into any issues. Thanks for the help

How should I add a search method in this code

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

While(true)-loop not breaking, scanner

I have a problem with some code. When I try to break my loop using "quit" it wont stop. If I begin with typing quit, it breaks as intended but the second time the loop runs and I type quit it's not breaking. What is the problem?
public static void interactionLoop() {
input = new Scanner(System.in);
String ssn = null;
String message = null;
int accountNr;
double amount;
while(true) {
for(Customers aCustomer : Customers.getCustomerList()) {
System.out.println(aCustomer.getName() + ", " + aCustomer.getSsn());
}
System.out.println("Choose a customer by using SSN.");
System.out.print(">> ");
ssn = input.nextLine();
if(ssn.equals("quit")) {
break;
}
Customers theChosenCustomer = Customers.getCustomerBasedOnSSN(ssn);
ArrayList<Accounts> accList = theChosenCustomer.getAccountList();
for(Accounts anAccount : accList) {
if(anAccount instanceof Savings) {
System.out.print("(Savings, " + anAccount.getAccountNr() + ")" + "\n");
}
if(anAccount instanceof Loans) {
System.out.print("(Loans, " + anAccount.getAccountNr() + ")" + "\n");
}
}
System.out.print("Enter the account that you want to work with using the account number:\n>> ");
accountNr = input.nextInt();
Accounts chosenAccount = theChosenCustomer.getSpecificAccount(accountNr);
System.out.println("Account balance: "+chosenAccount.getBalance());
for(Transaction t : chosenAccount.getTransaction()) {
System.out.println(t.getDateAndTime().getTime() +", " + t.getComment() +": " + t.getAmount());
}
System.out.println("\n");
System.out.print("Please enter the amount of money you wish you withdraw or deposit: ");
while(input.hasNext()) {
amount = input.nextDouble();
input.nextLine();
if(chosenAccount.isValid(amount)){
System.out.print("Please enter a comment: ");
message = input.nextLine();
Calendar transdatetime = Calendar.getInstance();
chosenAccount.makeTransaction(new Transaction(transdatetime,message,amount));
System.out.println("");
interactionLoop();
}
}
}
accountNr = input.nextInt();
From 2nd time onwards Scanner scans Integer from the Std InpuStream but then the newline remains which is taken by
ssn = input.nextLine();
due to which your program does not quit. Same goes for double. Better use
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
then use reader.readLine() and parse it into your desired data type. Eg. Integer.parseInt(reader.readLine())

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