ID check on an array of objects - java

I am having trouble for the past week trying to solve how to check if an Id has already been added to the array, and if it has, stop the user from entering the rest of the data, I would greatly appreciate some help with this.
My code:
class CustomerUse {
public static int checkId(Customer theArray[], int noOfValues,
String searchId) {
int idCheck = 0;
int step = 0;
while (step < noOfValues) {
step++;
if ((step < noOfValues) && (theArray[step].getId().equals(searchId))) {
idCheck = -1;
}
}
return idCheck;
}
public static void listAllNames(Customer[] names, int NoOfElements) {
int index;
String result;
for (index = 0; index < NoOfElements; index++) {
System.out.println(names[index]);
}
}
public static int findPlace(Customer theArray[], int balance, int noOfValues) {
int step;
int place;
step = 0;
while ((step < noOfValues) && (balance < theArray[step].getBalance())) {
step++;
}
place = step;
return place;
}
public static int addOne(Customer theArray[], int place, String Id,
Customer theObject, int noOfValues) {
int step;
if (noOfValues == 0) {
theArray[0] = theObject;
noOfValues++;
} else {
for (step = noOfValues - 1; step >= place; step--) {
theArray[step + 1] = theArray[step];
}
theArray[place] = theObject;
noOfValues++;
}
return noOfValues;
}
public static int deleteName(Customer theArray[], int noOfElements) {
String searchId;
int step;
int whichOne = 0;
System.out.println("Enter Id of customer to be deleted ");
searchId = EasyIn.getString();
step = 0;
while ((step < noOfElements)
&& !(theArray[step].getId().equals(searchId))) {
step++;
}
if (step < noOfElements) {
whichOne = step;
for (step = whichOne; step < noOfElements - 1; step++) {
theArray[step] = theArray[step + 1];
}
noOfElements--;
} else {
System.out.println(" Sorry this customer doesn't exist");
}
return noOfElements;
}
public static void main(String[] args) {
Customer empArray[];
int index;
int noOfElements;
String searchName;
Customer tempObject;
int step;
int option = 0;
int place;
String newName = "";
String newId;
int newBalance;
int checkID = 0;
empArray = new Customer[100000];
noOfElements = 0;
System.out
.println("\n 1. Add Customer \n 2. Delete Customer \n 3. List all Customers \n 4. Exit");
System.out.print("Enter Option ");
option = EasyIn.getInt();
while (option != 4) {
if (option == 1) {
System.out.print("Enter ID ");
newId = EasyIn.getString();
System.out.print("Enter name ");
newName = EasyIn.getString();
System.out.print("Enter Balance ");
newBalance = EasyIn.getInt();
System.out.println();
tempObject = new Customer(newName, newId, newBalance);
place = findPlace(empArray, newBalance, noOfElements);
noOfElements = addOne(empArray, place, newId, tempObject,
noOfElements);
checkID = checkId(empArray, noOfElements, newId);
if (checkID == -1) {
System.out.println("Sorry this ID already exists");
checkID = 0;
}
} else if (option == 2) {
noOfElements = deleteName(empArray, noOfElements);
} else if (option == 3) {
listAllNames(empArray, noOfElements);
}
System.out.print("Enter Option ");
option = EasyIn.getInt();
}
}
}

This effectively skips array entry at index 0:
while (step < noOfValues)
{
step++;
Better:
public static int checkId(Customer theArray[], int noOfValues, String searchId){
for (int step = 0; step < noOfValues; ++step ){
if( theArray[step].getId().equals(searchId) )
{
return step;
}
}
return -1;
}
Return -1 on not found, otherwise the index.
I haven't checked the remainder of your code, just saw that the use of an array should be discarded in favour of a List.

Related

PALIN- The next Palindrome - a SPOJ problem

I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}

