Search & Display Info from Parallel Array - java

just another newbie here needing help with a coding dilemma. The program I'm trying to create is a small database that has to use three parallel arrays (userNumber, player, and highScore). The intention is that the user should enter the a user number at the prompt and the program will display the person's information. If the number entered doesn't exist then the program should show them the number they entered and make them re-enter a user number until a correct one is entered.
The problems I'm running into now is that the program doesn't accept any user number except the first user number in the array, whether or not it's a valid number in the array list. Also, the error message only displays the first "incorrect" number regardless of how many times a "wrong" number is entered.
In short, I guess the right questions would be:
1.) Exactly what should I change in order for the program to return the info for just the array entries that correspond to the entered userNumber?
2.) What do I change to make each error message display the "incorrect" number that was just entered?
Here's the code I have:
import java.util.Scanner;
public class HighScoreSearch
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] userNumber = new int[5];
String[] player = new String[5];
Double[] highScore = new Double[5];
userNumber[0]= 1;
userNumber[1]= 2;
userNumber[2]= 3;
userNumber[3]= 4;
userNumber[4]= 5;
player[0]= "Morpheus";
player[1]= "Neo";
player[2]= "Cereal Killer";
player[3]= "Crash Override";
player[4]= "Acid Burn";
highScore[0]= 853797.67;
highScore[1]= 999999.99;
highScore[2]= 15097.34;
highScore[3]= 864513.16;
highScore[4]= 543188.68;
System.out.print("Enter User# ");
int scan= input.nextInt();
int i=0;
while (scan!=userNumber[i])
{
System.out.printf("Error #%s Is Unknown User", scan);
System.out.print("Enter User# ");
scan=input.nextInt();
}
System.out.printf("%s, user# %s, has a high score of: %s", player[i], userNumber[i], highScore[i]);
}
}

You are not using the entered value - consider
while (scan < userNumber[0] || scan > userNumber[4])
{
System.out.printf("Error #%s Is Unknown User", scan);
System.out.print("Enter User# ");
scan=input.nextInt();
}
// now use the value
System.out.printf("%s, user# %s, has a high score of: %s",
player[scan-1], userNumber[scan-1], highScore[scan-1]);
Of course, you should really loop through the userNumber array to check if the number is there. In reality such a solution would require you to create single obejcts holding this information and then having a List or array of these objects

You should consider using a HashMap for your users instead of an array. Otherwise, you would have to loop through the entire array each time to find if the user exists.
Map<Integer, Integer> userMap = new HashMap<>();
// map user numbers to associative array indexes.
userMap.put(1, 0);
userMap.put(2, 1);
userMap.put(3, 2);
userMap.put(4, 3);
userMap.put(5, 4);
player[0]= "Morpheus";
player[1]= "Neo";
player[2]= "Cereal Killer";
player[3]= "Crash Override";
player[4]= "Acid Burn";
highScore[0]= 853797.67;
highScore[1]= 999999.99;
highScore[2]= 15097.34;
highScore[3]= 864513.16;
highScore[4]= 543188.68;
System.out.print("Enter User# ");
int scan= input.nextInt();
// loop until the user actually exists
while (!userMap.containsKey(scan))
{
System.out.printf("Error #%s Is Unknown User", scan);
System.out.println();
System.out.println("Enter User# ");
scan=input.nextInt();
}
// get the index for the user
int lookup = userMap.get(scan);
System.out.printf("%s, user# %s, has a high score of: %s", player[lookup], scan, highScore[lookup]);
Note
The other benefit with using this approach is that your user numbers don't have to be in order.
For example, you can have the following mapping and the code would still work:
userMap.put(1, 0);
userMap.put(2, 1);
userMap.put(9, 2); // user # 9 can map to index 2.
userMap.put(4, 3);
userMap.put(5, 4);
Per #ScaryWombat it would be ideal to create a Player class so you don't have to use associative arrays and make your program more OO.
Example:
class Player
{
private int id = 0;
private String name;
private Double score = 0.0;
public Player (int id, String name, double score)
{
this.id = id;
this.name = name;
this.score = score;
}
#Override
public String toString()
{
return String.format("%s, user# %s, has a high score of: %s", name, id, score);
}
}
Then, you can create a HashMap of Integer to Player
Map<Integer, Player> userMap = new HashMap<>();
userMap.put(1, new Player(1, "Morpheus", 853797.67));
userMap.put(2, new Player(2, "Neo", 999999.99));
userMap.put(3, new Player(3, "Cereal Killer", 15097.34));
userMap.put(4, new Player(4, "Crash Override", 864513.16));
userMap.put(5, new Player(5, "Acid Burn", 543188.68));
Now, you can look up the Player like this:
// get the player object for the user id
Player p = userMap.get(scan);
// print out the player like this since it has a toString()
System.out.println(p);

