used of loop and encapsulation - java

I'm trying to get the program to do:
If the data entered is not accepted, request the information again
(note: it is fine to request ALL the information again, it is not necessary to only request specific info to be re-entered, but you can if you would like).
For the program everything seem to run fine except for when its the resolution, it ask for another input but if the input isn't correct it just accept. I need it to keep running until the correct input is enter.
import java.util.Scanner;
public class encap
{
private static String userID;
private static String password;
private static String resolution;
private static int Ramsize;
private static int freespace;
private static int videocard;
//Get and Set methods
public static String getuserID()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter userID : ");
userID = input.next();
return userID;
}
public static String getpassword()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter password : ");
password = input.next();
return password;
}
public static String getresolution()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter video resolution: ");
resolution = input.next();
if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900"));
else
{
while(true)
{
System.out.println("Information invalid, Please fill again");
String getresolution = input.next();
if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900"));
break;
}
}
return resolution;
}
public static int getRamsize()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter RAM size : ");
while(true)
{
if(input.hasNextInt())
{
Ramsize = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter RAM size : ");
}
}
return Ramsize;
}
public static int getfreespace()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter HD free space : ");
while(true)
{
if(input.hasNextInt())
{
freespace = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter HD free space : ");
}
}
return freespace;
}
public static int getvideocard()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter video card RAM size: ");
while(true)
{
if(input.hasNextInt())
{
videocard = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter video card RAM size: ");
}
}
return videocard;
}
public static void setuserID(String newuserID)
{
userID = newuserID;
}
public static void setpassword(String newpassword)
{
password = newpassword;
}
public static void setresolution(String newresolution)
{
resolution = newresolution;
}
public static void setRamsize (int newRamsize)
{
Ramsize = newRamsize;
}
public static void setfreespace (int newfreespace)
{
freespace = newfreespace;
}
public static void setvideocard (int newvideocard)
{
videocard = newvideocard;
}
public static void main(String[] args)
{
setuserID(getuserID());
setpassword(getpassword());
setresolution(getresolution());
setRamsize(getRamsize());
setfreespace(getfreespace());
setvideocard(getvideocard());
System.out.println("You have input the following information: " + "\nuserID: " + userID
+ "\npassword: " + password + "\nVideo resolution: " + resolution + "\nRam Size: "
+ Ramsize + "\nHD Free Space: " + freespace + "\nVideo Card Ram Size: " + videocard);
}
}

The problem is because you never do anything within your valid case scenario and you are using .next() for a single character instead of .nextLine() which grabs the entire input entered following an end of line character (return character)
This will ask until the input entered satisfies your if condition.
public static String getresolution()
{
String resolution;
boolean validAnswer = false;
Scanner input = new Scanner(System.in);
HashSet<String> validResolutions = new HashSet<>();
validResolutions.add("800x600");
validResolutions.add("1024x768");
validResolutions.add("1152x900");
//add more resolutions if you want without having to create a bigger if check
//validResolutions.add("1400x1120");
do {
System.out.print("Please enter video resolution: ");
resolution = input.nextLine().replaceAll(" ", "").replaceAll("\n", "");
validAnswer = validResolutions.contains(resolution) ? true : false;
if(!validAnswer)
System.out.println("Incorrect resolution please try again");
} while (!validAnswer);
return resolution;
}

Related

do while loop and user input issue

I'm trying to make a program where a user needs to input a random integer. If the user inputs a String I want an error message to pop out: "This is not a number" and after that restart the program until the user inputs a number. I got this so far and I'm stuck. I just get an error message if I input a string and program crashes.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
do {
System.out.println("Input a number!");
number = scanner.nextInt();
if (!scanner.hasNextInt()) {
System.err.println("This is not a number");
}
} while (!scanner.hasNextInt());
System.out.println("You entered: " + number);
}
You're getting an InputMisMatchException because if you input a string into a scanner.nextInt(), it will immediately give an error and stop the program before it does anything else, so it won't reach your if statement. One way to get around this issue is to instead receive user input as a string, try to parse it for an int, and end the loop if it doesn't throw an exception. This is my implementation:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
int number = 0;
boolean end = true;
do {
System.out.println("Input a number!");
input = scanner.nextLine();
try {
number = Integer.parseInt(input);
end = true;
} catch(Exception e) {
System.err.println("This is not a number");
end = false;
}
} while (!end);
System.out.println("You entered: " + number);
}
See if the below code can help achieve what you want to do.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String number;
do {
System.out.println("Input a number!");
number = scanner.next();
} while (!isNumeric(number));
System.out.println("You entered: " + number);
}
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
}

