If I increment a variable within a switch case how do I get it to increment outside as well? - switch-statement

There are multiple issues with my code, I know. I am definitely a beginner. One issue is that my object keeps being written over. I tried incrementing within the switch case as you can see. That doesn't seem to work. I am not sure how else to do it. Also, when my program sees that a user tries to reuse an employee id it gives an error, but doesn't break out of the switch case. Any help on how to break out once the error is printed would be a big help! Thank you!
import java.util.*;
public class HR{
public static void main (String arg [ ]) throws Exception {
Employee[] employees = new Employee[10];
int size = 0;
int index = 0;
int option = 1;
int enumb = 0;
int delEnumb = 0;
double salary;
double moreThanSalary;
String name;
while (option != 0) {
try {
// Printing statements displaying menu on console
System.out.println("\n**********MENU**********");
System.out.println("1: Add Employee");
System.out.println("2: Delete Employee");
System.out.println("3: Display Employee(s) Earning Salary higher that you specify");
System.out.println("4: Print all employees info");
System.out.println("0: Exit program");
Scanner input = new Scanner(System.in);
System.out.print("\nEnter your selection : ");
option = input.nextInt();
switch (option) {
case 1:
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("\nYou have selected to add a new employee");
System.out.println("\nEnter ID: ");
enumb = scanint.nextInt();
for (index = 0; index < employees.length; index++){
if (employees[index] != null){
if (employees[index].getEnumb() == enumb) {
System.out.println("\nEmployee ID already exists");
}
}
}
System.out.println("Enter salary: ");
salary = scanint.nextDouble();
System.out.println("Enter name: ");
name = scanstr.nextLine();
employees[size]= new Employee(enumb, salary, name);
size++; // this doesn't seem to be incrementing so it is just writing over
// the same object again and again.
break;
case 2:
System.out.println("\nYou have selected to remove an employee");
Scanner scanId = new Scanner(System.in);
System.out.println("Enter Employee number: ");
delEnumb = scanId.nextInt();
if (delEnumb >= 10001 && delEnumb <= 99999){
for (index = 0; index < employees.length; index++){
if (employees[index] != null){
if (employees[index].getEnumb() == delEnumb) {
employees[index] = null;
System.out.println("Employee entry has been deleted");
}
}
}
}
break;
case 3:
System.out.println("\nYou have selected to search through and find employees "
+"\nwhose salary is more than an amount you provide.");
System.out.println("Enter Salary amount: ");
Scanner userInput = new Scanner(System.in);
moreThanSalary = input.nextDouble();
for (index = 0; index < employees.length; index++) {
if (employees[index] != null){
if (employees[index].getSalary() > moreThanSalary ) {
System.out.println(employees[index]);
}
}
}// closes for loop
break;
case 4:
System.out.println("============================");
for (index=0; index < employees.length; index++){
if (employees[index] != null){
System.out.println(employees[index]);
System.out.println("============================");
}
}
break;
case 0:
System.out.print("\nYou have selected to exit the program. Thank you!");
break;
// If none of the above cases execute (less than 0 or more than 4)
default:
System.out.println("\nSorry, you have entered a number other than 1, 2, 3, 4 or zero. \nTry Again.\n");
break;
} // closes switch
} // closes try
catch (InputMismatchException ime) {
System.out.print("\n\t\t\t\t ***Error*** \nThat entry was not an integer! Try again :)\n");
continue;
} // closes catch
catch (EmployeeException ee) {
System.out.print(ee.getMessage());
} // closes catch
} // closes while
} // closes main
} // closes class
'''

I found solutions to my issues. In case this helps others in future here is what I came up with. I am sure there are faster ways but this is what I used within the limits of my CS class:
import java.util.*;
import java.text.*;
public class HR{
public static void main (String arg [ ]) throws Exception {
final int SIZE = 100; // Constant used so changing array size is easier
int realSize = 0;
int index = 0;
int option = 1;
int enumb = 0; // variable used in switch case 1
int delEnumb = 0; // variable used in switch-case 2
double salary; // variable used in switch case 1
double moreThanSalary; // variable used in switch-case 3
String name; // variable used in switch case 1
boolean isEqual = false; // variable used in switch case 1 & 2
boolean isEmpty = true; // variable used in switch-case 4
boolean isNotMore = true; // variable used in switch-case 3
Employee[] employees = new Employee[SIZE]; // creates empty array 'employees' and sets size to 100
while (option != 0) {
try {
// Printing statements displaying menu on console
System.out.println("\n**********MENU**********");
System.out.println("1: Add Employee");
System.out.println("2: Delete Employee");
System.out.println("3: Display Employee(s) Earning Salary higher that you specify");
System.out.println("4: Print all employees info");
System.out.println("0: Exit program");
Scanner input = new Scanner(System.in);
System.out.print("\nEnter your selection : "); // Gets user input
option = input.nextInt(); // Stores user input
switch (option) {
case 1: // add a new employee
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("\nYou have selected to add a new employee");
System.out.println("\nEnter ID: "); // Gets uer input
enumb = scanint.nextInt(); // Stores user input
// Checks through current contents of array to see if enumb already exists
for (index = 0; index < employees.length; index++){
// Skips empty (null) elements of array
// && runs if the user entry matches a previous employee id then error message prints
if (employees[index] != null && employees[index].getEnumb() == enumb){ // == because it's primitive datatype
//
System.out.println("\nEmployee ID already exists");
isEqual = true;
} // closes if statement
} // closes for loop
// Will only run if the for loop above didn't find a matching employee ID number
if (isEqual == false) {
System.out.println("Enter salary: ");
salary = scanint.nextDouble(); // stores user input
System.out.println("Enter name: "); // Gets user input
name = scanstr.nextLine(); // stores user input
employees[realSize]= new Employee(enumb, salary, name); // creates object in employees array
}
break; // returns the user to the menu
case 2:
isEqual = false;
System.out.println("\nYou have selected to remove an employee");
Scanner scanId = new Scanner(System.in);
System.out.println("\nEnter Employee number: ");
delEnumb = scanId.nextInt(); // stores user input
// Checks if the number the user has enteres is within the Employee ID range
if (delEnumb >= 10001 && delEnumb <= 99999){
// Loops through employees array to check all NON null entries to find one that matches
// and deletes it
for (index = 0; index < employees.length; index++){
if (employees[index] != null && employees[index].getEnumb() == delEnumb){ // == because primitive
employees[index] = null; // 'deletes' it by setting array element to null
System.out.println("\nEmployee entry has been deleted");
isEqual = true;
} // Closes if statement
} // Closes for loop
// Prints in case the ID number the user enters doesn't yet exist in the array
// Returns them to the menu
if (isEqual != true) {
System.out.println("\nThere is no current employee with that number.");
}// closes if statement
}// Closes if statement
else {
// Prints if the user has entered a number outside of the range then returns them to the menu
System.out.println("Your selection is outside of the range 10001 to 99999. "
+"You will now be returned to the menu.");
}// Closes else statement
break; // returns the user to the menu
case 3: // runs is the user selects the salary search option
System.out.println("\nYou have selected to search through and find employees "
+"\nwhose salary is more than an amount you provide.");
System.out.println("\nEnter Salary amount: ");
Scanner userInput = new Scanner(System.in);
moreThanSalary = input.nextDouble(); // Stores user input of double size
// Used to help format the dollar amount the user entered to it looks nice
DecimalFormat myFormatter = new DecimalFormat("$###,##0.00"); // used to format the $ amount nicely
String output = myFormatter.format(moreThanSalary);
// Print to let user know that the following text are employees that earn over the amount they requested
System.out.println("\nNext you will see the employees that make over " + output + ":");
// Loops through the array to search through salaries
System.out.println("============================");
for (index = 0; index < employees.length; index++) {
// Only searches NON null elements and prints out entries where the employee
// earns over the specified amount the user inputed
if (employees[index] != null && employees[index].getSalary() > moreThanSalary){
System.out.println(employees[index]);
System.out.println("============================");
isNotMore = false;
}// closes if statement
}// closes for loop
// Will print if the amount that the user entered is more than any current employee salaries
if (isNotMore != false) {
System.out.println("\nNo employees earn over " + output + ", time for a raise!");
}// closes if statement
break; // returns the user to the menu
case 4: // Will run if the user chooses to print out all employee info
for (index=0; index < employees.length; index++){
// Skips entries that are empty (null)
if (employees[index] != null){
System.out.println(employees[index]);
isEmpty = false;
} // closes if statement
} // closes for loop
if (isEmpty != false) {
System.out.println("\nThere are no employees currently in the system. ");
}
break; // returns the user to the menu
case 0: // Will run if the user chooses to exit the program
System.out.print("\nYou have selected to exit the program. Thank you!");
break;
// Will run if none of the above cases execute (user enters a # less than 0 or more than 4)
default:
System.out.println("\nSorry, you have entered a number other than 1, 2, 3, 4 or zero. \nTry Again.\n");
break; // returns the user to the menu
} // closes switch
} // closes try
// prints error message if user enters something other than an integer
catch (InputMismatchException ime) {
System.out.print("\n\t\t\t\t ***Error*** \nThat entry was not an integer! Try again :)\n");
continue;
} // closes catch
// prints if the user enters something that triggers my custom exception
catch (EmployeeException ee) {
System.out.print(ee.getMessage());
} // closes catch
realSize++; // here so that future entries are put in the next element
} // closes while
} // closes main
} // closes class

Related

Check50 Errros: Not passing " handles most basic words properly" and "handles substrings properly" tests. Check50 also can't check for a memory error

I am working on Pset5 Speller. I've managed to get all my errors down to three, but I cannot figure out how to fix my program so that it handles most basic words and handles substrings. I have run debugger, but it doesn't really help. I have also run valgrind and it says that no memory leaks are possible. I think the problem maybe my check function or hash function, so I have changed them a few times but I still get the same check50 results. The sumbit50 link:
https://submit.cs50.io/check50/57b8af186bcdadea0b585f0785ef47a5cf317b99 says that check50 only ever finds 1 word in the dictionary and identifies all words as misspelled. I really am not quite sure what the problem is. Can someone help me please? Here are my checks and hash functions. Thank you!!!
// Hashes word to a number
unsigned int hash(const char *word)
{
// hash function created by Deliberate Think on Youtube
int hash_key = 0;
int n;
for (int i = 0; word[i] != '\0'; i++)
{
if (isalpha(word[i]))
{
n = word[i] - 'a' + 1;
}
else
{
n = 27;
}
hash_key = ((hash_key << 3) + n) % N;
}
return hash_key;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// create an array to store words, then copy words from table to compare
int n = strlen(word);
char wordcheck[LENGTH + 1];
strcpy(wordcheck, word);
for (int i = 0; i < n; i++)
{
wordcheck[i] = tolower(word[i]);
}
//hashes word, then accesses linked list at that value
int j = hash(wordcheck);
node *cursor = hashtable[j];
if (hashtable[j] != NULL)
{
//iterates through linked list: cursor pointer starts at head of list and while there is a value, it moves on to the next word in the list
while (cursor != NULL)
{
//if the word is found, return true
if (strcmp(cursor->word, wordcheck) == 0)
{
return true;
}
else
{
cursor = cursor->next;
}
}
}
return false;
}
bool load(const char *dictionary)
{
//opens dictionary file
FILE *inputfile = fopen(dictionary, "r");
if (inputfile == NULL)
{
return false;
}
//initializes new node pointer and reads words from new file while !EOF
char word[LENGTH + 1];
while (fscanf(inputfile, "%s", word) != EOF)
{
//actually creates and initializes new node( creates space in memory for node using malloc function) and copies word into node while keeping tracking of # of words
node *new_node = malloc(sizeof(node));
if (new_node == NULL)
{
unload();
return false;
}
else
{
strcpy(new_node->word, word);
}
//hashes words in node to determine which linked list to use
int j = hash(new_node->word);
//initializes node pointer to first bucket in hashtable
node *head = hashtable[j];
if (head == NULL)
{
//if there is no data in linked list, new_node becomes head of linked list
hashtable[j] = new_node;
}
else
{
//if data exists, node points to next word in list, then head of linked list points to node pointer
new_node->next = hashtable[j];
hashtable[j] = new_node;
}
wordcount++;
fclose(inputfile);
}
return true;
}
I solved it! I had to change the way the hash function was written inside of the load function and rewrite fclose(inputfile) to be outside of one of the curly braces. All errors gone!

How to display contact name or display_name of contact in list off messeges

How could I display the names of the following numbers in my Listview if the numbers are given in the loop.
void FetchAllMessages(){
msgList = new ArrayList<>();
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
if (cursor.moveToFirst()) {
do {
String from = cursor.getString(cursor.getColumnIndex("address"));
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(from));
Cursor phones = getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phones.moveToFirst()){
contactname = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
msgList.add(contactname);
}else{
msgList.add(from);
}
} while (cursor.moveToNext());
}
}
There is no display in my android and it continue to crash.
Any help is much appreciated.
It seems you didn't write code for no contacts check. Try this code
ContentResolver cr = cntx.getApplicationContext().getContentResolver();
//Query to get contact name
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
// If data data found in contacts
ArrayList<String> msgList = new ArrayList<String>();
if (cur.getCount() > 0) {
int k = 0;
String name = "";
while (cur.moveToNext()) {
String id = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Check contact have phone number
if (Integer
.parseInt(cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Create query to get phone number by contact id
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[]{id},
null);
int j = 0;
while (pCur
.moveToNext()) {
// Sometimes get multiple data
if (j == 0) {
// Get Phone number
phoneNumber = "" + pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber.startsWith("+91")) {
phoneNumber = phoneNumber.substring(3, phoneNumber.length());
}
phoneNumber = phoneNumber.replaceAll("\\s", "");
if (phoneNumber.length() == 10) {
// Add contacts names to arrayList
msgList.add(name.toString());
}
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cur.close();

HashMap object in value

My question is, how do I "unwrap" a hashmap value object?
I am able to create, save, and load the hashmap. I am doing a populate then select employee to calculate pay.
Map<Integer, Employee> hm = new HashMap<>();
hID++;
System.out.println("Enter employee first name: ");
String nameF = sc.next();
System.out.println("Enter employee last name");
String nameL = sc.next();
hourly = new HourlyEmployee();
Employee hEmp = new Employee(hourly, nameF, nameL);
System.out.println(hEmp.getName());
hm.put(hID, hEmp);
/*
save()
exit
run
load()
select employee, enter ID
loops to find match
*/
Set<Map.Entry<Integer, Employee>> set = hm.entrySet();
do
{
System.out.println("Enter the empoyee ID");
int id = sc.nextInt();
if (id >= 1000 && id < 1999)
{
System.out.println("***** HOURLY *****");
for (Map.Entry<Integer, Employee> entry : set)
{
if (entry.getKey().equals(id))
{
// this is where I run into the issues. all I get
// with the value is the hash location. I can't
// figure out how to unwrap into the hourly class
// as the object, then edit the values then wrap again.
System.out.println(entry.getValue());
// I understand this is not how you get what I
// need. But this does give me:
//
// "edu.umsl.composition.++++++++.Employee#682a0b20"
}
}
See the code comments.
I found the solution: *partial code
public void selectEmployee() {
Set<Map.Entry<Integer, Employee>> set = hm.entrySet();
do {
System.out.println("Enter the empoyee ID");
int id = sc.nextInt();
if (id >= 1000 && id < 1999) {
System.out.println("***** HOURLY *****");
for (Map.Entry<Integer, Employee> entry : set) {
if (entry.getKey().equals(id)) {
int key = entry.getKey();
Employee hEmp = entry.getValue();
hEmp.getHourlyEmp().getGrossPay();
}
}

As3 Text Manipulation - How to say "if charAt == Carriage Return"?

I currently have a form that disables a send button based on two textfields. The one field is a message box. I want to have it so that a person can't just put in a bunch of enters and spaces. I currently ahve a check for spaces, but charAt just returns a space :/ Here is what I want it to look like:
_sendComposeBtn.visible = true;
// if the length of the message is zero, don't let people send it
if (_messageLength == 0)
{
trace("hiding");
_sendComposeBtn.visible = false;
_realMessage = false;
}
_allSpaces = true;
// start with allSpaces true. If there is a nonspace (or non-enter character then hide send button
for (i = 0; i < _bigMessageTextField.length; i++)
{
if (_bigMessageTextField.text.charAt(i) != " " && _bigMessageTextField.text.charAt(i) != (ENTER_CHARACTER))
{
trace("not a space");
_allSpaces = false;
}
}
if (_allSpaces == true)
{
_sendComposeBtn.visible = false;
}
You can say:
_bigMessageTextField.text.charAt(i) != String.fromCharCode(13)

How to create multiple checkbox in canvas

I get trouble when I try to create a check box in canvas.
My checkbox works well but I don't know how to store value of each item, that mean when user check row 1 , and then they move to another row check box still check row 1, and when user check row 1 and 2 and move to another row, check box will check row 1 and 2.
But I can't find out solution for this problem
modify your code to use selectTodelete as boolean array instead of int, about like shown below
// ...initialization of DataList
boolean[] selectTodelete = new boolean[2]; // instead of int
{ selectTodelete[0] = selectTodelete[1] = false; } // init array
Command editCommand, backCommand,selectCmd, unselectCmd,selectAll;
//...
protected void paint(Graphics g) {
//...
for(int i =0 ; i<countRow; i++ ){
//draw background
//...
if(selectTodelete[i]){ // was selectTodelete == 1
//draw select dot at location for row 'i'
//...
}
// remove: you don't need that anymore: if(selectTodelete == 2) {
//draw select dot...
//}
// draw a checkbox before each item
// ...
}
}
public void commandAction(Command c, Displayable d) {
//...
if(c == selectCmd){
selectTodelete[selectedItem] = true;
}
if(c== unselectCmd){
selectTodelete[selectedItem] = false;
}
if(c == selectAll){
selectTodelete[0] = selectTodelete[1] = true;
}
repaint();
}
//...
}
update - answer to question in comments
I want to get RCID fit to checked it mean when row was checked I can get this id and when I use delete command it will delete all rows were checked
For that, you can expose selectTodelete for use outside of its class with getter, or, better yet, with method like below...
boolean isSelected(int elementNum) {
return elementNum >= 0 && elementNum < selectTodelete.length
&& selectTodelete[elementNum];
} // modelled after javax.microedition.lcdui.Choice.isSelected
...information exposed like that can be further used anywhere when you need it to deal with RCID, like eg in method below:
Vector useSelection(DataList dataList, DataStore[][] ds) {
Vector result = new Vector();
int count = ds.length;
for(int i = 0; i < count; i++ ) {
if (!dataList.isSelected(i)) {
continue; // skip non selected
}
System.out.println("RCID selected: [" + ds[i][5].cellText + "]");
result.addElement(ds[i][5]);
}
return result;
}

Resources