I'm proving another answer that uses arrays, since your requirement is to use parallel arrays. Please see all the comments in the code. I've added error checking so the program doesn't exit nor get into an invalid state.
The key here is that you have to loop through the entire array each time the user enters a potential user number.
import javax.swing.JOptionPane;
public class HighScoreSearch
{
// You need an indicator for an invalid user in the case where
// you don't use all array positions
private static final int INVALID_USER_NUM = -1;
public static void main(String[] args)
{
// consider renaming this int to something like userNumber (scan is not very meaningful)
int scan = 0;
int[] userNumber = new int[10];
String[] player = new String[10];
Double[] highScore = new Double[10];
userNumber[0]= 10;
userNumber[1]= 777;
userNumber[2]= 5;
userNumber[3]= 1234;
userNumber[4]= 357;
// set the rest to an invalid user #; otherwise these will have a value 0 by default
userNumber[5]= INVALID_USER_NUM;
userNumber[6]= INVALID_USER_NUM;
userNumber[7]= INVALID_USER_NUM;
userNumber[8]= INVALID_USER_NUM;
userNumber[9]= INVALID_USER_NUM;
player[0]= "Morpheus";
player[1]= "Neo";
player[2]= "Cereal Killer";
player[3]= "Crash Override";
player[4]= "Acid Burn";
highScore[0]= 853797.67;
highScore[1]= 999999.99;
highScore[2]= 15097.34;
highScore[3]= 864513.16;
highScore[4]= 543188.68;
// this represents the array index of the user across the arrays
int indexOfUser = 0;
// flag to indicate if we found a valid user
boolean userFound = false;
do
{
String replyBox = JOptionPane.showInputDialog("Enter User#");
// consider trimming this replyBox value
// If they enter "10 " (w/o quotes would you still want that to be valid)
replyBox = replyBox.trim();
scan = INVALID_USER_NUM; // default to an invalid user #
try
{
scan = Integer.parseInt(replyBox);
}
catch (java.lang.NumberFormatException nfe)
{
// they didn't enter a valid integer, but you don't want to exit the program
}
// don't bother searching if it's invalid
if (scan != INVALID_USER_NUM)
{
// loop through each user to see if you find the entered #
for (int i = 0; i < userNumber.length && !userFound; i++)
{
// we found this user
if (scan == userNumber[i])
{
indexOfUser = i;
userFound = true;
}
}
}
if (!userFound)
{
// you should use replyBox instead of scan here
//String messagefalse = String.format("Error %s is an Unknown User", scan);
String messagefalse = String.format("Error: '%s' is an Unknown User", replyBox);
JOptionPane.showMessageDialog(null, messagefalse);
}
} while (!userFound); // loop until we find a user
// we've found a user - use the indexOfUser to index the arrays
String messagetrue = String.format("%s, user# %s, has a high score of: %s", player[indexOfUser], userNumber[indexOfUser], highScore[indexOfUser]);
JOptionPane.showMessageDialog(null, messagetrue);
}
}