Stop do while loop from executing the next loop after breaking from the current loop

This code works fine when PIN is wrong but when it is correct it breaks from the first loop and then continues to ask for PUK. I want it to work in such a way that if the PIN is correct the entire program breaks.
This is the code:
import java.util.Scanner;
public class PINDemo {
public static void main(String [] args) {
String PIN = "12345";
String PUK = "123456789";
int attempts = 1;
String entry;
Scanner obj = new Scanner(System.in);
lab1:do {
System.out.println("Enter your PIN");
attempts++;
entry = obj.next();
if(!entry.equals(PIN)) {
System.out.println("Wrong PIN. Attempt "+attempts);
}
else {
System.out.println("PIN Correct. SIM Unlocked");
break ;
}
}while(attempts < 4);
System.out.println("PIN Blocked. Please enter your PUK");
for(attempts = 1;attempts < 4; attempts++) {
entry = obj.next();
if(!entry.equals(PUK)) {
System.out.println("Wrong PUK try again");
}
else {
System.out.println("PUK Correct. SIM Unlocked");
}
}
}
}
Not a java expert here, but I suggest writing the code in a more manageable form. (i.e. separate the data entry flow from the higher level logic)
import java.util.Scanner;
class CodeEntry
{
private Scanner scanner = new Scanner(System.in);
private String entryMessage;
private int guessCount;
private String secretValue;
public CodeEntry(String entryMessage, int guessCount, String secretValue, String WrongCodeMessage, String RightCodeMessage, String OutOfAttemptsMessage)
{
this.scanner = scanner;
this.entryMessage = entryMessage;
this.guessCount = guessCount;
this.secretValue = secretValue;
this.WrongCodeMessage = WrongCodeMessage;
this.RightCodeMessage = RightCodeMessage;
this.OutOfAttemptsMessage = OutOfAttemptsMessage;
}
private String getAttemptString(int attempt)
{
return "Attempt " + (attempt + 1) + "/" + guessCount;
}
private String WrongCodeMessage;
private String RightCodeMessage;
private String OutOfAttemptsMessage;
public boolean EnterCode()
{
boolean guessed = false;
for (int attempt = 0; attempt < guessCount; attempt++)
{
System.out.println(entryMessage);
guessed = secretValue.equals(scanner.next());
if (guessed)
{
System.out.println(RightCodeMessage);
break;
}
System.out.println(WrongCodeMessage + " " + getAttemptString(attempt));
}
if (!guessed)
{
System.out.println(OutOfAttemptsMessage);
}
return guessed;
}
}
public class MyClass {
public static void main(String args[]) {
CodeEntry pinEntry = new CodeEntry("Enter your PIN", 3, "12345", "Wrong PIN, try again.", "PIN Correct. SIM Unlocked", "PIN Blocked");
if (!pinEntry.EnterCode())
{
CodeEntry pukEntry = new CodeEntry("Enter your PUK", 3, "123456789", "Wrong PUK, try again.", "PUK Correct. SIM Unlocked", "SIM Blocked");
if (!pukEntry.EnterCode())
{
//badjuju - if needed
}
}
}
}
You have Code For "PIN blocked" outside the do while loop, So it will anyway ask for "PIN Blocked. Please enter your PUK".
Use a flag to isPinCorrect like
import java.util.Scanner;
public class PINDemo {
public static void main(String [] args) {
boolean isPinCorrect=false;
String PIN = "12345";
String PUK = "123456789";
int attempts = 1;
String entry;
Scanner obj = new Scanner(System.in);
lab1:do {
System.out.println("Enter your PIN");
attempts++;
entry = obj.next();
if(!entry.equals(PIN)) {
System.out.println("Wrong PIN. Attempt "+attempts);
}
else {
System.out.println("PIN Correct. SIM Unlocked");
isPinCorrect=true;
break ;
}
}while(attempts < 4);
if(!isPinCorrect) //This will only run if pin is blocked
{
System.out.println("PIN Blocked. Please enter your PUK");
for(attempts = 1;attempts < 4; attempts++) {
entry = obj.next();
if(!entry.equals(PUK)) {
System.out.println("Wrong PUK try again");
}
else {
System.out.println("PUK Correct. SIM Unlocked");
}
}
}
}
}

