Searching arrayLists - java

Hi im creating a simple mp3 database that stores a trackNum, name and duration. I need to search an array list and get the index of the search.
Here is what i have at the moment.
//My methods
public void searchTrackNum(Intager trackNumber){
System.out.println(trackNum + ": " + name[index] + " " + duration[index]);
}
public void searchName(String name){
System.out.println(trackNum + ": " + name[index] + " " + duration[index]);
}
//Using the methods
case 4:
System.out.println("What name would you like to search for: 1-Track Number or 2-Name");
int question = in.nextInt();
if(question == 1){
System.out.println("Please enter the track Number?");
meth.searchTrackNum(in.nextInt());
}
if(question == 2){
System.out.println("Please enter the Name?");
meth.searchName(in.next());
}
else{
System.out.println("Pease enter 1 or 2.");
}
break;
How do i search an arrayList
I need to be able to get the index of the search to add the name of the track and the duration of it.

I suggest using
int index = Arrays.asList(names).indexOf(nameToLookFor);
If the names are sorted, you can use binarySearch instead.

Related

While Loop Error Is Repeating My User Input Prompt

My goal in this project is to be able to ask a user if they want to add a mechanic and bay number to their respective ArrayLists. My code works fine, but there is one annoying problem. When the while loop that starts all of the code over again runs, the prompt for if they would like to edit the schedule prints twice, once without allowing a user response. I realise there is a lot of code to read but I will print it all here, and the bug that I get every time. It would mean a lot if someone could take the time to tell me what I need to fix.
Code:
// Import packages and create main function
import java.util.Scanner;
import java.util.ArrayList;
public class schedule{
public static void main(String []args){
// Creates scanner and ArrayLists
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> mechanics = new ArrayList<Integer>();
ArrayList<Integer> bays = new ArrayList<Integer>();
boolean edit = true;
while(edit == true){
edit = editSchedule(scanner);
// Runs AddorRemove or ends program based on user's previous choice
if(edit == true){
if(AddorRemove(scanner) == true){
add(scanner, mechanics, bays);
}
else{
remove(scanner, mechanics, bays);
}
}
else{
System.out.println("Have a nice day!");
}
}
}
// Asks user if they want to edit the schedule
public static boolean editSchedule(Scanner scanner){
String answer = "b";
while(!(answer.equals("y")) || answer.equals("n")){
System.out.print("Would you like to edit the schedule? (y/n): ");
answer = scanner.nextLine();
if(answer.equals("y") || answer.equals("n")){
break;
}
else{
System.out.println("Invalid response.");
}
}
if(answer.equals("y")){
return true;
}
else{
return false;
}
}
// Asks user if they want to add or remove an element
public static boolean AddorRemove(Scanner scanner){
String aor = "b";
while(!(aor.equals("a")) || aor.equals("r")){
System.out.print("Do you want to add or remove a mechanic and bay? (a/r): ");
aor = scanner.nextLine();
if(aor.equals("a") || aor.equals("r")){
break;
}
}
if(aor.equals("a")){
return true;
}
else{
return false;
}
}
// Checks to see that elements are not present already and adds element to the mechanic and bay ArrayLists
public static void add(Scanner scanner, ArrayList<Integer> mechanics, ArrayList<Integer> bays){
System.out.print("Enter the mechanic's ID number: ");
int mechanic = scanner.nextInt();
System.out.print("Enter the bay number: ");
int bay = scanner.nextInt();
boolean shouldAdd = true;
for(int i=0; i<=mechanics.size()-1; i++){
if(mechanic == mechanics.get(i)){
System.out.println("Mechanic " + mechanic + " is already booked.");
shouldAdd = false;
}
}
for(int j=0; j<=bays.size()-1; j++){
if(bay == bays.get(j)){
System.out.println("Bay " + bay + " is already booked.");
shouldAdd = false;
}
}
if(shouldAdd == true){
mechanics.add(mechanic);
bays.add(bay);
System.out.println("Mechanic " + mechanic + " booked for bay " + bay + ".");
}
else{
System.out.println("Could not book mechanic " + mechanic + " in bay " + bay + ".");
}
}
// Removes an element from the mechanic and bay ArrayLists
public static void remove(Scanner scanner, ArrayList<Integer> mechanics, ArrayList<Integer> bays){
System.out.println("remove");
}
}
That is the code so far. Don't worry about the remove function, as I haven't added anything to it yet. Mainly focus on the main function and the editSchedule function, which is where something goes wrong. I will now paste the problem I am having with the output.
Would you like to edit the schedule? (y/n): y
Do you want to add or remove a mechanic and bay? (a/r): a
Enter the mechanic's ID number: 1
Enter the bay number: 3
Mechanic 1 booked for bay 3.
Would you like to edit the schedule? (y/n): Invalid response.
Would you like to edit the schedule? (y/n):
All I want to know is what is making the code repeat the phrase "Would you like to edit the schedule? (y/n):" and then adding "Invalid response." If any of you need clarification or further explanation, please let me know. Thanks!
When you use scanner.nextInt() it doesn't complete the line. See this test as an illustration:
#Test
public void testScanner() {
Scanner scanner = new Scanner("1\n2\n3\n4\n");
System.out.println("nextLine: [" + scanner.nextLine() + "]");
System.out.println("nextInt: [" + scanner.nextInt() + "]");
System.out.println("nextLine: [" + scanner.nextLine() + "]");
System.out.println("nextLine: [" + scanner.nextLine() + "]");
}
It produces:
nextLine: [1]
nextInt: [2]
nextLine: []
nextLine: [3]
So after the add() method returns, you have a line ending that the scanner will read as a blank line. That gives you the Invalid response message.