Related

Ascending a String input of numbers in java

I am working on a program where user can input random numbers and when user give -1 the loop will break and the entered numbers will be displayed
Example:
Enter a Number: 32
Enter next Number: 1243
Enter next Number: 123
Enter next Number: 76
Enter next Number: -1
Thank You. You have entered 32, 1243, 123, 76
Now whatever number is entered it will be displayed in ascending order
----Ascending order -----
[32,76,123,1243]
Now i have completed the following but the to get exact result the user need to enter
->0032
->0076
->0123
->1243
Then i am getting the exact result
[0032, 0076, 0123, 1234]
Then only my sorting is working fine otherwise it is like
[ 123, 1243, 32, 72]
Now how to solve this ?
package Testx;
import java.util.Arrays;
import java.util.Scanner;
public class Test7Ctr{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner user = new Scanner(System.in);
String user_input = "";
String holdv="";
String holdvx="";
String ascend="";
//AsveNd(user_input);
try
{
int b =0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
int x= Integer.valueOf(user_input);
if (x != -1)
{
holdv=user_input;
holdvx+=holdv+",";
ascend+=holdv+" ";
b++;
}
else
{
System.out.println("THANK YOU FOR ENTERING= "+holdvx);
break;
}
}
while(b <= 100);
{
}
String[] numbers=ascend.split("\\s");
for(String numb:numbers)
{
int intarray[] = new int[numbers.length];
Arrays.sort(numbers);
//break;
}
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(numbers));
}
catch(Exception e)
{
}
}
}
You are sorting strings rather than numbers. This makes your sort work in lexicographic order instead of plain ascending order.
So to fix your problem, simply add Integers and not Strings. You can even parse a String to an Integer using Integer.parseInt().
Also, there is no need to call sort every time you insert a new number, but just once in the end. That adds a lot of overhead to your process.
You can get the proper integer sorting with the following:
String[] numbers = ascend.split("\\s");
int intarray[] = new int[numbers.length];
int i = 0;
for (String numb : numbers)
{
// convert the String to an int
intarray[i++] = Integer.parseInt(numb);
}
Arrays.sort(intarray); // sort the int array, not the String array
System.out.println("---Ascending order---");
System.out.println(Arrays.toString(intarray));
Side Note:
Your do/while loop would be better written as:
int x = 0;
do
{
System.out.print("Enter next number:");
user_input = user.nextLine();
x = Integer.valueOf(user_input);
if (x != -1)
{
holdv = user_input;
holdvx += holdv + ",";
ascend += holdv + " ";
}
} while (x != -1);
System.out.println("THANK YOU FOR ENTERING= " + holdvx);
You don't need the int b
You don't need the else statement in the loop. Just have the loop terminate when x is -1.
Also, you had an empty block after the while (...); That is not doing anything. The while portion of a do/while loop has no body.
You are sorting the "Strings" and not the "numbers". Scan those inputs as number, put them to a dynamic list (and not a static sized array) and then sort the list of numbers (and not of string)

How to prompt for index of Object Array and Display the Value?