Create account and Login

im having some trouble figuring out how i should approach this task. I would like to create an option to create an account and then have a login section. I am trying to figure out how to pass the information to the login class as i would like to be able to login without creating a new account every time. im not sure if this current code would allow for multiple accounts at the same time. I am open to suggestions if so on how to do that, but im fine with one account.
Here is my code so far:
CreateAccount class
import java.util.Scanner;
public class CreateAccount{
public static void main(){
CreateAccount obj1 = new CreateAccount();
obj1.accountNumberPin();
}
public void accountNumberPin(){
System.out.println("create a six digit account number: ");
Scanner input = new Scanner(System.in);
int accNum = input.nextInt();
System.out.println("create four digit pin: ");
Scanner input2 = new Scanner(System.in);
int accPin = input2.nextInt();
}
public int getAccNum(){
return accNum;
}
public int getAccPin(){
return accPin;
}
}
Login Class
import java.util.Scanner;
public class Login{
public void login(){
CreateAccount test= new CreateAccount();
int theaccNum = test.getAccNum();
int theaccPin = test.getAccPin();
System.out.println("Enter account number: ");
Scanner input1 = new Scanner(System.in);
int accNumberInput= input1.nextInt();
System.out.println("Enter account pin: ");
Scanner input2= new Scanner(System.in);
int accPinInput = input2.nextInt();
if(accNumberInput==theaccNum && accPinInput == theaccPin){
System.out.print("1 2 1 2 this is just a test");
}
}
}
PS, i know there is an issue currently with the get methods
You should start by having an Account class that only contains the data of the account:
class Account {
private final int number;
private final int pin;
public Account(int number, int pin) {
this.number = number;
this.pin = pin;
}
public int getNumber() {
return number;
}
public int getPin() {
return pin;
}
}
Then implement the logic in another class. This class can maintain a list of the created accounts. That list will persist as long as you don't stop the program. (if you need persistence across restarts then you need some kind of storage, that is a file or a database).
Here is an example where I tried to keep as much of your code as possible:
public class Main {
private static final Map<Integer, Account> accounts = new HashMap<>();
public static void main(String[] args) {
while (true) {
System.out.println("Choose an option:");
System.out.println("1 - Create an account");
System.out.println("2 - Login into an account");
System.out.println("3 - List account numbers");
System.out.println("4 - Quit");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice == 1) {
createAccount();
} else if (choice == 2) {
login();
} else if (choice == 3) {
listAccountNumbers();
} else if (choice == 4) {
break;
} else {
System.out.println("Invalid choice");
}
}
}
private static void createAccount() {
System.out.println("create a six digit account number: ");
Scanner input = new Scanner(System.in);
int accNum = input.nextInt();
System.out.println("create four digit pin: ");
Scanner input2 = new Scanner(System.in);
int accPin = input2.nextInt();
Account account = new Account(accNum, accPin);
accounts.put(accNum, account);
}
private static void login() {
System.out.println("Enter account number: ");
Scanner input1 = new Scanner(System.in);
int accNumberInput= input1.nextInt();
System.out.println("Enter account pin: ");
Scanner input2= new Scanner(System.in);
int accPinInput = input2.nextInt();
Account account = accounts.get(accNumberInput);
if(account.getPin() == accPinInput) {
System.out.print("Valid credentials for account number " + account.getNumber());
} else {
System.out.print("Invalid credentials for account number " + account.getNumber());
}
}
private static void listAccountNumbers() {
accounts.keySet().forEach(System.out::println);
}
}
public Account deposit(double amount) {
balance += amount;
return new Account(getID(), getCustomer(), getBalance());
}
public Account withdraw(double amount) {
if(balance >= amount) {
balance -= amount;
}
return new Account(getID(), getCustomer(), getBalance());
}