5 Card Poker Hand JAVA-Analyze and Categorize

Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent.
Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.
I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind.
Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind.
Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4.
Any suggestions to my code?
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int HAND_SIZE = 5;
int[] hand = new int[HAND_SIZE];
getHand(hand); //Prompt user for hand
sortHand(hand);//Sort hand in ascending order
if(containsFullHouse(hand))
{
System.out.print("FULL HOUSE!");
}
else if(containsStraight(hand))
{
System.out.print("STRAIGHT!");
}
else if(containsFourOfAKind(hand))
{
System.out.print("FOUR OF A KIND!");
}
else if(containsThreeOfAKind(hand))
{
System.out.println("THREE OF A KIND!");
}
else if(containsTwoPair(hand))
{
System.out.println("TWO PAIRS!");
}
else if(containsPair(hand))
{
System.out.println("PAIR!");
}
else
System.out.println("High Card!");
}
public static void getHand(int[] hand)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter five numeric cards, 2-9, no face cards please");
for(int index = 0; index < hand.length; index++)
{
System.out.print("Card " + (index + 1) + ": ");
hand[index] = input.nextInt();
}
}
public static void sortHand(int[] hand)
{
int startScan, index, minIndex, minValue;
for(startScan = 0; startScan < (hand.length-1); startScan++)
{
minIndex = startScan;
minValue = hand[startScan];
for(index = startScan + 1; index <hand.length; index++)
{
if(hand[index] < minValue)
{
minValue = hand[index];
minIndex = index;
}
}
hand[minIndex] = hand[startScan];
hand[startScan] = minValue;
}
}
public static boolean containsPair(int hand[])
{
boolean pairFound = false;
int pairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
pairCount++;
}
startCheck = hand[index];
}
if (pairCount == 1)
{
pairFound = true;
}
else if(pairCount !=1)
{
pairFound = false;
}
return pairFound;
}
public static boolean containsTwoPair(int hand[])
{
boolean twoPairFound = false;
int twoPairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
twoPairCount++;
}
startCheck = hand[index];
}
if (twoPairCount == 2)
{
twoPairFound = true;
}
else if(twoPairCount != 2)
{
twoPairFound = false;
}
return twoPairFound;
}
public static boolean containsThreeOfAKind(int hand[])
{
boolean threeFound = false;
int threeKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
threeKind++;
}
startCheck = hand[index];
}
if(threeKind == 3)
{
threeFound = true;
}
else if(threeKind !=3)
{
threeFound = false;
}
return threeFound;
}
public static boolean containsStraight(int hand[])
{
boolean straightFound = false;
int straight = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 1)
{
straight++;
}
startCheck = hand[index];
}
if(straight == 4)
{
straightFound = true;
}
return straightFound;
}
public static boolean containsFullHouse(int hand[])
{
boolean fullHouseFound = false;
int pairCheck = 0;
int startPairCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startPairCheck) == 0)
{
pairCheck++;
}
startPairCheck = hand[index];
}
int threeOfKindCheck = 0;
int startThreeKindCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startThreeKindCheck) == 0)
{
threeOfKindCheck++;
}
startThreeKindCheck = hand[index];
}
if(pairCheck == 1 && startThreeKindCheck == 3)
{
fullHouseFound = true;
}
return fullHouseFound;
}
public static boolean containsFourOfAKind(int hand[])
{
boolean fourFound = false;
int fourKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
fourKind++;
}
startCheck = hand[index];
}
if(fourKind == 1)
{
fourFound = true;
}
else if(fourKind !=4)
{
fourFound = false;
}
return fourFound;
}
}
Some hints.
Start with the highest hand. This eliminates lots of logic.
I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind.
But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.

quadratic probing hash table