I want to prompt a user through command line using a Scanner, to select from a predefined index of a Rational Array. After that I want to display the value of a selected Rational Object. How can I go about doing so ? Below is the code I have so far
//Array of rational objects that I want to let user select from
Rational[] rationals = {new Rationa(2, 3), new Rational(2, 18), new Rational(3,12)};
//Method for displaying value of object
public static void displayValue()
{
System.out.println("Please select from index: ");
}
First create a .toString() method for the Rational class. Then you may print the array like this:
System.out.println(Arrays.toString(rationals));
Then you may get input like this:
Scanner sc = new Scanner(System.in);
int index = sc.nextInt();
Ensure an acceptable number was given:
if(index > -1 && index < rationals.length){
System.out.println(rationals[index]);
}else{
System.out.println("Please input an acceptable value.")
}
If you want to keep asking for an input, until an acceptable one is given, you it can be done by using a while loop:
boolean askAgain = true;
while(askAgain){
int index = sc.nextInt();
if(index > -1 && index < rationals.length){
System.out.println(rationals[index]);
askAgain = false;
}else{
System.out.println("Please input an acceptable value.")
}
}
EDIT: You may want to specify that the list starts at index 0, not 1.
EDIT2: .toString() example,
public class Person(){
private String name;
private int id;
public Person(String n, int id){
this.name = n;
this.id = id;
}
public String toString(){
return "Name: " + name + ", " + id;
}
}
The toString(); method for an object class is just meant for returning the "useful information" as a String. In this example, for a Person class, the toString() method just returns the name and id of the user. So, for your Rational class, you can adjust that method to properly turn the object into a String.
Usage:
Person p1 = new Person("Jake", 1);
System.out.println(p1.toString());
OUTPUT:
"Name: Jake, 1"
You will need to use a Scanner to read input from the console. To use Scanner, you need to import java.util.Scanner;
This line creates the new Scanner and attaches it to System.in, which is the standard input for the program.
Scanner console = new Scanner(System.in);
Now we can read an integer from input to select the index.
int index = console.nextInt();
After that, all you'll need to do is print out the value at index in your array.

java array that accepts input of put name mark, quit and get name (not working)

im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}

How do you find the index number of a string in an array in Java

I have no idea if I'm coding this efficiently, or even correctly, but I want to input a name, address, and phone number. I then want to have input find a match from the input array, and use that same index number to print the corresponding information.
import java.util.*;
public class NameAddress {
public static void main(String[] args) {
Scanner ui = new Scanner(System.in);
System.out.println("Welcome to the name collecting database");
String []names = new String[5];
String []address = new String[5];
String []phone = new String [5];
int count =0;
while (count<=5)
{
System.out.println("Please enter the name you would like to input");
names[count] =ui.next();
System.out.println("Name has been registered into Slot "+(count+1)+" :"+Arrays.toString(names));
System.out.println("Please enter the address corresponding with this name");
ui.nextLine();
address[count] = ui.nextLine();
System.out.println(names[count]+" has inputted the address: "+address[count]+"\nPlease input your phone number");
phone[count]=ui.nextLine();
System.out.println(names[count]+"'s phone number is: "+phone[count]+"\nWould you like to add a new user? (Yes or No)");
if (ui.next().equals("No"))
{
System.out.println("Please enter a name to see matched information");
String name = ui.next();
if(name.equals(names[count]))
{
System.out.println("Name: "+names[count]+"\nAddress: "+address[count]+"\nPhone: "+phone[count]);
}
count=6;
}
count++;
}
}
}
if(name.equals(names[count])) will work only if the name user is searching is at the current index of names. So you have to check every item in the array to determine whether it exists in the array. You can do this:
int itemIndex = Arrays.asList(names).indexOf(name);
if(itemIndex>=0) // instead of if(name.equals(names[count]))
{
// rest of the codes; use the itemIndex to retrieve other information
}
else
{
System.out.println(name + " was not found");
}
Or manually loop over the names array as others showed.
System.out.println("Please enter a name to see matched information");
String name = ui.next();
for(int i = 0; i <names.length;i++){
if(name.equals(names[i]))
{
System.out.println("Name: "+names[i]+"\nAddress: "+address[i]+"\nPhone: "+phone[i]);
}
}
It seems like you have data input already done.
As for data retrieval by searching, if you don't care about efficiency, then you could iterate over the entire array to see if the text inputted matches any element in your array using
int searchIndex = 0;
for (int i = 0; i < names.length; i++) {
if (searchString.equals(names[i])) {
searchIndex = i;
}
}
where searchString would be the string input by the user to find the element in the array. The code block above assumes you don't have duplicate data, but you could easily tweak the returned index to contain an array of indexes that contain your data, if you wish. You'd then have an index number (or index numbers) with which you could use to find the rest of the data in your other arrays.