ArrayLists (Removing and Changing Elements)

Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();

How to add multiple user-prompts in while loop?

I have to write a program that asks the user for his name, address and phone number. When the data is entered the program shall print the data and ask the user to verify the data by entering yes or no. This process shall be repeated until the user is satisfied and answers yes to the question.
Now, at this moment I am able to pop-up a single prompt (in my case asking only the user's name). But what if I want to add multiple question (i.e. asking address and telephone number) and happen the same thing? How could I do that?
My code:
package userinfo;
import java.util.Scanner;
import sun.security.krb5.SCDynamicStoreConfig;
public class UserInfo {
public static void main(String[] args) {
String varify;
String yes = "yes";
String no = "no";
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.next();
System.out.println("Your input was: "+name);
System.out.println("Varify by yes or no: ");
while (true) {
varify = input.next();
if (varify.equalsIgnoreCase(yes)) {
System.out.println("Varified! Your name is: " + name);
} else if (varify.equalsIgnoreCase(no)) {
System.out.println("Type your name again: ");
}
}
}
}
You can extract this code to a method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName = readFieldAndVerify(input, "Enter your name: ");
String userAddress = readFieldAndVerify(input, "Enter your address: ");
String userPhoneNumber = readFieldAndVerify(input, "Enter your phone number: ");
}
private static String readFieldAndVerify(Scanner input, String prompt) {
while (true) {
System.out.print(prompt);
String field = input.next();
System.out.println("Are you sure (yes / no)?");
String verify = input.next();
if (verify.equalsIgnoreCase("yes")) {
System.out.println("Verified!");
return field;
} else {
System.out.println("Canceled");
}
}
}
EDIT Added logic for more questions... Expand it in similar fashion for everything you need. You could expand this code into a single method as well so you avoid code replication. Check answer from user alaster for an example.
Try this. It will store the name variable in case you want to use it further.
We use a boolean to keep asking the user to input his name until he validates it.
Of course, you can still use while(true) and then break if the name is valid, but I prefer this method since the code is more clear and easier to understand.
private static boolean isVerified(String verify) {
if (verify.equalsIgnoreCase("yes")) {
return true;
} else if (verify.equalsIgnoreCase("no")) {
return false;
} else
return false;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validName = false;
boolean validTelephoneNo = false;
boolean validAddress = false;
String name="";
String telephoneNo="";
String address="";
while (!validName) {
System.out.print("Enter your name: ");
name = input.next();
System.out.println("Are you sure your name is " + name + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your name is: " + name);
validName = true;
} else {
System.out.println("Not verified! Please type your name again.");
}
}
while (!validTelephoneNo) {
System.out.print("Enter your telephone nummber: ");
telephoneNo = input.next();
System.out.println("Are you sure your telephone number is " + telephoneNo + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your telephone number is: " + telephoneNo);
validTelephoneNo = true;
}
else {
System.out.println("Not verified! Please type your telephone number again.");
}
}
while (!validAddress) {
System.out.print("Enter your address: ");
address = input.next();
System.out.println("Are you sure your address is " + address + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your address is: " + address);
validAddress = true;
}
else {
System.out.println("Not verified! Please type your address again.");
}
}
System.out.println("Done, here is your info:");
System.out.println("Name: " + name);
System.out.println("Telephone Number: "+telephoneNo);
System.out.println("Address: "+address);
}

Categories