How to make final String after scanner - java

I wonder how to make my String as final after scanner. I wish that registration was possible only once.
public class Register extends Menu {
public static String login, password;
public void register() {
Console con = System.console();
System.out.println("Enter login:");
this.login = con.readLine();
System.out.println("Enter password:");
this.password = String.valueOf(con.readPassword());
menu();
}
And there's part with login:
public class Logowanie extends Register {
public void logowanie() {
Scanner scanner = new Scanner(System.in);
String login, haslo;
boolean isFalse = true;
while (isFalse = true) {
System.out.println("Enter login:");
login = scanner.next();
System.out.println("Enter password:");
haslo = scanner.next();
if (login.equals(super.login) && haslo.equals(super.password)) {
System.out.println("You're in.");
isFalse = false;
menu();
} else {
System.out.println("Try again.");
}
}
}
}

I don't have enough rep to put a comment.
This line seems to be assigning instead of just checking.
while (isFalse = true)
should be
while (isFalse == true)

This code is not tested so there could be syntax errors.But using this flow you may achieve what you want to do.
Note:Replace 'regUsers' with a database or a file if you want registration details to prevail till next run.
public class User
{
public User(String uName,String pwd)
{
userName=uName;
password=pwd;
}
String userName;
String password;
//any other properties as needed
}
public class MyAppMenu extends Menu {
List<User> regUsers=new ArrayList<User>();
public void Login()
{
//prompt user to enter login details
//Check if there is a user matching in 'regUsers' list with entered login details
//if exists login success continue with rest of the app logic
//else prompt user to enter details again or register
}
public void Register()
{
//prompt user to enter registration details
//Create new User() object with entered details and add it to 'regUsers' array
//continue with rest of the app logic or prompt to login
}
}
public class MainApplicaton
{
MyAppMenu myMenu=null;
public static void main(String [] args)
{
myMenu=new MyAppMenu();
myMenu.Login();
}
}

I'm not completely clear on what you're asking. However, there are a couple things I can see that might help:
(1) Don't make class fields public. It's considered bad practice to do so, because then any other class could assign some other value to it. Instead, make the fields private, and provide a getXxx() method that allows other code to retrieve the field, but don't provide a method to set the field. That way, your class will have complete control over what happens to the field.
(2) If you want registration to occur only once, you can make your register() method check so that it throws an exception if it's called more than once. One way would be to define a private boolean that is initialized to false; register() can throw an exception if it's true, and then set it to true the first time it runs successfully. Or you could do the same thing by checking whether login is null; your method could throw an exception if login != null which would indicate whether someone has logged in already.

Related

Can I check the local vairable by using method in other class?

public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu();
}
}
Here's the menu class:
public class BookstoreMenu {
private Scanner sc = new Scanner(System.in);
private BookstoreController bc = new BookstoreController();
public void mainMenu() {
System.out.println("1. SignUp");
System.out.println("2. Check members list");
System.out.println("Select menu : ");
int menu = sc.nextInt();
switch (menu) {
case 1: {
bc.createAccount();
break;
} case 2:
default:
System.out.println("...");
}
}
}
This is controller class where I made methods:
public class BookstoreController {
private Scanner sc = new Scanner(System.in);
public void createAccount() {
System.out.println("Let's get started");
System.out.print("Your name : ");
String[] strArray = new String[0];
String name = sc.nextLine();
strArray = saveId(strArray, name);
System.out.print(name + ", Nice to meet you!");
System.out.println(Arrays.toString(strArray));
}
public String[] saveId(String[] originArr, String name) {
String[] newArr = new String[originArr.length + 1];
System.arraycopy(originArr, 0, newArr, 0, originArr.length);
newArr[originArr.length] = name;
return newArr;
}
}
I'm trying to make a menu with just two options. The first option is Sign Up through createAccount(); and once I finish signing up, I want to go back to the menu class and choose option 2.
I was thinking I could approach the information of strArray in BookstoreController class by typing bc.~ under case 2 of the switch in the BookstoreMenu class, but I failed.
My question is: Is it possible to approach the value which was made in the local area of another class?
No you cannot. Welcome to the world of Object Oriented Programming OOP & design. One of the more important ideas of OOP is that you encapsulate data and then access it through method calls (or, for other languages, properties).
In this case you should return an Account class from createAccount(). Then you can have a method there to the strArray. That variable should be a field in the Account class and be renamed to something that reflects its purpose, rather than the types it is made up of (string and arrays).
Now, in modern Java, we store objects like accounts in lists, not arrays. Lists can be grown at your leisure. I've put the list into a field of the controller, so it can be maintained in the right controlled location.
Here is some example:
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu(new Scanner(System.in), System.out);
}
}
public class BookstoreMenu {
private BookstoreController bc = new BookstoreController();
public void mainMenu(Scanner sc, PrintStream out) {
while (true) {
// this is a "try with resources", using a localized scanner
int menu;
out.println("1. SignUp");
out.println("2. Check members list");
out.println("9. Quit");
out.println("Select menu : ");
menu = sc.nextInt();
// either menu has been assigned, or an exception has been thrown, so we can now use it
switch (menu) {
case 1:
bc.createAccount(sc, out);
break;
case 2:
bc.displayAccounts(out);
break;
// always leave yourself an exit option
case 9:
out.println("Bye");
System.exit(0);
// the default should display an error or warning
default:
out.println("Unknown option, try again");
}
}
}
}
public class BookstoreController {
// the list of accounts that is initially empty, but may grow
private List<Account> accounts = new ArrayList<Account>();
public void createAccount(Scanner sc, PrintStream out) {
out.println("Let's get started");
out.println("Your name : ");
String name = sc.nextLine();
out.println(name + ", nice to meet you!");
Account account = new Account(name);
accounts.add(account);
}
public void displayAccounts(PrintStream out) {
for (Account account : accounts) {
out.println(account);
}
}
}
// this is the additional "data class"
public class Account {
private String name;
// constructor that assigns the name to the field
public Account(String name) {
this.name = name;
}
// a method to retrieve the property name
public String name() {
return name;
}
// this is what is called when it is printed using println (converted to string)
#Override
public String toString() {
return String.format("Account %s", name);
}
}