How to calculate input from an array

I'm having trouble with this array I'm working on. In the for loop, I need to somehow calculate an on base percentage. The element at index 0 will store the OBP. How can I retain the information the user inputs to calculate the OBP? Thank you.
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[index] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[index] = keyboard.nextInt();
}
I'd suggest a HashMap inside a HashMap for this use case.
Before loop:
HashMap<Integer, HashMap<String, Integer>> years = new HashMap<>();
HashMap<String, Integer> entry = new HashMap<>();
For every input from user's keyboard (example):
entry.put("hits", 5);
years.put(2019, entry);
entry.put("walks", 10);
years.put(2019, entry);
In the end you get a result such as:
{2019={hits=5, walks=10}}
Retrieving results is simple too:
// retrieve map of data for a specific year:
years.get(2019)
result: {hits=5, walks=10}
// retrieve specific data for a specific year:
years.get(2019).get("hits")
result: 5
You will want to store the values entered by the user in a variable. Instead of having an array of inputs (which is one way of doing it) - you can simply store each value in a separate variable and then do the calculation at the end.
See my sample code below:
public static void main(String args[]) {
// let's take incoming values from the user for our calculations
Scanner keyboard = new Scanner(System.in);
// we'll use this array to store the values entered by the user
// in position zero of the array we'll store the OBP
// in positions 1-5 we'll store the inputs as entered by the uesr
float[] values = new float[6];
// we'll use this flag to determin if we should ask the user input again or quit the program
boolean letsDoThisAgain = true;
while (letsDoThisAgain){
System.out.println("Enter a Year: ");
int year = keyboard.nextInt();
System.out.println("For Year " + year + ", enter number of:");
System.out.println("Hits: ");
values[1] = keyboard.nextFloat();
System.out.println("Walks: ");
values[2] = keyboard.nextFloat();
System.out.println("Number of times player has been hit by a pitch: ");
values[3] = keyboard.nextFloat();
System.out.println("Number of at bats: " );
values[4] = keyboard.nextFloat();
System.out.println("Number of sacrifice flies: ");
values[5] = keyboard.nextFloat();
// calculate the OBP
values[0] = (values[1] + values[2] + values[3] - values[5] ) / values[4]; // or however you calculate it
System.out.println("OBP: " + values[0]);
System.out.println("------");
System.out.println("Do you want to do it again? (y/n): ");
String quitOrDoItAgain = keyboard.next();
if( "n".equalsIgnoreCase(quitOrDoItAgain)){
letsDoThisAgain = false;
}
}
System.out.println("Thanks for playing... Good Bye!");
}
By the usage of a proper data structure like Map<string year, object playerstats> including OBP calculation on the object player stats before storing but this is an in-memory solution only last till the program is running if you like persistent then look on the database side
Also from the way you have presented your code it seems you are over-writing the value at year[index] always.
if you just want to use an array, then go like
years[index] = year[index] (math operation) keyboard.nextInt()

