Hashmap output in console - java

I'm working on little "project" for saving some data in a Hashmap which I want to print out later in my console.
I've almost finished with the whole code but I'm having problems with giving it out in my console...
My code so far is:
import java.util.HashMap;
import java.util.Scanner;
public class Passwordsaver` {
public static void main(String[] args) throws InterruptedException {
// declare the hashmap
HashMap<Integer, String> Password = new HashMap<>();
boolean loopAgain = true;
Scanner scan = new Scanner(System.in);
// loop while user not entering no
do {
// ask for account (page)
System.out.print("Enter Page:");
String page = scan.nextLine();
// ask for password
System.out.print("Enter Password");
String password = scan.nextLine();
// add the key value pair from user input to the hashmap
String oldVal = password + page;
if (oldVal!=null) {
System.out.println("The password for the page: " + page + " is "
+ password + " and will be overwritten if entered again");
}
// ask user to check if another entry is required
System.out.print("Enter another account (y/n)?");
String answer = scan.nextLine();
// condition to satisfy in order to loop again
loopAgain = (answer.equals("y") || answer.equals("Y"));
} while (loopAgain);
scan.close();
System.out.println("\n**********************************");
System.out.println("The following accounts are in database");
System.out.println(" account "+ " password");
for(int page:Password.keySet()){
System.out.println(" "+ Password +" "+Password.get(page));
}
System.out.println("\n**********************************");
}
}
Everything works except the last step...How can I print it?
Is there also a possibility to save the data so at a later time I can still change the map without having Eclipse opened the whole time?
Many thanks in advance!!!

You are printing the full HashMap (Password) and not the key of every entry.
Have a look at the following loop:
for(int page:Password.keySet()){
System.out.println(" "+ page +" "+Password.get(page));
}
Here we print the key and the value of the entry.
In terms of performance, it's better to iterate over the entrySet, so you do not have the additional cost of a look up:
for(Map.Entry<Integer,String> entry:Password.entrySet()){
System.out.println(" "+ entry.getKey() +" " + entry.getValue());
}
EDIT
In addition you forgot to store the page/password combination in your hashmap. Add
Password.put(page, password) to store the data.
You also have to change the type to the HashMap to HashMap<String,String>

The following code will work:
Map<Integer, String> passwords = ...
for (Map.Entry<Integer, String> entry : passwords.entrySet()) {
// iterates over every entry in the map, creates a variable called "entry"
int key = entry.getKey();
String value = entry.getValue();
// now you can print with whatever formatting you want. e.g.:
System.out.println("account: " + key + ", password: " + password);
}
Or, using Java 8 functional style code:
passwords.forEach((key, value) -> {
System.out.println("account: " + key + ", password: " + password);
});
If you want to store the data, take a look JSONs, and the Jackson Databind library. This is a library to map Java objects to JSONs, and back (this isn't all it does, but just one of the features). In short, you can convert your Map to and from a String, so that it can be saved to a file/sent over the network/etc.

Related

How can I make sure that the user did not enter his/her entire name in the First Text Field named as "First Name"

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
}

Java Method to find a match in ArrayList

I have the following method in a program of mine that allows a user to enter a unique ID that is associated with a laptop in an ArrayList.
The desired output is as follows:
If the ID entered by the user matches an ID in the ArrayList, the laptop and its specifications will print out.
If the ID does not match, it will print out "Invalid ID".
I am very close to achieving this; however I can only figure out how to get it to print whether or not it matches for each laptop in the list. So for example, if the ID entered by the user matches one of three laptops in the list it will print as follows:
Acer Predator Helios 300 CPU: Intel i7-9750h GPU: NVIDIA GTX1660ti Memory: 16GB ID: 1234567
Invalid ID.
Invalid ID.
So my question is: how do I get it to print ONLY the single match or "Invalid ID" while still being able to loop through the entire list to check for a match? Not necessarily asking you to spoon feed me the fix, but at least help point me in the right direction or help with the logic. I thank you in advance for any help!
My method is as follows:
private static void findLaptop(ArrayList arr) {
//Prompt user to input an ID.
System.out.println("Input ID: ");
System.out.println();
//Scan for user input.
Scanner keyboard = new Scanner(System.in);
int inputId = keyboard.nextInt();
//Loop through ArrayList and check for a match.
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == ((Laptops) arr.get(i)).getId()) {
System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " +
((Laptops)arr.get(i)).getId());
}
//If entered ID does not match, print invalid ID.
else if(inputId != ((Laptops) arr.get(i)).getId()) {
System.out.println("Invalid ID.");
}
}
}
Use below code:
//Create a boolean
boolean found= false;
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == ((Laptops) arr.get(i)).getId()) {
System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " +
((Laptops)arr.get(i)).getId());
//set boolean true and break
found = true;
break;
}
}
//Out side the look check If entered ID does not match, print invalid ID.
if(!found) {
System.out.println("Invalid ID.");
}
You can do this using a return statement that is used after printing a match
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == (arr.get(i)).getId()) {
System.out.println((arr.get(i)).getModel() + " CPU: " + (arr.get(i)).getCpu() + " GPU: " +
(arr.get(i)).getGpu() + " Memory: " + (arr.get(i)).getMemory() + "GB ID: " +
(arr.get(i)).getId());
return;
}
}
// outside loop
System.out.println("Invalid ID.");
edit
If you have you ArrayList set up properly as ArrayList<Laptop> then you would not need all those crazy casts.
edit2
If you a foreach loop it would be even cleaner
for (Laptop lt : arr) {
if (iputId == lt.getId()) // etc
Supposing you have a class called Laptop as follows:
public class Laptop {
private String id;
private String manufacturer;
// other fields
// getters and setters
}
You can find matches with an id using Java 8 Streams:
List<Laptop> laptops = ...
String idToSearch = "something";
Optional<Laptop> result = laptops.stream() // convert into stream for easier handling
.filter(l -> l.getId().equals(idToSearch)) // find only laptops with a matching id
.findFirst(); // find the first one, if present
The variable result is an Optional<Laptop>, meaning it may or may not contain a Laptop value. You can consume this result as follows:
Laptop laptop = result.get(); // throws an exception if no value present, not reccomended
Laptop laptop = result.orElse(null); // returns null if no value present
result.ifPresent(laptop -> {
doSomething(laptop); // this function is only called if a value is present
})

How do write several Java codes using Strings and while loop with JOptionPane

I am in beginning Java. I have been trying for several days to figure how to code the following:
Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane.
In the loop, check if the user selects OK of Cancel without entering data, if so prompt the user until valid data is entered.
Separate the name, phone, and email into separate String variables.
In the loop, check if the name is 10 characters or less, if not, prompt the user until valid data is entered.
If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user.
Display the contents in a JOptionPane using the get methods.
Even if someone can help me with just the "Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane."
and/or
"If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user." code.
I can figure out the rest I'm sure. And yes, I know how to spell Sunflower...the A was on purpose. Thank you to anyone who helps. I really appreciate it!
This is what I have: (the Contact class info is posted below) I am learning how to clean this code up to be more efficient. I was going to delete from about Line 19 on after I figured our how to do the while loop. For now, I get all excited when I actually get a code to work.
import javax.swing.*;
public class TestContact
{
public static void main(String[] args)
{
Contact mycontact = new Contact();
mycontact.setName("Tanya Smith");
mycontact.setPhone("440-226-2866");
mycontact.setEmail("tanya#gmail.com");
JOptionPane.showMessageDialog(null,
"The Contact's information is:\n Name: " + mycontact.getName() +
"\n Phone Number: " + mycontact.getPhone () +
"\n Email: " + mycontact.getEmail());
JOptionPane.showInputDialog(null, "Please enter your Name: " );
while Name.equals()
String Info = JOptionPane.showInputDialog(null, "Please enter you Name, Phone Number and Email");
String[] word = Info.split(" ");
String AllInfo =
Character.toString(word[0].charAt(0)) +
Character.toString(word[1].charAt(0)) +
Character.toString(word[2].charAt(0)) +
Character.toString(word[3].charAt(0));
JOptionPane.showMessageDialog(null, "Your Name: " + word[0] + " " + word[1] +
"\nYour Phone: " + word[2] +
"\nYour Email: " + word[3]);
}
}
I figured out how to do it one way with the Character.toString, but not with using the while loop.
While I don't approve of simply asking for code, you do sound legitimately stuck, and confused. I'm also waiting on a 4 gig transfer over a very slow network connection, so here's a bit to get you started. This should get you most of the way. Next time try to post whatever you came up with, regardless of how off base you think it might be. A least we know you're not just asking for code.
public static void main(String [] args) {
promptForData();
}
public static void promptForData() {
boolean cont = true;
while (cont) {
String input = JOptionPane.showInputDialog("Enter name phone and email space delimited.");
cont = !validData(input);
}
}
public static boolean validData(String input) {
String[] parts = input.split(" ");
if (parts.length != 3) return false;
if (parts[0].length() < 11) return false;
return true;
}
"Even if someone can help me with just the "Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane."
Pseudo code
String name;
String phone;
String email;
String input;
String[] array;
while name.length() > 10 or name is null
input = JOptionPane...
array = input.split(....)
name = first array index
// end loop
phone = second array index
email = third array index
""If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user." code."
Pseudo code
class Contact
String name;
String phone;
String email
Contact (constructor taking the three field type arg)
this field = an argument
.... // two more
After the loop from the first part after get the valid input
Contact contact = new Contact( fill in the args)

Returning an Array results within a method

Problem solved.
I have two methods in my class.
private void retrieveDetails(){
List<String> details = File.getCredentials();
username = details.get(0);
pw = details.get(1);
}
private void checkCredentials() throws IOException {
retrieveDetails();
System.out.println("\nPlease enter USERNAME: ");
String usersName = scan.next();
System.out.println("\nPlease enter PASSWORD: ");
String usersPW = scan.next();
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw);
if (usersName.equals(username) && usersPW.equals(pw)) {
doWork();
} else {
System.out.println("Incorrect credentials");
}
}
I thought I came up with a solution by moving the following up to where my strings are initialized.
List<String> creds = File.getCredentials();
I created a System.out statement to check if the details coming from retrieveDetails() match those entered by the users. They do match - but when the system goes to the else clause instead of executing doWork();
If what is printed is the same then try trimming before comparing. E.g.:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
When i have similar problem i do this simple trick:
Print the size of the strings you are comparing because sometimes you have characters like \n or \r which are not visible when you print the string.
First of all, it seems like you have a typo in sysout statement below.
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw); //Should be username
Secondly, you might wanna trim the strings for better string comparison.
Sometimes strings read from file or console can contain unwanted and hard-to-catch empty strings like spaces and tabs. These can be removed by calling .trim() method on strings.
Thus, try using the following code instead:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
}
usersName.equals(username) && usersPW.equals(pw).
I have faced these problem also, These kind of equality always tricky, Try to trim the strings that you are going to compare, as well as if you can compare these strings based on their length.
if (usersName.trim().equalsIgnoreCase(username.trim()) && usersPW.trim().equalsIgnoreCase(pw.trim()))
or
if (usersName.trim().length()==username.trim().length && usersPW.trim().length()==pw.trim().length))

Java arrays: select and replace values via user inputs

In the program I'm creating, the user will input values to create an array of videos. Each video contains several data fields (number, title, publisher, duration & date). However what I am currently trying to acheive is to let the user choose a particular video in the array they just created, select the data field they wish to rename, rename the value and then set the renamed value as the new value. Here is my code for adding videos to an array:
public Library createLibrary()
{
Library video = new Library();
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
for (int i = 0; i < videos.length; i++)
{
//User enters values into set methods within the Library class
System.out.print("Enter video number: " + (i+1) + "\n");
String number = scannerObject.nextLine();
System.out.print("Enter video title: " + (i+1) + "\n");
String title = scannerObject.nextLine();
System.out.print("Enter video publisher: " + (i+1) + "\n");
String publisher = scannerObject.nextLine();
System.out.print("Enter video duration: " + (i+1) + "\n");
String duration = scannerObject.nextLine();
System.out.print("Enter video date: " + (i+1) + "\n");
String date= scannerObject.nextLine();
System.out.print("VIDEO " + (i+1) + " ENTRY ADDED " + "\n \n");
//Initialize arrays
videos[i] = new Library ();
videos[i].setVideo( number, title, publisher, duration, date );
}
return video;
}
And here is the basic concept for my select and replace function for those who can't figure out what I mean:
public void replaceVideo(Library[] videos, String replaceTo, String replaceWith)
{
for (int i = 0; i < videos.length; i++)
if (videos[i].equals(replaceTo)) {
videos[i]= replaceWith;
}
}
Simpler solutions will be appreciated. Thanks.
Try comparing replaceTo to the name of the video (or whatever replaceTo is supposed to match):
if (videos[i].getName().equals(replaceTo)) {
I can't see your replace ever working, since it appears that you are comparing a Library type and a String type with .equals().
If you use one of the Collection classes instead of an array, the replace method changes to
public void replaceVideo(Vector<Library> videos, Library current, Library newCopy)
{
Collections.replaceAll(videos, current, newCopy);
}
I used Vector, but you could use a Set, List, etc. as needed.
For your code to work, you need to override the Library.equals method to compare strings only. Otherwise, you can compare the video title, for one sample, against the parameter replaceTo.
Certainly, it is OOP elegant to override the equals method. Try my suggestion and Thomas'
Good luck.

Categories

Resources