Calling boolean methods

My overall goal with this program is to validate that a user inputted string is in fact a valid number. I am required to use at least two methods, including the main method. I have read many posts related to calling user-defined methods from within the main method, but I am however struggling to make mine work. When declaring my isAValidNumber method, I keep getting the error "illegal start of expression". How can I declare this method so that I can call it from within the main method and contentiously run it until the user enters an invalid invalid number?
import java.util.Scanner;
public class IsAValidNumber
{
public static void main(String[] args)
{
//prompt user for a valid number
Scanner consoleInput = new Scanner(System.in);
System.out.print("\nEnter a valid integer or floating point value: \n");
String input = consoleInput.nextLine();
/* while(isAValidNumber = true)
{
//
} */
public static isAValidNumber(String input)
{
for(int j=0;j<input.length();j++)
{
if(input.matches("\\d+(\\.\\d*)?|\\.\\d+") == true)
{
boolean isAValidNumber = true;
}
else
{
boolean isAValidNumber = false;
}
}
}
}
}
You can't declare methods inside of methods in Java. Declare isAValidNumber outside of main (either before or after it, doesn't matter) and you should be OK:
public class IsAValidNumber
{
public static boolean isAValidNumber(String input)
{
// Method's body snippet for brevity's sake
}
public static void main(String[] args)
{
// Code that can call isAValidNumber
}
}

Java Postcard Class and printer

I am trying to make a class and a separate printer class for post cards. The idea is to make a postcard that can take user inputs for sender, recipient, and occasion. Then add in something that allows us to send the same postcard to another friend. This is my post card class
public class Postcard
{
private String message;
//define other variables that you need in this class
private String sender;
private String recipiant;
private String occasion;
private String print;
// Methods go here
public Postcard()
{
String message = "Happy holidays too ";
String sender = "Michael";
String recipiant = "";
String occasion = "";
}
public void setmessage(String m)
{
this.message = m;
}
public void setSender(String s)
{
this.sender = s;
}
public void setRecipiant(String r)
{
this.recipiant = r;
}
public void setOccasion(String o)
{
this.occasion = o;
}
public String print()
{
print = message + sender + recipiant + occasion;
return print;
}
}
and this is the post card print class
import java.util.Scanner;
public class PostcardPrinter
{
public static void main(String[] args)
{
String text = "Happy Holiday to ";//write your msg here
Postcard myPostcard = new Postcard(); // use the constructor method
//use the mutator method to set the name of the recipient
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
myPostcard.print();
//write the code to send the same msg to another friend
System.out.println("Do you want to send another? Type 'yes' or 'no' ");
String choice = op.nextLine();
while (choice != no)
{
String text = "Happy Holiday to ";
Postcard myPostcard = new Postcard();
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
}
}
}
Error's appear in the while loop saying that varriable no doesn't exist and when commented out, nothing happens. Virtual machine is running, but nothing happens. Any help would be greatly appreciated
The line:
while (choice != no)
Is looking for a variable called no, not a string constant. You want:
while (!choice.equals("no"))
Or, the case-insenstive method:
while (!choice.equalsIgnoreCase("no"))
One thing to point out - since the value of choice never changes once inside the loop, you'll basically be looping forever. You'll probably want to ask again after each iteration of the loop. You can probably just set the initial value of choice to an empty string, then immediately start the loop when the program begins. This would allow you to remove the redundant code above the loop.