My java arrays overwrite existing elements

So I am relatively new to Java language but am trying to get better so I can add more skills to my resume. I am currently focusing on arrays and I am writing a program that I want to be able to use with a barcode scanner or keyboard in order to keep track of Cultural Enrichment credits (inspired by my school's need of one ). I thought it might be a neat starting program to wrap my head around array use but I am having a problem with the two arrays. They keep overwriting the new values entered. I have been googling and trying things but I am still not able to get them to work properly and would like to ask for help from more seasoned coders. I know my output method is rather lazy but it'll do for what I would like to see for the output format.
Here is my code:
public static void main(String []args)throws InputMismatchException
{
Scanner user_input = new Scanner( System.in );
int n = 0;
String Name;
int CEU;
String[] users = new String[5];
String[] numbers = new String[6];
Object end = null;
Object print = null;
System.out.print("Enter value for CEU: ");
CEU = user_input.nextInt();
while (n >= 0)
{
/* Loop*/
System.out.println("Scan ID or type **end,print** ");
numbers[n] = user_input.next();
if ("end".equals(users[n] ))
{
System.out.print("Program terminated.");
System.exit(0);
}
if ("print".equals(numbers[n]))
{
System.out.print("CEUs: " + CEU);
System.out.print(" ID#: " + numbers[0]);
System.out.print(" Name: " + users[0]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[1]);
System.out.print(" Name: " + users[1]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[2]);
System.out.print(" Name: " + users[2]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[3]);
System.out.print(" Name: " + users[3]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[4]);
System.out.print(" Name: " + users[4]);
}
else
{
System.out.print("Enter Name: ");
users[n] = user_input.next();
}
}
}
Inside your loop you need to increment n as it is always 0. Use: n++; at the last line of code inside the while loop.
n isn't being incremented. Because n never changes, it will override the same part of the array each time the loop executes. Also, it seems like you may get a outofbounds error later, because i will keep increasing. Soon it will be greater than the max index of the numbers array, so it will return the error. You should try adding in some code that stops the error from happening.

How to show the number as astrisk [duplicate]

This question already has answers here:
Displaying asterisk depending on the number entered [closed]
(3 answers)
Closed 8 years ago.
So I have to show the number of total grades(which i have calculated already) as astrisk. the output should be like this,
A=******
B=******
C=******
D=*****
And this is my code:
import java.io.*;
import java.util.*;
public class grades
{
public static final void main(String args[]) throws FileNotFoundException
{
System.out.println("name");
Scanner myScanner = new Scanner(new File("students.txt"));//Creating new scanner object
int lineNumber =1;//Line Number for each student.
while (myScanner.hasNext())
{
String firstName = myScanner.next();//Scanning student first name and storing in the string
String lastName = myScanner.next();// Scanning student last name and storing in the string
String athleteFlag=myScanner.next();//Scanning for verification of athlete and storing in the string
String athlete= "Y";
String notAthlete = "N";
//if else statement to declare if student is a athlete
if (athleteFlag.equals(athlete))
{
athleteFlag="YES";
}
else if(athleteFlag.equals(notAthlete))
{
athleteFlag="NO";
}
int quiz1=myScanner.nextInt();// Grades on Quiz 1
int quiz2=myScanner.nextInt();// Grades on Quiz 2
int quiz3=myScanner.nextInt();// Grades on Quiz 3
int quiz4=myScanner.nextInt();// Grades on Quiz 4
int quiz5=myScanner.nextInt();// Grades on Quiz 5
int test1=myScanner.nextInt();// Grades on Test 1
int test2=myScanner.nextInt();// Grades on Test 2
//student quiz average
double quizAverage = (double)(quiz1+quiz2+quiz3+quiz4+quiz5)/5;
//Overall Numerical Grade
float overallNumericalGrade =(float)(quizAverage+test1+test2)/3;
//Students letter Grade, eligibility and counting number of each grade
String grade;
String eligibility;
int gradeA=0;
int gradeB=0;
int gradeC=0;
int gradeD=0;
int gradeF=0;
if(overallNumericalGrade>=90.0)
{
grade="A";
eligibility ="YES";
gradeA++;
}
else if(overallNumericalGrade>=80.0)
{
grade = "B";
eligibility ="YES";
gradeB++;
}
else if(overallNumericalGrade>=70.0)
{
grade = "C";
eligibility ="YES";
gradeC++;
}
else if(overallNumericalGrade>=60.0)
{
grade = "D";
eligibility ="NO";
gradeD++;
}
else
{
grade = "F";
eligibility ="NO";
gradeF++;
}
System.out.println(lineNumber + " "+lastName+","+firstName+"/ "+athleteFlag+ "/ " + eligibility +
" / " +"Grades on all quiz "+ quiz1+ " "+quiz2+" "+quiz3+" "+ quiz4+" "+quiz5+" "+test1+" "+
test2+ " /" +"quiz average is " + quizAverage +"\n " + "Overall Numerical grade is " +
overallNumericalGrade+" / "+ "Student letter Grade is " + grade);
lineNumber++;
}
}
}
I just dont know how to output this. Any help will be appriciated. Thanks in advance.
Assuming the total of all grade is overallNumericalGrade and that you want to display it as * in the last output (as this is the only output in your code), You could do
System.out.println(lineNumber + " "+lastName+","+firstName+"/ "+athleteFlag+ "/ " + eligibility +
" / " +"Grades on all quiz "+ quiz1+ " "+quiz2+" "+quiz3+" "+ quiz4+" "+quiz5+" "+test1+" "+
test2+ " /" +"quiz average is " + quizAverage +"\n " + "Overall Numerical grade is " +
String.valueOf(overallNumericalGrade).replaceAll(".", "*")+" / "+ "Student letter Grade is " + grade);
The important part is here
String.valueOf(overallNumericalGrade).replaceAll(".", "*")
Where I convert the total value to a String then replace everything with *.
If the total is not overallNumericalGrade then simply use the replacement on whatever is the value.
Edit : To answer to your comment, here more explanation.
String.replaceAll is a method that replace everything corresponding to the given Regular expression(regex) given by what we give as second parameter ( in that case *). The regex I gave is simply a . which means any character except linebreak. So, String.valueOf(overallNumericalGrade) convert it to a String so I can call the replaceAll method, then replace everything with *.
As for an answer to your second question, once again you could use the replacement to replace each linebreak of grade by a simple space so that it display all on the same line. Something like
grade.replaceAll(System.getProperty("line.separator"), " ");
Notice that I used System.getProperty("line.separator") instead of giving in the char so that it work on any system.

Need help declaring a variable within a for loop (Java)

I'm currently working on a program and ran into an error while trying to execute a for loop. I want to declare a variable in the for loop, then break once that variable obtains a certain value, but it returns the error "cannot be resolved to a variable."
Here's my code
int i = -1;
for (; i == -1; i = index)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
int index = (input.indexOf('y'));
}
I want to run the output segement of my program until the user inputs yes, then the loop breaks.
The variable index's scope is local to the block of the for loop, but not the for loop itself, so you can't say i = index in your for loop.
You don't need index anyway. Do this:
for (; i == -1;)
or even
while (i == -1)
and at the end...
i = (input.indexOf('y'));
}
Incidentally, I'm not sure you want input.indexOf('y'); an input of "blatherskyte" will trigger this logic, not just "yes", because there's a y in the input.
Instead of using a for loop, you can do-while(it suits much better for this scenario.
boolean exitLoop= true;
do
{
//your code here
exitLoop= input.equalsIgnoreCase("y");
} while(exitLoop);
for indefinite loop, i would prefer while.
boolean isYes = false;
while (!isYes){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}
You cannot do this. If the variable is declared inside of the loop, then it is re-created every run. In order to be part of the condition for exiting the loop, it must be declared outside of it.
Alternatively, you could use the break keyworkd to end the loop:
// Should we exit?
if(input.indexOf('y') != -1)
break;
Here you want to use a while loop. Usually you can decide which loop to use by saying your logic out loud to yourself, While this variable is(not) (value) do this.
For your problem, initialize the variable outside of the loop, and then set the value inside.
String userInput = null;
while(!userInput.equals("exit"){
System.out.println("Type exit to quit");
userInput = scan.nextLine();
}

Categories