JAVA: Hashmap scanner input lookup - java

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);

Related

How to store different objects of arrayList in memory and later retrieve them?

I am new to Java, and I am stuck at a place here.
I have a student class that has some variables like name, contact no, etc. I have created a method addStuDetails to store the details of student in main class by taking values of these variables from user using scanner.
public class Student extends Person {
private int rollNumber, marks;
public Student(String name, String add, int contactNo, int roll, int mark) {
super(name, add, contactNo);
this.rollNumber = roll;
this.marks = mark;
}
public String toString() {
return "Name: " + Name + " ,Address: " + Address + " ,Contact no:" + ContactNumber + " ,Roll no.: " + rollNumber
+ " ,Marks :" + marks;
}
public void addStuDetails(Student s) {
List<Student> stu = new ArrayList<Student>();
Student sObj = new Student(Name, Address, ContactNumber, rollNumber, marks);
stu.add(sObj);
System.out.println(stu);
}
}
Following in the main class where the user enters the values:
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the details of student: ");
System.out.print("Enter name: ");
String name = input.nextLine();
System.out.println("Enter address: ");
String address = input.nextLine();
System.out.println("Enter contact no: ");
int no = input.nextInt();
System.out.println("Enter rollno: ");
int roll = input.nextInt();
System.out.println("Enter marks");
int marks = input.nextInt();
Student s = new Student(name,address,no,roll, marks);
s.addStuDetails(s);
}
The details are added in the above created arrayList and gets printed. Now, I want to store all the students that user created in the mail class in the memory and then retrieve the same using roll no. Can anyone please help on how to do the same? Please note that I don't want to store these students in ant database or file, only in the memory.
It doesn't make sense for Student to contain a List of students, it's beyond it's scope of responsibility.
Instead, List should be independent of it, for example...
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main();
}
private List<Student> students = new ArrayList<Student>();
public Main() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the details of student: ");
System.out.print("Enter name: ");
String name = input.nextLine();
System.out.println("Enter address: ");
String address = input.nextLine();
System.out.println("Enter contact no: ");
int no = input.nextInt();
System.out.println("Enter rollno: ");
int roll = input.nextInt();
System.out.println("Enter marks");
int marks = input.nextInt();
Student s = new Student(name, address, no, roll, marks);
students.add(s);
}
}
nb: I have a personal dislike for static, as it tends to lead new developers to bad habits 😝
Equally, if you wanted to encapsulate the "student" functionality, you could create a student "manager" class, which maintained the list internally and exposed functionality that could be performed upon it, but that might be beyond the scope of this question

Print with category in java using method overriding in java