Java Method Design query

This is a fairly rudimentary question but one that I am kind of on the fence about. Lets say I have a class A and it has methods method1,method2,method3,method4 and a main method.
method2 is only invoked by method1;
method4 is only invoked by method3.
The solution says to invoke the method1 from main and also method2 from main and same with method3 and 4.
So isn't it bad design to have the main method invoke method1, and method2 explicitly? What is the point of having private methods in a class if you invoke them in the main method even though they are only dependent on a single method in the whole class?
Wouldn't it be cleaner to call method2 from method1 and method4 from method3 since in both cases the latter method is only invoked by the former?
I thought this was the whole point of helper methods, so that we are able to abstract away unnecessary details of the implementation.
Again my apologies for the simplicity of the question, I am quite new to java.
Class A{
public static void main(String[] args){
int x = method1()
if ( x = 0){
//user wants to create a new account
method2()
}
}
private static int method1(){
//some code to check user login credentials in list of users
//if login credentials fail,user is asked if they want to create a new account, if yes,
//method 2 is invoked
//return value is whether the user wants to create a new account or not.
}
private static void method2(){
//creates new account for user and is only invoked by method1.
}
}
In the above case wouldn't it just be easier to call method2() from method1() instead of calling it in the main(). I would like to know if there are any advantages or disadvantages of this style of implementation.
In general terms, this is an exercise in separation of concerns. First, let's give your methods real names:
checkUserAccount(name, password)
addNewUserAccount(name)
Now, suppose you write checkUserAccount() so that it calls addNewUserAccount() if the user name is not found. In this case, the main program has no way of calling a function to just check the user credentials. The main program has no choice but to check the user account and then a new account will be added if the user isn't found. This is not very flexible if you decide to change things later.
On the other hand, if you separate these actions then the main program can decide what to do itself in the case where a user account is not found. You can then write code that looks something like what you showed:
if (checkUserAccount(name, password)) {
// great! logged in
} else {
addNewUserAccount(name);
}
This allows you to easily modify the main program if you choose to add a new feature. For example:
if (checkUserAccount(name, password)) {
// great! logged in
} else {
if (newUsersPermitted) {
addNewUserAccount(name);
} else {
System.out.println("Sorry, this system is closed.");
}
}
Of course, a real login system will have many more details to consider.
It's just a pseudocode, just to give you an idea.
public class User {
String name;
String username;
String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Here you can leave your queries
public class UserDAO {
public Boolean checkUsername(User user){
//here you use the object User
//ex: user.username, user.password in your query
String sql = "select bla bla bla";
if(sql){
//save something in log(just a example for a private method)
saveLog();
return true;
}else{
return false;
}
}
private Boolean saveLog(){
String sql = "insert bla bla bla";
if(sql){
return true;
}else{
return false;
}
}
}
Here is your main class
public class Test {
public static void main(String[] args) {
User u = new User();
u.setUsername("john");
u.setPassword("6876sdh");
UserDAO dao = new UserDAO();
Boolean ret = dao.checkUsername(u);
if(ret){
System.out.println("OK");
}else{
System.out.println("No Ok");
}
}
}
A full simple example: http://www.roseindia.net/tutorial/java/jdbc/dataaccessobjectdesignpattern.html

Simple ArrayList question

I have this class:
public class User {
public User(String nickname, String ipAddress) {
nickname = nickname.toLowerCase();
System.out.println(nickname + " " + ipAddress);
}
}
And another class that creates an array containing User objects.
class UserMananger {
static User user;
static User user2;
static User user3;
static ArrayList allTheUsers;
public void UserManager() {
allTheUsers = new ArrayList();
user = new User("Slavisha", "123.34.34.34");
user2 = new User("Zare", "123.34.34.34");
user3 = new User("Smor", "123.34.34.34");
allTheUsers.add(user);
allTheUsers.add(user2);
allTheUsers.add(user3);
}
}
What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"
public static void main(String args[]) {
System.out.println(allTheUsers.get(0));
}
For example, this main method should give me something like:
Slavisha 123.34.34.34
but it doesn't. What seems to be the problem?
First problem: you haven't overridden toString() in User. For example:
#Override
public String toString() {
return nickname + " " + ipAddress;
}
Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:
static {
// Initialize the static variables here
}
Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.
Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?

Categories