Hi I'm currently working on an assignment where I have to check if the Resident Password matches with the Door password or not, I have to give the user three tries and after that use assert to show to tell the user to try again. this is my code but the assert is not showing any message.
public static void main(String[] args) throws Exception {
// write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
assert i>2 : "Serious Error – Program has been terminated Try again later";
}
what should I do to get the message using assert.
From https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html#enable-disable
By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions. To enable assertions at various granularities, use the -enableassertions, or -ea, switch
The way assert works with sending an error message is via using ensuring the condition fails in the case you want. For example:
assert <condition> : <message-if-condition-is-false>;
So if you change your assert to use:
assert i<=2 : "Serious Error – Program has been terminated Try again later";
You throw if i is still <=2. If the condition fails, then the message gets thrown as AssertionError.
So with the above, if I execute it as:
javac Example.java
java -ea Example
and give the desired wrong inputs, you would get:
Exception in thread "main" java.lang.AssertionError: Serious Error, Program has been terminated Try again later
Anyhow, you could choose to use System.err and output the error message:
public static void main(String[] args) throws Exception {
// Write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
// This need not be verified with if (i>2) because the System.exit(0); will exit if the condition satisfies
System.err.println("Serious Error – Program has been terminated Try again later");
}
Related
I'm a Java beginner and my project consists of creating a simple program to register users for an alumni center. The process creates an ID and then provides the new user with an OTP. Next is the login (Enter ID:, Enter OTP: ).
My OTP verification method is not working. It seems to be a problem with the IF.equals declaration, the process jumps straight to the ELSE condition.
Any suggestions why?
Here is my code:
class Main {
static NewRegandLogin newRegAndLogin = new NewRegandLogin(null, null, null, null, null, null);
static ArrayList<NewRegandLogin> loginInformation = new ArrayList<>();
public static void main(String[] args) {
System.out.println(" WELCOME TO THE ALUMNI SHE-CODES SYSTEM ");
System.out.println("_________________________________\n - New Alumni registration - \n");
System.out.println("");
newRegAndLogin.registerNewGrad();
System.out.println();
System.out.println("_________________________________");
System.out.println();
System.out.println("Your new Alumni ID is: " + newRegAndLogin.getAlumniId());
System.out.println();
System.out.println("Your temporary password is:");
System.out.println(newRegAndLogin.oTp(8));
loginInformation.add(newRegAndLogin);
System.out.println("_________________________________");
System.out.println("_________________________________\n - Alumni Login - \n");
System.out.println("");
newRegAndLogin.login();
System.out.println("");
System.out.println("Please make a list of completed Courses: -->Enter 'S' to stop adding courses<--");
newRegAndLogin.setAlumniCourses();
System.out.println("_________________________________");
newRegAndLogin.setLinkedInPage();
loginInformation.add(newRegAndLogin);
//printAlumniProfile();
System.out.println("_________________________________");
newRegAndLogin.jobOffer();
}
void login() {
System.out.print("ID: ");
alumniIdImput = scanner.nextLine();
idVerification();
do {
System.out.println("Password (OTP if logging in for the first time): ");
passwordImput = scanner.nextLine();
oTpFromImput = passwordImput.toCharArray();
oTpVerification();
} while (isPasswordCorrect=false);
void oTpVerification() {
isPasswordCorrect = false;
if (oTpFromImput.equals(oTp(8))) {
isPasswordCorrect = true;
System.out.println("Logging In.....");
}else {
isPasswordCorrect = false;
System.out.println("Incorrect password.\nPlease enter valid password: 8 alpha numeric
characters(Aa,123,#,#,$,%)");
}
}
This is the oTp method
char[] oTp (int length) {
String capitalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String smallChars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!##$%^&*_-=+/.?<>";
String values = capitalChars + smallChars + numbers + symbols;
Random oneTimePassword = new Random();
char[] password = new char[length];
for(int i = 0; i<length;i++) {
password[i] = values.charAt(oneTimePassword.nextInt(values.length()));
}
return password;
}
It seems you built a guessing game, not an OTP verification code.
You first read the OTP from user, and only then randomly generate one to copare to it.
Basically, you code expects the user to guess a random 8 character password that has not been created you, which is basically impossible...
You need to generate to OTP first, show it to the user, then ask them to input it.
I see your logic code is generate OTP code after User input. It seem so wierd bro.
Whenever you call oTp(8) function will generate new OTP.
Use should generate OTP first then store somewhere, then User input and compare it.
You need to store the generated otp somewhere. Then compare it with the input otp. Right now you are comparing it with the otp(8). And otp(8) always returns a new otp.
New to Java. I'm having a hard time understanding why my code isn't running. I'm getting a InputMismatchException when I try to run my code.
I did some testing and problems occur if there's white space in my file such as "New York." I've been trying different things such as looping with .hasNextLine() instead of .hasnext() as suggested in other threads but to no avail. Sometimes I can get it to run until the end it gives me a NoSuchElementException. If you could please put me in the right direction, that would help a lot thank you!
import java.util.*;
import java.io.*;
public class StandaloneReport {
public static void main(String[] args) {
String fileInputName;
String fileOutputName;
String firstName;
String lastName;
String houseNumber;
String street;
String city;
String state;
String zip;
String productDescription;
double productPrice;
//Scanner obj1
Scanner input = null;
input = new Scanner(System.in);
System.out.printf("What is the file name?\n");
fileInputName = input.nextLine();
//Print out the name user inputed
System.out.println("File name is: " + fileInputName);
//Read the file
FileReader filereader;
Scanner readInput = null;
try {
readInput = new Scanner(filereader = new FileReader(fileInputName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (readInput.hasNext())
{
firstName = readInput.next();
lastName = readInput.next();
houseNumber = readInput.next();
street = readInput.next();
city = readInput.nextLine();
state = readInput.next();
zip = readInput.next();
productDescription = readInput.nextLine();
productPrice = readInput.nextDouble();
Textfile looks like this:
Jane
Doe
10
Broadway
New York
NY
10001
Galaxy S10
199.99
2
Samsung Bluetooth
29.99
1
Slim Fit Hard Plastic Case
2.99
2
Charger
17.99
3
Error I get:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at hey.bcs.hwk.purchases.standalonereport.StandaloneReport.main(StandaloneReport.java:55)
I expected it to read it smoothly so I can print it using PrintStream in another file but I cannot even get past this part.
To be honest your program is problematic in so many ways. But here's an explanation to fix the mismatch issue you mentioned.
readInput.nextLine()
will read the remainder of the current line. So after reading "Broadway" the Scanner stays in the same line and when you call nextLine, the Scanner yields whatever is left in the line for "Broadway", which is an empty String.
To avoid this situation, do
street = readInput.next();
readInput.nextLine();
To drop the current line("Broadway" for example). And then call
city = readInput.nextLine();
That way the program will read "New York" as you expected. As Tom mentioned in the comments, for more details, look at the question asked here.
Apart from the Scanner issue, your program is ambiguous as to where it ends – you did not provide closing brackets. That while loop seems redundant considering that your input is broken: it ceases to match what you have in your code after the "199.99" line. Please put your complete code on there and revise your sample input.
This is for one set of data, one data item per line. You have to make adjustments for multiple sets of data.
int i = 0;
while (readInput.hasNext())
{
if (i == 0)
{
firstName = readInput.nextLine();
}
else if (i == 1)
{
lastName = readInput.nextLine();
}
else if (i == 2)
{
houseNumber = readInput.nextLine();
}
else if (i == 3)
{
street = readInput.nextLine();
}
else if (i == 4)
{
city = readInput.nextLineLine();
}
else if (i == 5)
{
state = readInput.nextLine();
}
else if (i == 6)
{
zip = readInput.nextLine();
}
else if (i == 7)
{
productDescription = readInput.nextLine();
}
else if (i == 8)
{
productPrice = readInput.nextDouble();
}
i += 1;
} // End while
I'm complete beginner in Java. In my program, the user is supposed to write the command message followed by some text on the same line before pressing the return-key, and the program should print the entered text. Is this possible? I aim for something like this:
Command> message this is a message!
this is a message!
At the moment I'm using a switch statement for all the commands in the program. Right now I have to write "message" then press enter before writing the text.
Command> message
this is a message!
this is a message! (output)
My code:
switch (cmd) {
//other commands
case "message":
printMessage();
break;
default:
System.out.println("Wrong command!");
}
public void printMessage() {
String text = keyboard.nextLine();
System.out.println(text);
}
I also have to include another command in the program, where the user enters the name of an event and the program prints info about said event.
Is it possible to have an object name as a command?
Command> event name
information about event above, if the event exists (output)
A switch statement seems to be too limited for this? If that won't work, what other options do I have?
I will assume that you have a class and that you can at least print a HelloWorld message in the Terminal
so... you will need:
Scanner object so you can read the input given by the user and the Split method from the String class so you can split the input message Hola_World in 2 parts, the 1st is message and the 2nd is Hola_World
Example:
public static void main (String[] args){
Scanner inputScanner = new Scanner(System.in);
String userInput = inputScanner.nextLine();
System.out.println("Foo: " + userInput);
String[] userInputSplitted = userInput.split(" " );
String fisrtPart = userInputSplitted[0];
String secondPart = userInputSplitted[1];
System.out.println("1st Part: " + fisrtPart);
}
I keep getting a syntax error on my last else statement in a string of if, else if , else , and I can't figure out why nor can I find anywhere that tells me what's really confusing is I have done this type of if else statement setup before and never had this problem. I have tried using 2 coding programs (JCreator and Eclipse) but they both give me an error Eclipse gives me a syntax error on the word else and JCreator on the entire statement saying it has no if statement to pair with it, but I have done one like this and didn't need an if statement as is was the final one.
import java.util.Scanner;
public class Hotel
{
public static void main(String[] args)
{
String answer = "";
Scanner keyboard = new Scanner(System.in);
GuestInterface go = new GuestInterface();
PassswordField hotel = new PassswordField();
System.out.println("do you wish do acces the guest interface or the hotel staff interface? ");
System.out.println("Hint: hotel staff -or- guest");
answer = keyboard.nextLine();
if(answer.equalsIgnoreCase("hotel Staff"))
{
System.out.println("Enter username");
answer = keyboard.nextLine();
hotel.readPassword("Enter Passsword \n ");
System.out.print("\n" + "incorect Password");
System.out.println("System will now shut down");
System.exit(0);
}
else
if(answer.equalsIgnoreCase("Guest"))
{
go.run();
}
else //error throws on this statment
{
System.out.println("uncompatible responce");
System.out.println("System ato shut down activated");
System.exit(0);
}
}
}
You wrote a ; at the end of this line:
if(answer.equalsIgnoreCase("Guest"));
So that is a seperate if-statement. Right after that, you start with this:
{
go.run();
}
else //error throws on this statment
{
// (...)
}
Which makes no sense to the compiler, because it didn't start with an if-statement.
Remove the ; to solve the error.
I'm making a credential like program and it is very WIP. I placed a while loop with a Boolean condition to make the program run again whenever a person finishes creating a credential, but when it loops to the beginning of the program it prints the first part twice! like this:
run:
|-----------------------------------------------|
|Welcome to the Credential Managing System 2013!|
|-----------------------------------------------|
Would you like to create or manage a credential?
Choose: Manage | Create
Waiting for input: Create
Credential name: df
Credential ID: 34243
Credential Password: numbers or words?
Waiting for input: numbers
Credential Password: 13651
|-------------------|
|Credential created!|
|-------------------|
Would you like to create or manage a credential?
Choose: Manage | Create
Waiting for input:
from there it stops reading the input again.
here is the entire code!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Carlinhos
*/
import java.util.Scanner;
public class Criação {
public static void main(String[] args){
Scanner e = new Scanner(System.in);
System.out.println(" |-----------------------------------------------|");
System.out.println(" |Welcome to the Credential Managing System 2013!|");
System.out.println(" |-----------------------------------------------|");
System.out.println("");
Boolean autoRun = true;
while(autoRun){
System.out.println(" Would you like to create or manage a credential?");
System.out.println("");
System.out.println(" Choose: Manage | Create");
System.out.println("");
System.out.print(" Waiting for input: ");
String op1 = e.nextLine();
autoRun = false;
if(op1.equals("Create")){
System.out.println();
System.out.print("Credential name: ");
String credName = e.nextLine();
System.out.print("Credential ID: ");
int credID = e.nextInt();
System.out.println("Credential Password: numbers or words?");
System.out.print("Waiting for input: ");
e.nextLine();
String credPassCheck = e.nextLine();
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
}
else if(credPassCheck.equals("words")){
System.out.print("Credential Password: ");
String credPassLet = e.nextLine();
}
System.out.println("");
System.out.println(" |-------------------|");
System.out.println(" |Credential created!|");
System.out.println(" |-------------------|");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
autoRun = true;
}
}
}
}
Change this line:
while(autoRun = true)
to this:
while(autoRun)
= is not the equality comparison operator, it's the assignment operator. So, when you check that condition autoRun is the assigned the value true even though you set it to false earlier. You can use == instead but since autoRun is a boolean variable, you can simply use this variable without comparing it to anything else.
UPDATE:
After OP's comments that the program has started exiting after printing the prompt for the second time, I looked into the code a little more and found these lines:
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
}
This is basically consuming less input than is necessary and thus the next prompt for "Waiting for Input" gets a single newline character as its input. The fix should be obvious now:
if(credPassCheck.equals("numbers")){
System.out.print("Credential Password: ");
double credPassNum = e.nextDouble();
e.nextLine(); //Add this Line
}