Java array in for loop - java

I'm trying to create a menu for toll data entry that runs in a loop until the user requests to exit. The menu will ask the user to enter data which is stored in an array and keeps adding to the array until the user exits from the menu.
The menu should look as follows:
Toll Data Entry Menu
My menu works fine until asking the user to enter the trip date. The menu will continue to ask for each trip date up until the end of the length of the array (30 - arbitrary length).
I however want the menu to ask for the trip date, store the value entered by the user, then move onto entering the entry point, store value, etc and then loop back to the selection for the user to enter the above details again for a separate trip until they choose to exit. (I need to print these values later on) I'm not sure how to store the values from the user separately without prompting the user to enter all (30) values at the one time.
Should I be using an array or is there another way to store multiple values for a looped menu?
Hope my explanation is clear.

To fetch the complete set of details one at a time, you just need a single for loop as:
String[] datesA = new String [30];
int[] entryP = new int [30];
int[] exitP = new int [30];
for (int i = 0; i < 30; i++) {
System.out.println("Enter trip date: ");
datesA[i] = inputA.nextLine();
// User to enter entry point
System.out.println("Enter entry point: ");
entryP[j] = inputA.nextInt();
// User to enter exit point
System.out.println("Enter exit point: ");
exitP[k] = inputA.nextInt();
}
To improve the implementation though think over the lines of creating an object that includes all the details in one as :
class TollDataEntry {
String entryDate;
int entryPoint;
int exitPoint;
.... getter, setter etc.
}
and then use an array or Collection of this object to store the details of each TollDataEntry with those three values as a single entity.

Related

JAVA - Menu running in loop - How can I print out all choices?

I'm trying to learn JAVA and I'm working on a simple pizza order assignment running purely in text/console format.
I've made the user chose a pizza, but they need the option to add extra ingredients.
My thought was to use a for loop to show a toppings menu and then ask for a numbered input matching the ingredient they want to add.
I want them to be able to select several ingredients, why I'm doing it in a loop.
My code as of now looks like this:
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Everything works great, but I'd like to add a system.out.println() telling the user, what they've chosen as:
"You've added extra cheese - Would you like to add more?"
If so, I would like to expand that sentence: "You've added extra cheese & pepperoni - Would you like to add more?"
Could you help me by pointing me in a direction that might work? I'm not into any object related part of JAVA yet, purely text-based so far.
Thanks.
Solution provided by Adeel Ahmad
ArrayList<Integer> ingredients = new ArrayList<>();
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
ingredients.add(ingredientInput);
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Looking back it's so interesting to see which problems I struggled to solve, as now, a few months later, this seems so basic. But thanks anyway to everyone who helped :D
First off, you need to be able to store all the added ingredients in data container (e.g ArrayListor HashMap). Whenever user inputs an ingredient, just added that in your ArrayList
ArrayList<Integer> ingredients = new ArrayList<>();
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
ingredients.add(ingredientInput);
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Once you have collected all the user selected ingredients in your ArrayList, you can then iterate over it in a loop and construct your final message.
You could use something like this
String orderedSoFar = "";
boolean done = false;
do {
// read next ingredient from user
String currentIngredient = scanner.nextLine();
// if first extra ingredient
if(orderedSoFar.equals("")){
orderedSoFar += currentIngredient;
// if not first extra ingredient
} else {
orderedSoFar += " & " + currentIngredient;
}
System.out.println("Ingredients so far " + orderedSoFar);
System.out.println("Add more extra ingredients?");
// read choice to continue or not from user
done = Boolean.valueOf(scanner.nextLine());
}while(!done);

I need the input of the user to not skip the value 100

