This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 2 years ago.
I currently have a programming assignment. In the assignment, I have to have two array that I need to store the data of a store's stock with. I use the first array for the Manager to access. I use the second array for the Cashier to access.
The manager may add the code, name, price, and quantity of up to 15 items.
The cashier may add the code and quantity of any item. If the code of the does not exist in the manager's array, the program will automatically exit.
The elements of the arrays are not in the same order for both array lists. So how do I make sure that the item code that the cashier has entered, actually exists in the Manager's array?
This is how I have declared the arrays:
String[] stockItemCode = new String[15];
String[] stockItemName = new String[stockItemCode.length];
int[] stockItemQuantity = new int[stockItemCode.length];
double[] stockItemPrice = new double[stockItemCode.length];
String[] saleItemCode = new String[stockItemCode.length];
String[] saleItemName = new String[stockItemCode.length];
int[] saleItemQuantity = new int[stockItemCode.length];
double[] saleItemPrice = new double[stockItemCode.length];
This is how the manager enters items:
// 3- The manager:
// 3.1- The manager has to login to add the items to the inventory list. The username and password are "Manager" and "Man_2020" respectively.
if (username.equals(managerUsername) && password.equals(managerPassword))
{
// 3.2- Once the manager is logged in, he will enter the item's code, name, quantity, and price.
do
{
System.out.println("Please enter item code: ");
stockItemCode[stockItemLimit] = sc.next();
System.out.println("Please enter item name: ");
stockItemName[stockItemLimit] = sc.next();
System.out.println("Please enter item quantity (numbers only): ");
stockItemQuantity[stockItemLimit] = sc.nextInt();
System.out.println("Please enter item price (numbers only): ");
stockItemPrice[stockItemLimit] = sc.nextDouble();
stockItemLimit++;
// 3.3- After entering the above information for each item, the program prompts the manager to continue or logout of his account. He has to use 'L' or 'S' to sign-out.
System.out.println("Would you like to stop the program? Entering S or L will stop the program");
logoutPrompt = sc.next().charAt(0);
}
while(!(logoutPrompt == 'L' || logoutPrompt == 'S'));
}
This is how I have tried to compare the elements of the arrays (I know it's wrong, but I don't know why. I'm very new to programming).
// 4- The sales employee:
// 4.1- The sales employee logs in to scan the sold items and print the receipt. The username and password are "Sales" and "Sale_2020" respectively.
else if (username.equals(salesUsername) && password.equals(salesPassword))
{
i = 0;
// 4.2- The sales employee, enters the *code* and the *quantity* of the sold item.
do
{
System.out.println("Please enter item code: ");
saleItemCode[i] = sc.next();
System.out.println("Please enter item quantity (numbers only): ");
saleItemQuantity[i] = sc.nextInt();
saleItemName[i] = stockItemName[i]; //This is the problem
saleItemPrice[i] = stockItemPrice[i]; //This is the problem
// 4.3- The program calculates the total price of the transaction, by using the quantity and the price of the sold items.
if(saleItemCode[i] == stockItemCode[i])
{
saleItemPrice[i] = stockItemPrice[i] * saleItemQuantity[i];
// 4.4- The program has to deduct the sold quantity of the items from the stock list.
stockItemQuantity[i] = stockItemQuantity[i] - saleItemQuantity[i];
// 4.5- After entering each item, the employee is prompted to continue adding the item to the receipt, or print it (by using 'P').
System.out.println("Would you like to print the receipt by entering P? Enter anything else to continue adding items.");
logoutPrompt = sc.next().charAt(0);
}
else
{
// If the code is entered incorrectly, the program skips to 4.5.
System.out.println("Would you like to print the receipt by entering P? Enter anything else to continue adding items.");
logoutPrompt = sc.next().charAt(0);
}
i++;
}
while(logoutPrompt != 'P');
Also, whenever I try to print the information of the stock's items while in the Cashier's loop, the arrayElements return as null as if they do not exist even though they clearly do.
for(i = 0; i <= stockItemLimit; i++) //COME HERE
{
int indexNumb = i+1;
System.out.println(indexNumb + "\t" + saleItemCode[i] + "\t" + saleItemName[i] + "\t" + "$" + saleItemPrice[i] + "\t" + saleItemQuantity[i]);
}
All help would be appreciated.
You find an element in an unsorted array by looping over all elements and comparing each.
int stockitemindex = -1;
for(int searchindex = 0; searchindex <= stockItemLimit; searchindex++) {
if (stockItemCode[searchindex].equals(saleItemCode[i])) {
stockitemindex = searchindex;
break;
}
}
It's not clear from your description why the arrays of stockitem and saleitem have the same size. It's not even clear if you need an array for saleitem. Just a String code and int quantity would seem enough.
Also in your loop at the end of your question, you access saleitem array, not stockitem array, that's why you get null contents.
Related
I'm fairly new at programming. Currently im working on a uni project to create a basic text game using java. The problem im having is trying to figure out how to implement a business rule that does not allow a user to enter the same name. I have it set up so the scanner reads into the array. I'm using Java and this is my first time using the forum so i greatly appreciate any help given and thank all of you in advance!:)
And apologies for the poor formatting i dont know how to post properly yet.
try {
// Takes in the number of players
int noOfPlayers;
Scanner s = new Scanner(System.in);
System.out.println("Enter number of players between 2 and 4");
noOfPlayers = s.nextInt();
s.nextLine();
if (noOfPlayers < 2 || noOfPlayers >= 5) { // limits number of players enter no less than 2 and no greater than 4
System.out.println("Nope wrong number");
enterInfo();
s.close();
return;
} else {
// array for storing player names
String[] names = new String[noOfPlayers];
// iterates through the array depending how many players are selected
// and takes in String input
for (int counter = 0; counter < noOfPlayers; counter++) {
System.out.println("Enter name of player : " + (counter + 1));
names[counter] = s.nextLine();
// fix this to stop same name sbeing entered
//if(names.equals(names)) {
// System.out.println("Enter a different name");
// counter--;
// }
}
}
s.close();
} catch (Exception e) {
System.out.println("Problem");
}
}
How about use Set? Set has to have all different things.
Like in Array [kim,lee,kim,park] but in Set [kim,lee,park]
input kim => Array [kim] set[kim] lenth 1 == size 1
input lee => Array [kim,lee] set[kim,lee] lenth 2 == size 2
input kim => Array [kim,lee,kim] set[kim,lee] lenth 3 != size 2
then all you have to do is tell them "make another name plz"
String name = s.nextLine();
names[counter] = name;
Set<String> set = new HashSet<String>();
set.add(name)
if(names.length != set.size())
{
System.out.println("Enter a different name");
counter--;
}
I hope you understand my poor explanation.
I'm trying to get input from the user to select players from an ArrayList. All the players in the ArrayList have a unique ID the user selects 5 - 8 players to start the program but I do not want to allow the user to input the same ID again as it will have a duplicate.
Heres what I m trying to do
I still am not getting this I tried this
public void SelectAthlete(){
Data ath = new Data();
ath.athleteData();
boolean choice = true;
int p=0;
String id;
int value =0;
Scanner input = new Scanner(System.in);
System.out.println();
do{
System.out.println();
System.out.print("\tEnter the number of Participants you want to Compete: ");
p=input.nextInt();
System.out.println("\tYou have Decided to compete with" +" " + p + " " +"Athletes");
if(p>=5 && p<=8){
System.out.println("\tEnter the Athlete ID : ");
for (int i=0;i<p;i++){
value=0;
id = input.next();
if(id.substring(0,1).equals("R") || id.substring(0,1).equals("P")){
for(int k=0;i<Data.AthleteData.size();k++)
{
if(Data.AthleteData.get(k).getID().contains(id))
{
value++;
choice = Data.Inputlist.add(id);
}
else if (!choice)
{
value--;
System.out.println("Please Enter Unique Value");
input.nextLine();
}
for(int j = 0; j<Data.AthleteData.size();j++)
{
if(id.equals(Data.AthleteData.get(j).getID()))
{
value++;
}
}
}
}
if(value!=0)
{
Data.Inputlist.add(id);
}
else
{
System.out.println("Enter a valid ID (in UPPER Case)");
input.nextLine();
i--;
}
}
choice = false;
}
else{
System.out.println("\n\tHowever You need to have
atleast 5 Athletes or atmost 8 Athletes to Start a game.");
input.nextLine();
}
for (int m=0;m<Data.AthleteData.size();m++){
if (Data.Inputlist.contains(Data.AthleteData.get(m).getID()))
{
System.out.println(Data.AthleteData.get(m));
}
}
}while(choice);
You could use a HashSet and see the response of the add method as follows:
Set<String> someSet = new HashSet<String>();
boolean isUnique = someSet.add("abc");
System.out.println(isUnique); // this will output true as abc does not already exist in the set and add operation was successful
isUnique = someSet.add("abc");
System.out.println(isUnique); //this will output false as abc already exists in the set and hence cannot be added again
But since you are using a Custom Object and not a String, you will need to declare the set as follows:
Set<YourClass> someSet = new HashSet<YourClass>();
In addition to that you will need to make sure that the equals method in YourObject class is implemented correctly too.
You can refer to these links for more information about equals: http://www.geeksforgeeks.org/overriding-equals-method-in-java/
and
https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/
There are many ways you can do this.
1.) After taking number you can loop back to check if it exist in the Arraylist.(NOT RECOMMENDED) as it have high runtime complexity.
2.) Simply you can use contains() method of arraylist to check if it is present already.
3) You can use a bitset for number and set it true when ever they are assigned.Later you can compare it with the bool value to check if it set or not. see https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html for more info on bitset
this is my first time posting a question here. I'm having a problem with the scanner method. this is the code I'm using
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
do {
System.out.println(
"\nPlease enter the book ID of the book that you wish to take out (Press 9 to exit to the main menu)");
if (input.nextInt() == 9) {
successful = true;
break;
}
int bookID = input.nextInt();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
do {
System.out.println("\nHow long would you like to loan the book for (20 Days maximum):");
int durationOnLoan = input.nextInt();
if (durationOnLoan <= 20 && 1 <= durationOnLoan) {
Books.get(i).setDurationOnLoan(durationOnLoan);
successful = true;
} else {
System.out.println("The number of days you have entered is invalid");
}
} while (successful == false);
System.out.println("\nThe book " + Books.get(i).getTitle() + " is now on loan");
Books.get(i).setOnLoan(true);
Books.get(i).setNumOfLoan(Books.get(i).getNumOfLoans() + 1);
successful = true;
}
}
the project I'm working on is a library array list which holds book objects (the array list works fine).
The for loop is used to iterate through the library array list to see if the book is there.
Whenever i run the program and enter a valid input for the book id, this happens
Please enter the book ID of the book that you wish to take out
101// this is my input which is valid
101// i have to enter it this second time for it to work and continue to the next piece of code
any thoughts? could it be a problem with the do while loop? or the for loop through the array list
In this line
if (input.nextInt() == 9) {
You read the number, and provided it's not 9, you continue. But you also discard it. which is why you have to enter it again. A simple solution is to use a variable which is what you have done already.
int bookID = input.nextInt();
if (bookID == 9) // check the save value so you don't have to enter it twice.
break;
If you are wondering, how could I have solved this myself? The answer is to use your debugger as this will should exactly what each line of code is doing.
I'm trying to split my variables and enter my student data in so I can move on with my grade calculation program, but my second time splitting the entered string, there is a problem and I cannot figure out what is the cause of it.
Users will enter information in that looks like this
John Denver: e100 q70 q50 h100 e100 e90 h80 q60 h100
The program needs to split apart all of this data and get the name entered into an array, and then the exam scores, quiz scores and homework scores represented by the "e", "q" or "h" in the entered data.
import java.util.Scanner;
public class GradeCalcWithArrays { /*
* Daniel The purpose is to calculate
* entered grades
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean done = false;
boolean quit = false;
int choice = 0;
int maxstudents = 200;
int[] examstats = new int[3]; /*
* Array created to store the information
* entered for exams
*/
int[] quizstats = new int[3]; /*
* Array created to store the information
* entered for quizzes
*/
int[] homeworkstats = new int[3]; /*
* Array created to store the
* information entered for homework
*/
String[] studentnames = new String[maxstudents]; /*
* Array created to
* store the student
* name information
* entered
*/
System.out.println("Welcome to GradeBook!");
System.out.println("Please provide grade item details");
System.out.print("Exams (number, points, weight):");
examstats[0] = s.nextInt(); // inputs exam number
examstats[1] = s.nextInt(); // inputs exam points
examstats[2] = s.nextInt(); // inputs exam weight
System.out.print("Quizzes (number, points, weight):");
quizstats[0] = s.nextInt(); // inputs quiz number
quizstats[1] = s.nextInt(); // inputs quiz points
quizstats[2] = s.nextInt(); // inputs quiz weight
System.out.print("Homework (number, points, weight):");
homeworkstats[0] = s.nextInt(); // inputs homework number
homeworkstats[1] = s.nextInt(); // inputs homework points
homeworkstats[2] = s.nextInt(); // inputs homework weight
double[] examscores = new double[examstats[0]];
double[] quizscores = new double[quizstats[0]];
double[] hwscores = new double[homeworkstats[0]];
System.out.println("--------------------");
do {
System.out.println("What would you like to do?");
System.out.println(" 1 Add student data");
System.out.println(" 2 Display student grades & statistics");
System.out.println(" 3 Plot grade distribution");
System.out.println(" 4 Quit");
System.out.print("Your choice:");
choice = s.nextInt(); /*
* Choice will determine what the next course of
* action will be with the program
*/
if (choice == 1) {
System.out.println("Enter student data:");
for (int i = 0; i <= maxstudents; i++) {
System.out.print("Data>");
String dataentry = s.nextLine();
String[] firstsplit = dataentry.split(":");
studentnames[i] = firstsplit[0];
String[] secondsplit = firstsplit[1].split(" ");
for (int j = 0; j <= maxstudents; j++) {
String c;
c = secondsplit[j].substring(0, 1);
if (c == "e") {
secondsplit = secondsplit[j].split("e");
examscores[i] = Double.parseDouble(secondsplit[j]);
}
if (c == "q") {
secondsplit = secondsplit[j].split("q");
quizscores[i] = Double.parseDouble(secondsplit[j]);
}
if (c == "h") {
secondsplit = secondsplit[j].split("h");
hwscores[i] = Double.parseDouble(secondsplit[j]);
}
if (dataentry.equals("done")) {
break;
}
}
}
}
if (choice == 2) {
}
if (choice == 3) {
}
if (choice == 4) {
quit = true;
System.out.println("Good bye!");
}
} while (quit == false);
}
}
I get an error that says: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GradeCalcWithArrays.main(GradeCalcWithArrays.java:83)
Can someone help me fix this and tell me if my program is going to work?
One thing that is wrong is that you have maxstudents set to 200, you allocate the studentnames array with size 200, but that means that the valid subscripts are 0 through 199, but your for loop uses a less than or equal test against 200:
`for (int i = 0; i <= maxstudents; i++)`
That means that i is 200 on the last iteration, so in that iteration your code will effectively execute studentnames[200] = firstsplit[0]; and that will cause an ArrayIndexOutOfBoundsException.
The above, however, will be a problem if you reach the 200th iteration without breaking out of the for loop. Looking at the code, I do see that you are attempting to break if the input is "done", however that break statement is actually inside the nested for loop, so it does not break out of the outer loop. That test really should happen before you do the first split. There's no reason to even try to split if the input was "done", so also no reason to go into the nested for loop.
There are additional problems as well: The nested for loop should not be testing against maxstudents because it's the number of grades that you care about. I'll leave the rest of them for you to figure out - with a hint about one of them: you should be checking your input for errors.
First off I'm sorry if this is a wierd one, but I don't exactly know what I'm trying to do in coding terms.
To clarify what I wish to do, I want to know a way to "Save" the value of receipt to either a list/set/array then go trough the process that determined the value of receipt and save that to the list again, and when I print the list the two different values of receipt are printed after eachoter.
Lets say first time the value of receipt was determined it was equal to x, then after I've saved that to a list and gone trough the same value determening process receipt= y and I add that to the list. Would it print: x and then y. Or y and y? And if it prints the new value of receipt twice, how do I make it print the two different values after eachother?
import java.util.Scanner;
public class TicketV005
{ // start of public class
public static void main (String [] args)
{ // start of main
Scanner keyboard = new Scanner(System.in);
int printedTickets,ticketTotal;
String fareType, purchaseLoc;
String answer1 =("null");
String receipt =("null");
int zoneAmount = 0;
double price = 0;
int answer2 = 0;
System.out.print("How many tickets do you wish to buy?(Answer with a number please.) ");
ticketTotal = keyboard.nextInt();
printedTickets = 0;
while (ticketTotal <= 0)
{
System.out.println("\nIncorrect input, try again.");
System.out.println("How many tickets do you wish to buy?(Answer with a number please.) ");
ticketTotal = keyboard.nextInt();
}
while(ticketTotal !=printedTickets )
{
System.out.print("Welcome! Are you buying a reduced fare ticket?(y/n) ");
answer1 = keyboard.next();
if (answer1.equals("y"))
fareType=("reduced fare");
else if (answer1.equals("n"))
fareType=("standard fare");
else
fareType=("null");
while (fareType.equals("null"))
{
System.out.println("\nIncorrect input, try again.");
System.out.println("Welcome! Are you buying a reduced fare ticket?(y/n) ");
answer1 = keyboard.next();
}
System.out.println("Would you like to purchase your ticket at 1. the automated services or at 2. the cashier? ");
answer2 = keyboard.nextInt();
if (answer2 ==1)
purchaseLoc=("automated services");
else if (answer2 ==2)
purchaseLoc=("cashier");
else
purchaseLoc=("null");
while (purchaseLoc.equals("null"))
{
System.out.println("\nIncorrect input, try again.");
System.out.println("Would you like to purchase your ticket at 1. the automated services or at 2. the cashier? ");
answer2 = keyboard.nextInt();
}
System.out.println("How many zones will you be travelling? (1-3) ");
zoneAmount = keyboard.nextInt();
while (zoneAmount <= 0 || zoneAmount > 3 )
{
System.out.println("\nIncorrect input, try again.");
System.out.println("How many zones will you be travelling? (1-3) ");
zoneAmount = keyboard.nextInt();
}
//Start of reduced fare
if (answer1.equals("y") && answer2 == 1 )
{ // Start of automated services reduced fare
for (int i= 1 ; i <= 3 ; i++)
{
if (zoneAmount == i)
price=(10*i)+10;
}
} //end off automated services reduced fare
if (answer1.equals("y") && answer2 == 2)
{ // Start of cashier reduced fare
for (int i= 1 ; i <=3 ; i++)
{
if (zoneAmount == i)
price=(14*i)+14;
}
} //End of cashier reduced fare
//End of reduced fare
//Start of standard fare
if (answer1.equals("n") && answer2==1)
{ //Start of standard fare automated services
for (int i = 1; i <=3 ; i++)
{
if ( zoneAmount ==i)
price=(18*i)+18;
}
} // end of standard fare automated servies
if (answer1.equals("n") && answer2==2)
{ // Start of standard fares cashier
for (int i = 1; i <=3 ; i++)
{
if( zoneAmount == i)
price=(22*i)+22;
}
} // End of standard fares cashier
//End of standard fare
System.out.println("");
receipt = (zoneAmount+" zone(s), "+ fareType+", bought at: "+ purchaseLoc+". Your price: "+price+" SEK.");
System.out.println(receipt);
printedTickets++;
System.out.println(""); //Empty line for when/if it repeats
} // end of while printedTickets is not equal to ticketTotal
}// end of main
}// end of public class
Edit1: Included full code for clarity.
Edit2: Better Clarification
It looks like you're asking two questions. One relates to whether you can save a variable and the other is about how to have a bunch of things aggregated together. From your code it's not clear what your aims are.
In java, the things you declare, like
String receipt
are references. This means they keep track of a piece of data. However, other things can also keep track of that same piece of data. So:
String receipt1 = "100EUR";
String receipt2 = receipt1;
In the above code, there's only one thing in memory with "100EUR" in it, and both receipt1 and receipt2 are looking at it. If something came along and modified one of them
receipt1 = "200EUR";
The other would be unaffected.
System.out.println(receipt1);
System.out.println(receipt2);
// output would be
200EUR
100EUR
In a lot of cases once something has been assigned to a reference via the = symbol, you can imagine that the reference is always going to have access to it, unchanged until the next time the = symbol is used to assign the reference to point to something else. However, in Java objects can change state, so if you had
List<String> myList = new ArrayList<String>():
and things started calling methods on myList to modify its contents, then the myList reference would feel like it's referring to something that changes. The reference itself is not changing, just the object it points to.
I brought the subject round to lists since you probably are trying to keep track of all receipts somewhere after creating them, and the list has an add function that will do that nicely for you.
If you want to print out the whole contents of the list, then you could have a loop:
for(String line:myList) {
System.out.println(line);
}
You can use a StringBuilder to append the new Strings. Alternatively, you can simply concatenate tow Strings with the +-Operator, but this is really inefficient in terms of execution time.
First you can declare an ArrayList of Strings:
ArrayList<String> receipts = new ArrayList<>();
Then add the value of the receipt variable:
receipts.add(receipt);
At the end you can print all elements of ArrayList
for (String s : receipts)
System.out.println(s);
I would use a StringBuilder, and keep on adding what you want in the loop, adding a newline to it at the end of the loop:
public static void main(String[] args)
{
StringBuilder receipt;
//Other variable initializations
Also, your while loop could probably be changed to a for loop:
for (int i = 0; i < ticketTotal; i++)
{
receipt.append(zoneAmount);
receipt.append(" zone(s), ");
receipt.append(fareType);
receipt.append(", bought at: ");
receipt.append(purchaseLoc);
receipt.append(". Your price: ");
receipt.append(price);
receipt.append(" SEK.\n");
}
Then when you need to just print your StringBuilder:
System.out.println(receipt.toString());