how to print Junior, Intermediate,Seniour as string as per age,and must generate roll number and these input must b generated from the user. Ex: junior name:Rahul age:22, roll:1000 intermediate name:prem age:40, roll:1001 senior name: Vamsi age:60, rollno:1002
String name;
static int age;
public static void main(String[] args) {
int size = 3;
DB[] studs = new DB[size];
for (int i = 0; i < size; i++) {
studs[i] = readStudent(i);
}
for (int i = 0; i <studs.length; i++) {
if(age <=30) {
System.out.println( studs[i]);
}else if(age <=40) {
System.out.println("Intermidiate" +" "+studs[i]);
}else {
System.out.println("Seniour" +" "+studs[i]);
}
}
}
static DB readStudent(int i) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name:");
String name = sc.nextLine();
System.out.print("Enter your age:");
int age = sc.nextInt();
DB studs = new DB(name, age);
return studs;
}
}
class juniourStudent extends Student {
String rollno = "juniour";
static int juniourcount = 1000;
juniourStudent(String name, int age) {
rollno = "juniour" + juniourcount++;
}
}
class intermidiateStudent extends Student {
String rollno = "intermidiate";
static int intermidiatecount = 1000;
intermidiateStudent(String name, int age) {
rollno = "intermidiate" + intermidiatecount++;
}
}
class seniourStudent extends Student {
String rollno = " seniour";
static int seniourcount = 1000;
seniourStudent(String name, int age) {
rollno = "seniour" + seniourcount++;
}
}
There are quite a few issues with your code.
Your class structure is counter-intuitive to what you are trying to do. Based on the example output, it seems that you want the rollNo to increase every time a student is made. It also seems to be redundant to create separate classes when the only thing that differs between them is the prefix (like junior, senior, intermediate, etc.). Instead of making multiple classes, why not add an instance variable to your student class. (Also import Scanner so we can use it later for user input, and ArrayList to store the student data) For Example:
import java.util.Scanner;
import java.util.ArrayList;
public class Student {
String name;
String studentType;
int age;
int rollno;
static int schoolRollno = 1000;
Next you should make a proper constructor for your student class consisting of a String name and an int age, and assigning them to the instance variables we declared earlier. We will assign the studentType variable based upon their age, and we will obtain the students rollno from the static variable. We must increment the static variable so the next student will have a different roll number. (You can change the age comparisons to whatever number you need, but these numbers are what I pieced together from your code)
public Student(String name, int age) {
this.name = name;
if(age <= 30) {
this.studentType = "Junior";
}
else if(age <= 40) {
this.studentType = "Intermediate";
}
else {
this.studentType = "Senior";
}
this.age = age;
this.rollno = schoolRollno;
schoolRollno++;
}
The last thing we need to do before we work on our main function is to write a toString() method for our student class. Based upon the output, you might want a method like this:
#Override
public String toString() {
return studentType + " name: " + name + " age: " + age + ", roll: " + rollno;
}
Now we can take a look at the public static void main(String args[]) function. We have a few things we need to do here. Since it appears we do not know the number of students we are going to be adding, we should use an ArrayList. We should also instantiate our scanner here as well:
ArrayList<Student> students = new ArrayList<Student>();
Scanner scan = new Scanner(System.in);
Now we should create a while loop that allows the user to continue inputting students and wish to stop. Personally, I'm a fan of the do/while loop, so I'll do it that way. We'll need to declare our variable outside of the loop so that we can use it as a conditional for the loop.
boolean done = false;
do {
//(inner loop code here)
} while(!done);
//end loop code
Now for the inner loop code. We need to obtain a String (name) from the user and an int (age). Once we obtain the inputs, we want to construct a Student object and add it to our ArrayList. Then, after all that, we want to see if the user wants to input another student (by changing the value of our boolean we used when declaring the first do/while loop according to the user's input). We can do all this using scanner like so:
System.out.println("Enter name:");
String name = scan.nextLine();
System.out.println("Enter age:");
int age = scan.nextInt();
//we use scan.nextLine() here because scan.nextInt() does not read to the end of the line
scan.nextLine();
Student s = new Student(name, age);
students.add(s);
boolean validInput = true;
do {
validInput = true;
System.out.println("Continue? (y/n)");
String input = scan.nextLine();
if(input.equalsIgnoreCase("y")) {
done = false;
}
else if(input.equalsIgnoreCase("n")) {
done = true;
}
else {
validInput = false;
}
} while(!validInput);
Finally, we want to print the students once we are done. We can print all the students in our ArrayList easily using a for-each loop. (This goes at the end of our main(String args[]) method)
for(Student s: students) {
System.out.println(s.toString());
}
TL;DR:
Combine your classes into one student class
Fix the constructor
Add a toString() method
Use an ArrayList to store the students b/c we don't know the number. (DB isn't a class in java, and an array is counter-intuitive when you don't know what size you'll need)
Create a loop that the user can break out of when they wish to
Obtain user input for the name and age, and use this to construct a student object and add it to the ArrayList
Print out all the students in the ArrayList after the loop

Java: Taking a string from user input and storing it in array, corresponding to an integer. Case: Employee Name and ID

I am working on a problem in Java that would ask the user for the ID and the last name of an employee and store each of the responses into an array for say, 20 employees. It does not have to be stored into one array, the arrays can be separate as in one for the employee id's and one for the last names, but I have to be able to print them neatly in the terminal.
The code I have below is a very simple idea of the way the program would be presented to the user. It simply asks "Enter the ID and last name of the employee." After that you enter the number, a space and then the last name. I can split the two using "nextLine().trim()" but I can't seem to store the string into an array.
// IntStringSplit.java
import java.util.Scanner;
import java.util.Arrays;
public class IntStringSplit {
public static void main( String[] args ) {
Scanner input = new Scanner( System.in );
String[] empName = new String[4];
int[] empNum = new int[4];
System.out.println( "Enter the ID and name: ");
for( int counter = 0; counter <= 4; counter++ ) {
int i = input.nextInt();
String s = input.nextLine().trim();
Arrays.fill( empNum, i );
Arrays.fill( empName, s );
}
for( int i2 : empNum )
System.out.printf( "The numbers are: %d%n", i2 );
for( str s2 : empName )
System.out.printf( "The names are: %s%n", s2 );
System.out.println();
}
}
Please see my suggested correction below:
Array.fill() fills the entire array with one value. Use arrayName[index] = value; syntax to add one value at a time.
Make sure your counter stops before it reaches the length of the array. Last index is array length - 1. Less than 4 or less than or equal to 3 in your case. (Would be better to use arrayName.length instead of a number, though.)
// IntStringSplit.java
import java.util.Scanner; import java.util.Arrays;
public class IntStringSplit {
public static void main( String[] args ) {
Scanner input = new Scanner( System.in );
String[] empName = new String[4];
int[] empNum = new int[4];
System.out.println( "Enter the ID and name: ");
for( int counter = 0; counter < 4; counter++ ) {
int i = input.nextInt();
String s = input.nextLine().trim();
empNum[counter] = i;
empName[counter] = s;
}
for( int i2 : empNum )
System.out.printf( "The numbers are: %d%n", i2 );
for( str s2 : empName )
System.out.printf( "The names are: %s%n", s2 );
System.out.println();
}
}
for( str s2 : empName ) is wrong, use
for( String s2 : empName ) instead. Also, a Array is not the ideal way to store such data, because the length is fixed and it can only contain on value. You can use a hasmap instead. It connects a key (the id) to the value (the last name).
HashMap<Integer, String> map = new HashMap<Integer, String>;
map.put(id, lastName);
Here is the the class i have written to take input from the User and retrieve the data after taking inputs.
Inputs needs to be in this format:
Enter the Employee Number followed by Last name:
23 abc
Enter the Employee Number followed by Last name:
21 bfs
Enter the Employee Number followed by Last name:
34 fs
Enter the Employee Number followed by Last name:
23 fig
Enter the Employee Number followed by Last name:
23 78
Results would be like this:
Employer Number is: 23 Last Name is: abc
Employer Number is: 21 Last Name is: bfs
Employer Number is: 34 Last Name is: fs
Employer Number is: 23 Last Name is: fig
Employer Number is: 23 Last Name is: 78
Code:
package com.test;
import java.util.Scanner;
import java.util.ArrayList;
public class IntStringSplit {
public static void main( String[] args ) {
int numberOfLoops= 5;
Scanner scanner = new Scanner(System.in);
ArrayList<Employee> myArray = new ArrayList<Employee>();
int counter=0;
while(counter<numberOfLoops){
System.out.println("Enter the Employee Number followed by Last name: ");
String employeDetails = scanner.nextLine();
String[] splited = employeDetails.split("\\s+");
Employee emp = new Employee();
emp.setNumber(Integer.parseInt(splited[0]));
emp.setLastName(splited[1]);
myArray.add(emp);
counter++;
}
scanner.close();
for(Employee emp: myArray){
System.out.println("Employer Number is: "+emp.getNumber() + " Last Name is: " + emp.getLastName());
}
}
static class Employee {
Integer empNumber;
String lastName;
public int getNumber() {
return empNumber;
}
public void setNumber(Integer empNumber) {
this.empNumber = empNumber;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
}

Using user input to call an integer

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");
}

Combining array indexes

I have created two arrays. One to store names and one to store sales. I am trying to link the indexes of each together so that index 1 from then name array will bring up the value of index 1 of the sales array. I am trying to get it to sort out the sales array and return the max sales and the person that brought in those sales. All the values are inputted by the user including the size of the arrays.
import java.util.Scanner;
import java.util.Arrays;
public class EmpArray {
public static int employee(){
Scanner input = new Scanner(System.in);
int numemp;
System.out.println("Enter how many employees to be compared: \n");
numemp = input.nextInt();
String name[] = new String[numemp];
int annsales[] = new int[numemp];
int maxannsales;
for (int i = 0; i < name.length; i++) {
System.out.println("Enter your name: \n");
String employeename = input.next();
name[i] = employeename;
System.out.println("\n");
}
for (int j = 0; j < annsales.length; j++) {
System.out.println("Enter in your annual sales: \n");
int employeesales = input.nextInt();
annsales[j] = employeesales;
System.out.println("\n");
}
System.out.println("Employee Name: " + Arrays.toString(name));
System.out.println("Total Sales: " + Arrays.toString(annsales));
Arrays.sort(annsales);
//look at page 456 of starting out with java and page 460 of the same book, p.464
System.out.println("Top Salary is : $"+annsales[annsales.length-1]);
maxannsales = annsales[annsales.length-1];
return maxannsales;
}
}
What am I doing wrong I have been at this for two weeks now.
You should make a class to store the date rather than the use two separate arrays.
public class Employee {
private int sales;
private String name;
public Employee(String name, int sales){
this.name = name;
this.sales = sales;
}
public String getName(){
return this.name;
}
public int getSales(){
return this.sales;
}
}
Now store the name and sales as local variables when you read in from your Scanner and pass them to the Employee constructor. You can then create an Employee array[] or ArrayList<Employee> and sort this array/arraylist on Employee.getSales()
Like so:
import java.util.Scanner;
import java.util.Arrays;
public class EmpArray {
public static void main(String[] args){
employee();
}
public static int employee(){
Scanner input = new Scanner(System.in);
int numEmp;
System.out.println("Enter how many employees to be compared: ");
numEmp = input.nextInt();
input.nextLine();
Employee[] employees = new Employee[numEmp];
for (int i = 0; i < numEmp; i++) {
System.out.print("Enter your name: ");
String employeeName = input.nextLine();
System.out.println();
System.out.print("Enter in your annual sales:");
int employeeSales = input.nextInt();
input.nextLine();
System.out.println();
//creates an Employee object based on the constructor defined in Employee
Employee employee = new Employee(employeeName, employeeSales);
employees[i] = employee;
}
//initialize maxSeller to first employee
Employee maxSeller = employees[0];
for(int i = 0; i < employees.length; i++){
//using the getters we created in Employee
System.out.println("Employee Name: " + employees[i].getName());
System.out.println("Total Sales: " + employees[i].getSales());
System.out.println();
//checks if employees[i] sold more than maxSeller
if(maxSeller.getSales() < employees[i].getSales()){
maxSeller = employees[i];
}
}
System.out.println();
System.out.println("Top Seller: " + maxSeller.getName());
System.out.println("Top Sales: " + maxSeller.getSales());
return maxSeller.getSales();
}
}
If you sort the array with the numbers, then that gets sorted. You can find the top or bottom sales amount, but you cannot get the name of the salesperson. The two arrays are not linked in any way, so you cannot expect sorting one to cause the sorting of the other.
You need to take an approach that is fundamentally different., using different data structures.
For instance, one approach would be to have a single Array, but not to make it of String(s) or int(s), but to store both the name and the sales together, as a pair. You could pout the pair into an object as shown by sunrize920, or you could put them both in a map.
Having paired them together into some type of object, you can then have an Array of such objects.
Then, you could sort that array. To do so, you will need to write a custom comparator.
Alternatively, keep your two arrays and don;t do any sorting. Just loop through on and find the largest number. Remember the position of the largest sales number. Then, look up the name in the other array, using the same position.

Categories

Resources