I'm currently working on a program for an O Level project where I have chosen to make a class management system. In my method class, I have various methods which control different functions of my program, such as one which collects the name of the students or one which displays a histogram of the student's grades. However, I have discovered a flaw in one of my methods. This is the method that lists the names of the students, one by one (which are saved in an array from a method that is executed before this method) and asks for the students marks. Here, the user is able to enter any number, which is inconvenient, considering that numerical grades normally range from 0-100. I have tried the following code but I have reached a predicament. The code does in fact stop the user from entering a mark over 100, but instead of allowing the user to re-enter a correct mark, it skips over to the next student, leaving the previous student without a mark. The following is said code:
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
marks[g] = Keyboard.readInt();
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
break;
}
}
}
Help would be very much appreciated and thank you in advance :)
Apologies if my English is not very good.
You almost got it - you need to read in your while-loop instead of breaking without reading. Also a do-loop would be more appropriate for not having to set an initial invalid value.
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
do {
System.out.println("Kindly enter a number that is less than 100");
marks[g] = Keyboard.readInt();
} while(marks[g]<0||marks[g]>100);
}
}
Set marks[ g ] to a number that isn't allowed before the loop, like - 1 then check the keyboard input inside of the while loop,
(and set It there every time as long as the while loop isn't stopped,
marks[g] = Keyboard.readInt();
and don't break the loop, as the loop would end anyways when the input is valid
The valid answers has to get into the array sequentially.
Use this simple trick to reset index [g] to the previous value
then you will overwrite the marks[g] value until you get a valid one:
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
g--; // Resetting index to previous value
break;
}

Java: Adding two random array elements for each category of a custom arraylist

I am providing the user with two random videos for each category they have selected.
I have an ArrayList of strings for the user preferences.
I also have an ArrayList of all of the videos in the database.
So I am trying to search through each of those category preferences one by one and find two random videos that fit into it those category.
I have implemented a solution that works (On a small dataset). But I am not sure it is optimal method considering there will soon be 500 videos, 50 categories and the user will be able to select 5 category preferences:
This is how I worked it out:
//Create a new array to store the videos
ArrayList<Video> videos = new ArrayList<>();
// Create counter for the position in the user preference array
int userPrefernceArrayIndex = 0;
// Create counter for number of successful category guesses
int numberOfSuccessfulGuesses = 0;
// Keep running until we have 2 videos for each of the user preferences
while (videos.size() < MainActivity.userPrefrencesStaticArraylist.size() * 2){
// Generate a random integer to get an entry random integer from the database array
Random rand = new Random();
int randomAlarmVidInt = rand.nextInt(MainActivity.allVideosFromDatabaseStaticArray.size());
// Find the category of the random video that was chosen
String categoryForRandomGuess = MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt).getVideoCategory();
// Find the current user video category we are testing for
String currentCategoryPreference = MainActivity.userPrefrencesStaticArraylist.get(userPrefernceArrayIndex);
// Check if category of the random video we got is the same as the category user
// preference we are testing for
if (categoryForRandomGuess.equals(currentCategoryPreference)){
// If it the the preference and the random video categories match add it to the video array
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
numberOfSuccessfulGuesses++;
// If the number of successful guesses is divisible by two then we have added two correct videos
// for that category so iterate to the next category
if (numberOfSuccessfulGuesses % 2 == 0){
userPrefernceArrayIndex++;
}
}
Because of the possibility for problems I hardly ever use a while loop or random unless necessary. I also see that guessing the number may not be the best solution memory wise. So I just want to make sure I am doing it the best way to avoid issues.
Thanks for your help
Yes you can optimize your solution as following:
Currently your iterations of while loop are getting wasted: Say categoryForRandomGuess and currentCategoryPreference both are equal to "Category 1".
So numberOfSuccessfulGuesses becomes 1, but userPrefernceArrayIndex stays 0. So if in next iteration if categoryForRandomGuess is "Category 4", the iteration will be wasted even if currentCategoryPreference can become equal to "Category 4" for some other value of userPrefernceArrayIndex, that is value other than 0.
I would Suggest using a HashMap<String,Integer> where String stores the video category and Integer stores the index of first video found in database of the category.
if the Integer value is -1, it will mean we have 2 videos and we are done with the category.
Now you can eliminate the variable userPrefernceArrayIndex and your code will be a lot shorter
So your code would be:
HashMap<String,Integer> mymap = new HashMap<>();
while (videos.size() < MainActivity.userPrefrencesStaticArraylist.size() * 2)
{
// Generate a random integer to get an entry random integer from the database array
Random rand = new Random();
int randomAlarmVidInt = rand.nextInt(MainActivity.allVideosFromDatabaseStaticArray.size());
// Find the category of the random video that was chosen
String categoryForRandomGuess = MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt).getVideoCategory();
//check if the hashmap has the category
if(mymap.get(categoryForRandomGuess) == null)
{
mymap.put(categoryForRandomGuess,randomAlarmVidInt);
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
}
else
{//-1 means we already have 2 videos of the category.
if(mymap.get(categoryForRandomGuess) == -1)
continue;
//if following condition is true, then its a duplicate video
if(mymap.get(categoryForRandomGuess) == randomAlarmVidInt)
continue;//skip the rest of loop and get new value of randomAlarmVidInt
else
{
mymap.put(categoryForRandomGuess,-1);//second video added
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
}
}
}

