I am a beginner in coding, and I am trying to create a simple program that when a reader types in their name, the program shows how much money they owe. I was thinking of using a Scanner, next(String), and int.
import java.util.Scanner;
public class moneyLender {
//This program will ask for reader input of their name and then will output how much
//they owe me. (The amount they owe is already in the database)
public static void main(String[] args) {
int John = 5; // John owes me 5 dollars
int Kyle = 7; // Kyle owes me 7 dollars
//Asking for reader input of their name
Scanner reader = new Scanner(System.in);
System.out.print("Please enter in your first name:");
String name = reader.next();
//my goal is to have the same effect as System.out.println("You owe me " + John);
System.out.println("You owe me: " + name) // but not John as a string but John
// as the integer 5
//Basically, i want to use a string to call an integer variable with
//the same value as the string.
}
}
As a beginner, You might be want to use a simple HashMap, which will store these mappings as key, value pair. Key will be name and value will be money. Here is example:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class moneyLender {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("John", 5);
map.put("Kyle", 7);
Scanner reader = new Scanner(System.in);
System.out.print("Please enter in your first name:");
String name = reader.next();
System.out.println("You owe me: " + map.get(name)); //
}
}
Output :
Please enter in your first name:John
You owe me: 5
If you want the read the user input as a String, it would be a great idea to use the nextLine() method.
You would also want to create a method which takes a String parameter i.e. the names and returns the owed amount.
public int moneyOwed(String name){
switch(name){
case "Kyle": return 5;
case "John": return 7;
}
}
public static void main(String[] args) {
int John = 5; // John owes me 5 dollars
int Kyle = 7; // Kyle owes me 7 dollars
Scanner reader = new Scanner(System.in);
System.out.print("Please enter in your first name:");
String name = reader.nextLine();
System.out.println(name +" owes me " + moneyOwed(name) + " dollars");
}
Related
I wanna ask if this is possible. So I have this program will enter a for loop to get the user input on number of subjects. Then after he will enter the subjects listed in the array as his guide. My goal is that I want to check his subjects if it is really inside the array that I made. I made a program but I don't know where to put the part that the program will check the contents.
My goal:
Enter the corresponding code for the subjects you have chosen: user will input 8
Enter the number of subjects you wish to enroll: be able to type the whole subject name like (MATH6100) Calculus 1
then the program will check if the subjects entered are part of the elements inside the array
UPDATE:
I have made another but the problem is that I don't know where to put the code fragment wherein it will check the contents of the user input for list of subjects he wish to enroll.
Here is the code:
private static void check(String[] arr, String toCheckValue){
boolean test=Arrays.asList(arr).contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
public static void main(String[] args){
String arr[]={"(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1", "(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1", "(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1"};
Scanner input1=new Scanner(System.in);
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int number_subjects1=input1.nextInt();
String []subjects1=new String[number_subjects1];
//else statement when user exceeds the number of possible number of subjects
if(number_subjects1<=8){
for(int counter=0; counter<number_subjects1; counter++){
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): " + (counter+1));
subjects1[counter]=input1.next();
}
String toCheckValue=subjects1[0];
System.out.println("Array: " +Arrays.toString(arr));
check(arr, toCheckValue);
System.out.println("\nPlease check if these are your preferred subjects:");
for(int counter=0; counter<number_subjects1; counter++){
System.out.println(subjects1[counter]);
}System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character=new Scanner(System.in);
String answer_1subjectserrors=character.nextLine();
System.out.println(answer_1subjectserrors + "Based on your answer, you need to refresh thae page and try again.");
}
}
}
I believe the issue is that you are checking your class course codes against an array which contains both the class code AND the class description.
You ask the user to enter the class code but then you use that code to check for its existence in an array containing both the code & description. The contains in List (collections) is not the same as the contains in String.
I have slightly modified your code so you may get the desired result.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);;
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
public static void main(String[] args) {
String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
Scanner input1 = new Scanner(System.in);
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int number_subjects1 = input1.nextInt();
String[] subjects1 = new String[number_subjects1];
// else statement when user exceeds the number of possible number of subjects
if (number_subjects1 <= 8) {
for (int counter = 0; counter < number_subjects1; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects1[counter] = input1.next();
}
String toCheckValue = subjects1[0];
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
check(class_codes, toCheckValue);
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < number_subjects1; counter++) {
System.out.println(subjects1[counter]);
}
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
}
}
When you are debugging always try to break down the statements into steps so you know where the error is. For example instead of boolean test=Arrays.asList(arr).contains(toCheckValue);
break it down to two steps like this :
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
That way you will have an easier time checking for issues.
Second request is to always look at the API. Skim over the API to look at the method that you are using to understand it better.
For example if you are using contains method of List then look up the API here:
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/List.html#contains(java.lang.Object)
Of course since this is Oracle's Java the explanation is imprecise & not straightforward but it is usually helpful.
I would recommend using a different data structure than plain arrays. Since you are already using List why not use another collections data structure like HashMap?
The original poster may want to look at a slightly refactored and cleaned up version of the code & try to figure out how to check for all courses since that is his next question. I believe that should become obvious with a more refactored code:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
public static String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
public static String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int desired_number_of_subjects = input_desired_number_of_subjects(input);
String[] desired_subjects = enter_subjects(desired_number_of_subjects, input);
String toCheckValue = desired_subjects[0];
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
check(class_codes, toCheckValue);
pls_confirm_desired_subjects(desired_number_of_subjects, desired_subjects);
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
private static int input_desired_number_of_subjects(Scanner input) {
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int take_number_of_subjects = input.nextInt();
// TODO: else statement when user exceeds the number of possible number of subjects
return take_number_of_subjects;
}
private static String[] enter_subjects(int desired_subjects_count , Scanner input_desired_subjects) {
String[] subjects_totake = new String[desired_subjects_count];
if (desired_subjects_count <= 8) {
for (int counter = 0; counter < desired_subjects_count; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects_totake[counter] = input_desired_subjects.next();
}
}
return subjects_totake;
}
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
private static void pls_confirm_desired_subjects(int take_number_of_subjects, String[] take_subjects) {
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < take_number_of_subjects; counter++) {
System.out.println(take_subjects[counter]);
}
}
}
I will shortly edit the above but a hint is : you can use a for loop to go over the entered desired_subjects array and do a check on each one of the subjects, perhaps?
The following checks for all the courses (though this is not how I would check the courses)
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
public static String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
public static String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int desired_number_of_subjects = input_desired_number_of_subjects(input);
String[] desired_subjects = enter_subjects(desired_number_of_subjects, input);
check_all_desired_subjects(desired_subjects);
pls_confirm_desired_subjects(desired_number_of_subjects, desired_subjects);
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
private static int input_desired_number_of_subjects(Scanner input) {
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int take_number_of_subjects = input.nextInt();
// TODO: else statement when user exceeds the number of possible number of subjects
return take_number_of_subjects;
}
private static String[] enter_subjects(int desired_subjects_count , Scanner input_desired_subjects) {
String[] subjects_totake = new String[desired_subjects_count];
if (desired_subjects_count <= 8) {
for (int counter = 0; counter < desired_subjects_count; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects_totake[counter] = input_desired_subjects.next();
}
}
return subjects_totake;
}
private static void check_all_desired_subjects(String[] desired_subjects) {
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
for (String subject_code_to_check:desired_subjects ) {
check(class_codes, subject_code_to_check);
}
}
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
private static void pls_confirm_desired_subjects(int take_number_of_subjects, String[] take_subjects) {
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < take_number_of_subjects; counter++) {
System.out.println(take_subjects[counter]);
}
}
}
All I want it to do is read input typed by the user as double type, and then convert it to another number. I'm also aware the equation isn't complete, not worried about that right now, just want it to run. I don't understand what I have done wrong.
public class EuroShoe {
public static void main(String[] args) {
double
footLength,
euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
footLength = Keyboard.readDouble(); // line 25
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
If you are following a tutorial, please check on the imports that were mentioned. But to answer your question and make your program work here's an answer.
import java.util.Scanner
public class EuroShoe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i =
double footLength, euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
// The statement below calls the "scanner" object to get the user input of value "double"
footLength = scanner.nextDouble();
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
Make sure to put this statement above
import java.util.Scanner // imports the specific Scanner class under the 'util' namespace
or you can use this as well
import java.util.* // imports every class under the 'util' namespace
Hope this helps you with your problem and keep coding! :)
This worked:
package euroshoe;
import java.util.Scanner;
public class EuroShoe {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
double footLength = input.nextDouble();
double euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.
I am relatively fresh (couple weeks) into Java and I am messing around with an Employee input system with ArrayLists. Anyway I want to ensure no matter the user input that that name in the output is the same format.
Example:
Input --> Enter Employee Name: SAMANTHA
Output --> Employee Name: Samantha
Here is the code I am running, I am just not sure where within this I could set that formatting.
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + first.get(i) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
}
First thing you should do is to check out String API https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
It's a must-know when it comes to Java, you'll need it in possibly every project you'll work on :)
There are plenty of ways to achieve your goal here.
What you could do for example is to capitalize the first letter and then append the rest of the String that you'll force to lowercase - check out the snippet below.
String inputString = input.next();
String resultString = inputString.substring(0, 1).toUpperCase() + inputString.substring(1).toLowerCase();
Try like this :
System.out.print("Employee Name: " + first.get(i).substring(0,1).toUpperCase()+first.get(i).substring(1).toLowerCase() + " ");
this one first.get(i).substring(0,1).toUpperCase() gest your first letter in string upper, and first.get(i).substring(1).toLowerCase() gets letters from index 1 - so from the 2nd letter of the string to lower.
Maybe what the OP is not understanding, is that this can be wrapped in a private method, like this:
private String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
Then your line uses this by adjusting the line that prints the name:
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
You can then reuse this function on the last name too...
Here is the entire class with this change:
package Dunno;
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
//New Method to fix capitalisation
private static String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
I hope my answer might help you to understand the answers already given better, and how the duplicate answer i provided is relevant - the use of an ArrayList here makes no difference to the String manipulation.
You should consider defining your own class of "Employee", that can persist the name, salary etc. then you only need one ArrayList, you currently have lists with values that are Logically linked by their position in the Array, but there is no technical dependency on that.
Im trying to create a classthat will store a table of people's first names and ages, and read people and ages from the console (e.g. Bob 19) and add to the HashMap. After a list of name, age pairs, a name will be entered without an age (e.g. Bob) and the user will terminate their input (ctrl-z). Print out the age of the person entered last, or print "unknown" if an age hasnt been entered for them. so for example if i entered "mary 12, bob 10, jon 20, bob" it should return 10.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Hashmap {
public static void main(final String[] args) {
HashMap<String, Integer> names = new HashMap<String, Integer>();
ArrayList<String> nameArray = new ArrayList<String>();
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String name = in.next();
nameArray.add(name);
Integer age = in.nextInt();
names.put(name, age);
}
Integer value;
int x = nameArray.size();
value = names.get(x);
System.out.println("the age is:" + value);
}
}
thanks for the help. I am a Java beginner and appreciate it all
Move name variable declaration out of while and get the age using the last name entered. Here you go:
String name
while (in.hasNext()) {
name = in.next();
nameArray.add(name);
Integer age = in.nextInt();
names.put(name, age);
}
Integer value;
value = names.get(name);
System.out.println("the age is:" + value);