Hellow, For some off reason I cannot get my hash table to fill with the items and keys when I insert. It seems like it is being added when run through the driver, but nothing is stored, and there are absolutely no error messages.
I am suppose to create a hash table that utilizes quadratic probing. I am suppose to count the number of transversals which cannot be > 20.
Here is the code:
public class HashTable {
String[] table;
String[] keys;
int currentSize, maxSize, numOfEntries;
int traverse = 0;
double capacity;
public HashTable(int size, double load){
if(size <= 0){
System.out.println("Size must be greater then 0");
}
else if(load < 0 || load > 1){
System.out.println("Load must be between 0 and 1. EX: 0.75");
}else{
this.currentSize = 0;
table = new String[size];
keys = new String[size];
this.capacity = load * size;
this.maxSize = size;
}
}
public int hash(String num){
return (2 * Integer.parseInt(num) + 5) % table.length;
}
public int getLength(){
return table.length;
}
public int getMaxSize(){
return maxSize;
}
public int probe(String num){
int temp = hash(num);
int calc = 0;
numOfEntries = 0;
while(table[temp] != null){
traverse++;
temp = (int)((temp + (float)calc/2 + (float) (calc * calc)) % maxSize);
calc++;
numOfEntries++;
}
if(traverse >= 20){
System.out.println("Insert Failed : Reached 20 Traversal Limit!");
return 20;
}
return temp;
}
public void resize(){
String [] tempTable = table;
if(table.length >= capacity){
table = new String[tempTable.length * 2];
for(int i = 0; i < tempTable.length; i++){
if(tempTable[i] != null){
insert(tempTable[i]);
}
}
}
}
public void insert(String num){
int temp = probe(num);
table[temp] = num;
currentSize++;
if(currentSize >= capacity){
resize();
}
}
public String searchKey(String key){
String temp = "";
numOfEntries = 0;
for(int i = 0; i < keys.length; i++){
if(key == keys[i]){
temp = table[i];
numOfEntries++;
break;
}
numOfEntries++;
}
if(temp == ""){
System.out.println("No items that match that key!");
}
return temp;
}
public int numOfEntries(){
return numOfEntries;
}
public void print(){
System.out.println("Key\t:\tValue");
for(int i = 0; i < table.length; i++){
if(keys[i] != null){
System.out.println(keys[i] + "\t:\t" + table[i]);
}
}
System.out.println();
}
}
Here is the Driver:
import java.util.*;
public class HashTableDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Table Size:\t");
int size = scan.nextInt();
System.out.println("Enter Load Factor (Between 0 and 1");
double load = scan.nextDouble();
int temp = 0;
HashTable table = new HashTable(size,load);
System.out.println(table.getLength());
System.out.println(table.getMaxSize());
while(temp != 4){
System.out.println();
System.out.println("i)(1) Insert an item to the Hash Table" +
"\nii)(2) Search A Specific Key" +
"\niii)(3) Display the Table" +
"\nvii)(4) Quit");
String input = scan.next();
switch(input){
case "1":
System.out.println();
System.out.println("Enter value to add to table");
String desKey1 = scan.next();
table.insert(desKey1);
continue;
case "2":
System.out.println("Please enter specific key desired:\t");
String desKey2 = scan.next();
if(table.searchKey(desKey2).equals(desKey2)){
System.out.println("Key Found");
System.out.println("Number of cells accessed:\t" + table.numOfEntries());
}
else{
System.out.println("Key Not Found");
}
continue;
case "3":
table.print();
continue;
case "4":
temp = 4;
break;
}
}
}
}

Roman number to decimal in Java