Java Error when using clearform(); on a save button

This is a Java Swing application to record CA results.The application will ask students to enter their Name, Student Number and CA Grade. The system must remember the Student
with the highest and Lowest Grades and display them on the input screen. I am currently receiving an error when using the
clearForm();
when coding the save button on my GUI.Subsequently the clearform(); and listResults(); methods are giving me errors.
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Creating a temp Result
result r = new result(nameTf.getText(), numTf.getText(), Integer.valueOf(resultTf.getText()));
// Saving it to the object array
registration[counter] = r;
// Checking the high value currently being stored, if it is higher than the new score, update
if (Integer.valueOf(highNum.getText()) < Integer.valueOf(resultTf.getText())) {
highNum.setText(resultTf.getText());
}
// Checking the low value currently being stored, if it is lower than the new score, update
if (Integer.valueOf(resultTf.getText()) < Integer.valueOf(lowNum.getText()) || counter == 0) {
lowNum.setText(resultTf.getText());
}
clearForm(); // clear the three input boxes when the user presses save
counter++; // Increment the student counter
listResults(); // List all stuudents currently stored in our object array
}
Asking this would be a lot easier with images.

states and capitals 2d array, java

here are my requirements:
Create (hard coded) the 50 states and their capital cities, using a 2
dimension array.
In the dialog box: ask the user either to enter the State or a City.
If the state is entered, find its capital city. If a city is entered,
find its State.
If not, found, issue an error message.
This should be in a Loop, until the user does not want to play
anymore.
I really don't know where to start, all I have done so far is create the array, I don't really get how to search the array, and spit out the corresponding state/capital.
Any help would be greatly appreciated.
Here is the code I have written so far.
import java.util.Scanner;
public class GuessStates {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
String[][] statesAndCapitols = {
{"Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"},
{"Montgomery","Juneau","Phoenix","Little Rock","Sacramento","Denver","Hartford","Dover","Tallahassee","Atlanta","Honolulu","Boise","Springfield","Indianapolis","Des Moines","Topeka","Frankfort","Baton Rouge","Augusta","Annapolis","Boston","Lansing","St. Paul","Jackson","Jefferson City","Helena","Lincoln","Carson City","Concord","Trenton","Santa Fe","Albany","Raleigh","Bismarck","Columbus","Oklahoma City","Salem","Harrisburg","Providence","Columbia","Pierre","Nashville","Austin","Salt Lake City","Montpelier","Richmond","Olympia","Charleston","Madison","Cheyenne"}};
System.out.println("Please enter a State or a capitol city.");
String userInput = input.nextLine();
}
}
thanks again!
try searching through the array with a for loop.
Using a for loop it keeps track and updates your current position of traversing the array.
Once you find the correct state or capital (by checking if userInput.equalsIgnoreCase(statesAndCapitols[x][y]), then take the current position you are at and retrieve the information needed.
I.E.
for(int x = 0; x < 2; ++x) //loop through states the first time, capitols the second
for(int y = 0; y < 50; ++y) //always 50, unless new states get added (obviously not a problem in this example, but useful to think about in future problems - YOUR DATA WILL ALMOST ALWAYS CHANGE.
if(userInput.equalsIgnoreCase(statesAndCapitols[x][y])
System.out.println(statesAndCapitols[x == 1 ? 0 : 1][y]);
In the array, I did x == 1 ? 0 : 1. That's a ternary operator, what it's saying is if x is equal to 1, use the value 0, otherwise use the value 1.
That's one way to go about this problem.
Another way would be to create your own Class/Datatype for the cities and states, that way you don't need to keep your arrays in sync, meaning you don't need to update 2 items for one change (like add another city/state combo).
Hope this helps a bit! :)
String entered_state=input.nextLine();
for(int i=0;i<50;i++){
if(statesAndCapitols[0][i].equals(entered_state)){
String searched_city=statesAndCapitols[1][i];
//print the city name
break;
}
}
if(i==50)
//print error
Same thing for searching state from entered city.

Categories