I have created the object of Dictionary class and i am inserting values in it. and on displaying i am getting all the values that i pushed in the dictionary. but while searching i am unable to get particular key value pair from dictionary.
class Demo{
static String newLine = System.getProperty("line.separator");
public static void main(String[] args) {
int ch=0,num=0;
String dictionary,contactName,contactNumber,relation;
Scanner in=new Scanner(System.in);
System.out.println(newLine + "Dictionary in Java" + newLine);
System.out.println("-----------------------" + newLine);
System.out.println("Adding items to the Dictionary" +
newLine);
Dictionary dict = new Hashtable();
while(ch!=4){
System.out.println("1. Insert Contact Details\n2. Display
Contact Details\n3. Search Contact Details\n4. Exit");
System.out.println("Enter Your Choice:");
ch=Integer.parseInt(in.nextLine());
switch (ch)
{
case 1:
System.out.println("How many Contacts you want to
insert:");
num=Integer.parseInt(in.nextLine());
for(int i=0;i<num;i++)
{
System.out.println("Enter the name of Contact Number
"+(i+1)+":");
contactName=in.nextLine();
System.out.println("Enter the Contact Number of
"+contactName+":");
contactNumber=in.nextLine();
dict.put(contactName, contactNumber);
}
System.out.println(newLine + "Items in the
dictionary..." + dict + newLine);
System.out.println("-----------------------" + newLine);
break;
case 2:
System.out.println(newLine + "Items in the
dictionary..." + dict + newLine);
System.out.println("-----------------------" + newLine);
break;
case 3:
System.out.println("Enter Name you want to search:");
String name=in.nextLine();
System.out.println(dict.get(name));
break;
}
}
And this is my output:
Dictionary in Java
-----------------------
Adding items to the Dictionary
1. Insert Contact Details
2. Display Contact Details
3. Search Contact Details
4. Exit
Enter Your Choice:
1
How many Contacts you want to insert:
2
Enter the name of Contact Number 1:
qwe
Enter the Contact Number of qwe:
123
Enter the name of Contact Number 2:
asd
Enter the Contact Number of asd:
12332
Items in the dictionary...{qwe=123, asd=12332}
-----------------------
1. Insert Contact Details
2. Display Contact Details
3. Search Contact Details
4. Exit
Enter Your Choice:
2
Items in the dictionary...{qwe=123, asd=12332}
-----------------------
1. Insert Contact Details
2. Display Contact Details
3. Search Contact Details
4. Exit
Enter Your Choice:
3
Enter Name you want to search:
1
null
please help me out.
Your code works fine, but you're entering the wrong search term. Instead of entering 1, you should have entered either que or asd, the names of the contacts.
If you want to print both name and contact number, then change your println as it will only print what you tell it to. Change this:
System.out.println(dict.get(name));
to this:
System.out.println("Name: " + name + ", contact: " + dict.get(name));
or something similar.
Related
I'm still new to Stack and Java so let me clarify the question as best as I can. I'm currently learning OOP in Java and I have an assignment that requires us to create a voucher system where essentially the user inputs some information about a purchase, that information is assigned to a voucher, and then once paid the voucher is then assigned a check number.
Now, I have the Voucher Class set up and I believe it's set up correctly, but my issue is with the VoucherDriver. My VoucherDriver has all of the code for the user input, and my VoucherClass has all of my variables and my array for the vouchers themselves. Here is the VoucherClass code:
public class Voucher {
private static int nextVoucherNumber, nextCheckNumber;
private int _voucherNumber,_checkNumber;
private static Voucher[] vouchers;
private String _purchaseDate, _paymentDate, _debitAccount, _vendor;
private double _amount;
Voucher(String purchaseDate, double amount, String debitAccount, String vendor) {
this._purchaseDate = purchaseDate;
this._amount = amount;
this._debitAccount = debitAccount;
this._vendor = vendor;
this._voucherNumber = nextVoucherNumber;
//checks if the array is full
for (int i = 0; i < vouchers.length; ++i) {
if (vouchers[i] == null) {
vouchers[i] = this;
nextVoucherNumber++;
break;
}
}
}
//must call this method first to initialize the vouchers
public static void initialize(int firstVoucher, int firstCheck, int maxNumberOfVouchers) {
nextVoucherNumber = firstVoucher;
nextCheckNumber = firstCheck;
vouchers = new Voucher [maxNumberOfVouchers];
}
public static Voucher find(int voucherNumber) {
for (Voucher v : vouchers) {
if (v != null && v._voucherNumber == voucherNumber) {
return v;
}
}
return null;
}
public static void printData() {
int count = 0;
for (Voucher v : vouchers) {
if (v != null) {
System.out.println(v);
count++;
} else {
break;
}
}
if (count == 0) {
//System.out.println("No Data.");
}
}
#Override
public String toString() {
return "Voucher #" + _voucherNumber + " Date: " + _purchaseDate + " Amount:$" + _amount + "\n"
+ "Account: " + _debitAccount + " Vendor: " + _vendor + "\n" + "Check #:" + _checkNumber + " Date:" + _paymentDate + "\n";
}
public void issueCheck(String paymentDate) {
this._paymentDate = paymentDate;
this._checkNumber = nextCheckNumber;
nextCheckNumber++;
}
}
How can I set the users input on the VoucherDriver, to equal a variable or method on the VoucherClass? Is that even possible or am I going in circles for no reason? I'll post some code snippets from my VoucherDriver below for extra clarification:
public class VoucherDriver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choiceSelection;
Voucher.initialize(1001, 2001, 10);
System.out.println("XYZ COMPANY Voucher Manager \n");
do {
System.out.println("Activities available: \n "
+ "1.Create a voucher \n "
+ "2.Print a voucher register \n "
+ "3.Issue checks");
System.out.println("Enter number of choice (or zero to quit): ");
choiceSelection = sc.nextInt();
if (choiceSelection == 1) {
System.out.println("Enter purchase date (dd/mm/yyyy): ");
sc.next();
System.out.println("Enter amount: ");
sc.nextDouble();
System.out.println("Enter name of account to debit: ");
sc.next();
System.out.println("Enter name of vendor: ");
sc.next();
System.out.println();
}
if (choiceSelection == 2) {
System.out.println();
}
if (choiceSelection == 3) {
System.out.println("Enter number of voucher to pay: ");
sc.nextInt();
System.out.println("Enter payment date (dd/mm/yyyy): ");
sc.next();
}
} while (choiceSelection != 0);
}
}
Initially, I had set new variables in the Driver to store the user input, however, I don't think that would work since those variables won't be "connected" to the variables on the VoucherClass, hence the scanner sc not having variables set to the left within the if statement.
I also tried calling my Voucher constructor method but I don't think I even did that right when I attempted to do so. If anyone can provide some insight on what I'm doing incorrectly, I would be most grateful.
A user commented that adding the assignment specs may be helpful, here is the sample session:
XYZ COMPANY Voucher Manager
Activities available:
create voucher
print voucher register
issue checks
Enter number of choice (or zero to quit): 4
Invalid choice. Try again.
Activities available:
create voucher
print voucher register
issue checks
Enter number of choice (or zero to quit): 1
Enter purchase date (dd/mm/yyyy): 17/08/2003
Enter amount: $123.45
Enter name of account to debit: tools
Enter name of vendor: Mack's Hardware
Activities available:
create voucher
print voucher register
issue checks
Enter number of choice (or zero to quit): 1
Enter purchase date (dd/mm/yyyy): 15/09/2003
Enter amount: $67.42
Enter name of account to debit: supplies
Enter name of vendor: ABC Company
Activities available:
create voucher
print voucher register
issue checks
Enter number of choice (or zero to quit): 2
Voucher Register:
voucher #1001 date: 17/08/2003 amount: $123.45
account: tools vendor: Mack's Hardware
check #0 date: null
voucher #1002 date: 15/09/2003 amount: $67.42
account: supplies vendor: ABC Company
check #0 date: null
Activities available:
create voucher
print voucher register
issue checks
Enter number of choice (or zero to quit): 3
Enter number of voucher to pay: 1000
No vouchers have that number.
Enter number of voucher to pay: 1001
Enter payment date (dd/mm/yyyy): 08/01/2004
Activities available:
create voucher
print voucher register
issue checks
Enter number of choice (or zero to quit): 2
Voucher Register:
voucher #1001 date: 17/08/2003 amount: $123.45
account: tools vendor: Mack's Hardware
check #2001 date: 08/01/2004
voucher #1002 date: 15/09/2003 amount: $67.42
account: supplies vendor: ABC Company
check #0 date: null
Activities available:
create voucher
print voucher register
issue checks
Enter number of choice (or zero to quit): 0
Collection like a list will be better approach to store Vouchers - btw. you can create list of 'Voucher' as a field in VoucherDriver. Then you dont need to initialize your Vouchers.
Assign scanner.nextLine/nextInt/nextString to variable (for validation e.q. Date if needed) and create new Voucher object using constructor at the end of if statement in main method. And add object to the list.
You don't need to use underscore in class fields if you are using this.
So it's been about 6 months since I've done anything with coding as well as I'm still relatively new to it. I'm doing some review and the program asks for several attributes, in which one is a string asking for an employee's ID #. It is supposed be in a loop, in which the loop is terminated when the user enters 0 for their employee ID. I have the program working up until this point and I haven't created the loop yet which is where I am stuck.
`import java.util.Scanner;`
`public class PayrollTester {`
`public static void main(String[] args) {`
`String empID;`
`float gross;`
`float ste;`
`float fed;`
`Scanner scnr = new Scanner(System.in);`
`System.out.println("Enter your Employee ID: ");`
`empID = scnr.nextLine();`
`System.out.println("Enter your Gross Pay: ");`
`gross = scnr.nextFloat();`
`System.out.println("Enter your State Tax Rate: ");`
`ste = scnr.nextFloat();`
`System.out.println("Enter your Federal Tax Rate: ");`
`fed = scnr.nextFloat();`
`Payroll empID1 = new Payroll(empID, gross, ste, fed);`
`System.out.println("The Net Pay for Employee " +
empID1.getEmplyeID() + " is " + empID1.calcNetPay());`
`}`
`}`
You can just do a while(true) loop and then you have an if statement right after they enter their employee id that checks to see if the value they entered is equal to 0.
while(true){
//get their employee id
if (empiID.equals("0")){
break;
}
//get more user inputs
}
This question says ask for the 'First Name' and the 'Last Name' from the user and then show the message Welcome with the full name of the user . also make sure that the user does not enter his/her full name in the first Text Field which asks for First Name only
I thought that if the user enters his/her full name in the first text field , we can know that from the fact that he/she entered a space or (' ') or not . If not we can simply show the message Welcome + full name . However it didn't work the way I thought it would ... Can somebody help me with itenter image description here
If I understand you the below will work accomplish what you need by ignoring the data after the space and asking the user for their last name.
code:
public static void main(String[] args) {
// Properties
Scanner keyboard = new Scanner(System.in);
String firstName, lastName
// Ask the user for their first name
System.out.println("What is your first name? ");
System.out.print("--> "); // this is for style and not needed
firstName = keyboard.next();
// Ask the user for their last name
System.out.println("What is your last name? ");
System.out.print("--> "); // this is for style and not needed
lastName = keyboard.next();
// Display the data
System.out.println("Your first name is : " + firstName);
System.out.println("Your last name is : " + lastName);
}
There is actually a few ways you can do this, but if I understand your question correctly a simple way would be below, which is from http://math.hws.edu/javanotes/c2/ex6-ans.html and helped me understand Java more when I was learning it, you just would alter it to your needs.
code:
public class FirstNameLastName {
public static void main(String[] args) {
String input; // The input line entered by the user.
int space; // The location of the space in the input.
String firstName; // The first name, extracted from the input.
String lastName; // The last name, extracted from the input.
System.out.println();
System.out.println("Please enter your first name and last name, separated by a space.");
System.out.print("? ");
input = TextIO.getln();
space = input.indexOf(' ');
firstName = input.substring(0, space);
lastName = input.substring(space+1);
System.out.println("Your first name is " + firstName + ", which has "
+ firstName.length() + " characters.");
System.out.println("Your last name is " + lastName + ", which has "
+ lastName.length() + " characters.");
System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
}
}
edit:
If this doesn't make sense I can give a better explanation with a better example with more detail.
More notes on similar problems.
https://www.homeandlearn.co.uk/java/substring.html
The problem with your code is, that you check every single charackter and then do the if/else for every single charackter. which means if the last charackter is not a whitespace it will at the end process the else tree.
The solution is to just check once:
if(fn.contains(' '){
//Do what you want to do, if both names were entered in the first field
}else{
//Everything is fine
}
I am using the scanner in java and am trying to enter a space in my input for option 2 (removing a user from my hashmap) but when I add a space in my answer I get an InputMismatchException. while researching I came across this thread Scanner Class InputMismatchException and Warnings that says to use this line of code to solve the issue: .useDelimiter(System.getProperty("line.separator")); i have added this and now my option 2 goes into a never-ending loop of me inputting data. Here is my code:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
choice = scan.nextInt();
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
Address address = new Address();
key = lastName.concat(firstName);
Person person = new Person(firstName,lastName);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.println("Please enter name of user to remove: ");
scan.useDelimiter(System.getProperty("line.separator"));
key=scan.next();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
ad1.listAllContacts();
}
else if(choice==5){
//Sort contacts
}
}while(choice!=6);
}
}
The reason why I need to use a space is to remove a user from my hashmap I need to enter their full name as the key is a concatenation of their last and firstname, any help will be appreciated
nextInt() behaves similar to next() that is when it read a line it places the cursor behind it.
Example:
You give 6 as input
6
^(scanner's cursor)
So next time when you call nextLine(). It will return the whole line after that cursor which is empty in this case.
To fix this issue you need to call an extra nextLine() so that the Scanner closes the previous line it was reading and move on to the next line.
You could do this
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
And in choice 2 since you want full name of user you could just use nextLine() to get whole line along with space.
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
Or you could do something similar to what you did in choice 1
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception
I'm sort of new at working with Java. I'm working on a program that takes in student names and their IDs, and when the correct ID is inputted afterwards, it spits out that student's information. The sample output would sort of look like this: How many students would you like to input? (2) What are their names? (Sally, Jack) What are their IDs? (2332, 5631) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally!
Here is a snippet of the code that searches back for the Student:
System.out.println("Would you like to search for a student?");
String answer = scan.next();
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
int id = scan.nextInt();
boolean found = Student.lookupID(list, id);
if(found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); //fix this
else
System.out.println("Error");
}
else {
System.out.println("Thanks for using this system!");
}
}
}
Right now, I'm trying to loop the code, so that the Output would now look like this: How many students would you like to input? (3) What are their names? (Sally, Jack, Rick) What are their IDs? (2332, 5631, 3005) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally! Would you like to search for another student? (Y) Please input their ID: (5631) We found Jack! Would you like to search for another student? (N) Thanks for using our system!
Would someone be able to help me with this?
You need to reset id to program be able to get new id.Try correct your code like this :
System.out.println("Would you like to search for a student?");
String answer = scan.next();
int id = 0; //RESET THE ID TO BE ABLE REPLAYIN WORK!
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
id = scan.nextInt();
boolean found = Student.lookupID(id);
if (found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); // fix
// this
else
System.out.println("Error");
} else {
System.out.println("Thanks for using this system!");
}