Java search if a string exists

I am trying to determine if the user entered value already exists in the current array, how to do that?
User entered value to check the variable is
accno and the array to compare to is accnums
This is what i am currently working on
public class Randomtopic {
static BigDecimal[] accbal = new BigDecimal[20];
static Integer[] accnums = new Integer[20];
public static void main(String[] args) {
displayMenu();
}
public static void displayMenu() {
int option, accno;
double accbal;
Scanner sc = new Scanner(System.in);
System.out.println(" Add an account");
System.out.println("Search an account with the given account number");
System.out.print("Enter Your Choice: ");
option = sc.nextInt();
switch (option) {
case 1:
System.out.println("You have choosen to add account");
addAccount();
break;
case 2:
System.out.println("You have choosen to search for an account");
System.out.print("Enter the Account Number: ");
accno = sc.nextInt();
System.out.println(search(accno, accnums));
break;
default:
System.out.println("Please choose an appropriate option as displayed");
}
displayMenu();
}
public static void addAccount() {
//String accno;
int i = 0;
int accno, input;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
//BigDecimal[] accbal= new BigDecimal[20];
Scanner sc = new Scanner(System.in);
//String[] accnums = new String[20];
int j;
System.out.print("Enter the account number: ");
accno = sc.nextInt();
if (String.valueOf(accno).matches("[0-9]{7}")) {
System.out.print("Enter account balance: ");
accbala = sc.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null )
break;
else if(accnums[j].equals(accno))
{
System.out.println("Account already exists");
}
}
//System.out.print(j);
if (j == accnums.length) {
System.out.print("Account storage limit has reached.");
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
}
input = accnums[0];
System.out.println("The value: " + input + " witha a balance of " + accbal[0].toString());
} else {
System.out.println("Wrong NRIC");
}
displayMenu();
}
public static String search(int accnum, Integer[] numbers) {
// Integer[] numbers;
//int key;
//numbers = accnums;
// System.out.print("Enter the Account Number: ");
for (int index = 0; index < numbers.length; index++) {
if (numbers[index].equals(accnum)) {
return String.valueOf(index);
// System.out.println("The account number exists in this array index :"+index);//We found it!!!
}
break;
}
return "-1";
}
}
So my problem?
When i enter the accnum for the first time itself i am getting NullPointerException. Tks
When you instantiate or create an array, the values are by default set to null; whenever you iterate over an array of possibly null values, it is required you skip these. For example,
for(loop conditions)
if (numbers[index] != null && (numbers[index].equals(accnum))) {
return String.valueOf(index);
//your text goes here;
}
break;//I suggest you take this line out of your original code. Your for loop will end this once you have iterated through the entire array, or you will automatically break out if you find the value.
}
If you must use an array, then this is the best way to iterate through it. The parenthesis and the && in the if clause prevent you from performing the .equals check if the value of numbers[index] == null - in turn, preventing the null error from being thrown. your only alternative would be to set every value in the numbers[ ] to 0, or some other value, and than skip that value when you iterate. Such would be done with a static final int. However, this is not ideal coding.
Ideally, you should use an ArrayList - you can then not only make this more efficient, but also, much more readable.
Your accnums is filled with null values. Check if they are not null. I suppose your NullPointerException is thrown from search method.
If I understood your code correctly you have a number of accounts with associated balance identified by an account number. In this case I would use a Map instead of fiddling with arrays.
when you run your method search first time, yours array accnums is filled with null value so when you call line if ( numbers[index].equals(accnum)) you are trying call equal method on null object
what you can do is change your accnums from array to list, and then size will depends on number elements, so it wont have fixed size like your arrays
The problem in your code without adding anything in your accnum you are searching.So your accnum contains NULL values.if you change your accnum array into list/hashmap the exception would not arise.

Categories