I have to make a program that converts Roman numbers to decimal. I am confused about how to write the conditions for the Roman numbers, such as IV (4), IX (9), XL (40) and CM(900). The code that I wrote works for all the other numbers.
public static void main(String[] args) {
System.out.print("Enter a roman numeral: ");
Scanner in = new Scanner(System.in);
String Roman = in.next();
int largo = Roman.length();
char Roman2[] = new char[largo];
int Roman3[] = new int[largo];
for (int i = 0; i < largo; i++) {
Roman2[i] = Roman.charAt(i);
}
for (int i = 0; i < largo; i++) {
if (Roman2[i] == 'I') {
Roman3[i] = 1;
} else if (Roman2[i] == 'V') {
Roman3[i] = 5;
} else if (Roman2[i] == 'X') {
Roman3[i] = 10;
} else if (Roman2[i] == 'L') {
Roman3[i] = 50;
} else if (Roman2[i] == 'C') {
Roman3[i] = 100;
} else if (Roman2[i] == 'M') {
Roman3[i] = 1000;
}
}
int total = 0;
for (int m = 0; m < Roman3.length; m++) {
total += Roman3[m];
}
System.out.println("The Roman is equal to " + total);
}
You can check the previous digit.
For example, I added the condition that detects IV :
if (Roman2[i]=='I'){
Roman3[i]=1;
} else if (Roman2[i]=='V'){
Roman3[i]=5;
if (i>0 && Roman2[i-1]=='I') { // check for IV
Roman3[i]=4;
Roman3[i-1]=0;
}
} else if (Roman2[i]=='X'){
Roman3[i]=10;
} else if (Roman2[i]=='L'){
Roman3[i]=50;
} else if (Roman2[i]=='C'){
Roman3[i]=100;
} else if (Roman2[i]=='M'){
Roman3[i]=1000;
}
Define enum like below:
public enum RomanSymbol {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int value;
private RomanSymbol(final int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public int calculateIntEquivalent(final int lastArabicNumber, final int totalArabicResult) {
if (lastArabicNumber > this.value) {
return totalArabicResult - this.value;
} else {
return totalArabicResult + this.value;
}
}
}
And use it like RomanSymbol.I.getValue() which will return 1 and similarly for other.
So if you accept character from user, you can get the values as:
char symbol = 'I';//lets assume this is what user has entered.
RomanSymbol rSymbol = RomanSymbol.valueOf(String.valueOf(symbol));
int invalue = rSymbol.getValue();
And if you have string like IV, then you could calculate on something like for example:
int lastValue = rSymbol.calculateIntEquivalent(intValue, 0);
lastValue = rSymbol.calculateIntEquivalent(intValue, lastValue); //and so on

not getting correct numbers in for loop

Hy there. Below you can see sagment of my code. So lets go to the problem.
int i is not returning correct values and i cannot figure it out why.
LIST: [AGRFT, AGRFT, ARNES, ASCII, ASEAN, Aaron, Abdul, Abdul]
So for example. User inputs AS***, the program should return i is at 2. However i am getting i is at 0.
If i remember right it should go like this:
User_input= AS***
User_input.lenght() should be 5
first it should be user_input.charAt(0)=='*' NO
second it should be user_input.charAt(1)=='*' NO
third it should be user_input.charAt(2)=='*' YES
BREAK
i is at 2.
SO what am i missing?
I am getting 0.
Oh and also at
for(i=0; i < user_input.length();i++){
i am getting warning that i++ is Dead code?
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i is at "+ i);
this is my full code for refrence. What it does it reads from txt file add wor
public class proba {
public static void main(String[] args) {
String izbira;
int dolzina=0;
int i=0;
Scanner in = new Scanner(System.in);
String user_input;
Scanner input = new Scanner(System.in);
String regex;
List<String> list5 = new ArrayList<String>();
int beseda;
String prefix = null;
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 5) {
list5.add(vrstica);
}
}
System.out.println(list5);
do{
do {
System.out.println("Enter lenght of word:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Wrong entry!%n ",
in.nextLine());
}
} while (dolzina <= 0);
Collections.sort(list5);
System.out.println("Enter a word for unknown character enter * :");
user_input = input.nextLine();
System.out.println("Sorted list: [length: " + list5.size() + "]");
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i je"+ i);
prefix=user_input.substring(0,i);
System.out.println(prefix);
int start=binarySearchfirst(list5,prefix);
int end=binarySearchlast(list5,prefix);
System.out.println(start);
System.out.println(end);
for (int b=start;b<=end;b++)
{
user_input = user_input.replace("*", ".");
String s = (String) list5.get(b);
if (s.matches(user_input))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}}
public static int binarySearchfirst(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == 0 || !integerList.get(mid - 1).startsWith(prefix)) {
return mid;
} else {
high = mid - 1;
}
} else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
public static int binarySearchlast(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size()-1;
while (low <= high) {
int mid = (low+high)/2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == integerList.size()-1 || !integerList.get(mid+1).startsWith(prefix)) {
return mid;
}
else {
low = mid+1;
}
}
else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid+1;
}
else {
high = mid-1;
}
}
return high;
}
}
You have an extra semi-colon after your if statement:
for(i=0; i < user_input.length();i++)
{ if (user_input.charAt(i)=='*');
break;
}
So the break is executed the first time through the loop no matter what. This is also why i++ is being reported as dead code...it's never being executed.

Categories

Resources