I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
Related
I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).
I am trying to make it so that if the username and / or password aren't correct, the program will run it over again, instead of just doing the print command in the else statement. I tried putting another while loop in the else statement and nesting the if statement inside that checks the username and password inside of it, but then I realized I would have to copy all the code from the if statement into the else statement, which obviously seems like it is not the correct solution and is probably very clunky. What is the right way to refer the program back to run from the start or something?
// Declare Variables
Scanner input = new Scanner(System.in);
String username;
String password;
String calculator = "calculator";
String renameUser = "renameUser";
String renamePass = "renamePass";
String getIp = "getIp";
String exit = "exit";
String command;
// Prompt User to login
System.out.println("Username: ");
username = input.nextLine();
System.out.println("Password: ");
password = input.nextLine();
if (username.equals("admin") && password.equals("admin") ) // Must use the equals method of string class to compare, == operator will NOT work.
{
System.out.println("Success! Welcome " + username + "!");
while (true) // Infinite loop using the true statement
{ command = input.nextLine();
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
break;
}
System.out.println("Logging out!");
}
}
}
}
}
}
else
{
System.out.println("Wrong username or password, please try again.");
}
}
}
Think about the below logic
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{
If command equals calculator then how can it equal renameUser
You should have it
if (....) {
}
else if (...) {
}
statement or as a switch statement
This snippet here is increasing the cyclomatic complexity of your software making it hard to make a decision, if you want to change that later, you have more chances to break the code than success
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
try to design something more like a witch case logic
Example:
switch (userInput) {
case renameUser:
renameUser();
break;
case getIp:
getIp();
break;
...
default:
break;
}
So there is this certain part of my program where I can create an account and the created account will be inserted into my database. And I'm trying to code something where *refer to the code:
public void actionPerformed(ActionEvent e) {
String user = userField.getText().trim();
String pass = passField.getText().trim();
String conPass = confirmPass.getText().trim();
try{
// TODO Auto-generated method stub
if(e.getSource()==submit){
if (user.equals(user)&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if the pass field is blank
else if(user.length()<5){
JOptionPane.showMessageDialog(null,"Username must be at least 5 characters!");
}
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
GUI gui = new GUI();
}//if(pass.equals(conPass))
else if(user.length()==0&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if both fields are blank
else if (user.length()==0 &&pass.equals(pass)){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if user field is blank
else if(user.equals(user)&&pass!=conPass){
JOptionPane.showMessageDialog(null, "Password do not match!");
}//check if password and confirm pass matches
}
I dont really know how to say the problem but look in the if and else if statements, if the user meet one the those conditions, the program should print the JOptionPane thing. Except for the second else if.
You might be wondering why I put these codes at my else if
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
The reason for this is that, my program is having some logic error when I try to put it in if statement. Please help me with my code thanks :) Feel free to write a new code for me :DD
i might try something like this:
public static boolean isSet(String s){
if(s==null || "".equals(s)) return false;
return true;
}
//.... your validation here
if(isSet(user) && isSet(pass) && isSet(conPass) && pass.equals(conPass)){
//create account
}else{
//smth wrong eg. if(!pass.equals(conPass) { //wrongpass }
}
I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.
see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}
This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.
I first want to validate that the user entered a value and to make sure to exit if 'cancel' was pushed. Then, I want to validate that the String releaseDateString is in the correct format at the same time as converting the String to java.sql.Date.
The first validation is taking place but then the JOptionPane carries on repeating itself and does not even consider the try and catch following it.
Here is my method
boolean retry = false;
java.sql.Date releaseDate = null;
String releaseDateString = "";
String title = "";
while (!retry) {
while(!retry){//field is validated to make sure a value was entered and to exit if cancel was pushed
releaseDateString = JOptionPane.showInputDialog("Please input the release date of the movie (yyyy-mm-dd)");
qtd.stringValidation(releaseDateString);
}
try { //the date is validated to make sure it is in the correct format
releaseDate = java.sql.Date.valueOf(releaseDateString);
} catch (Exception e) {
retry = false;
JOptionPane.showMessageDialog(null, "Make sure you enter a date in the format of 'dd-mm-yyy'");
}
}
It links to this method
public static boolean stringValidation(String attribute){
boolean retry = false;
if (attribute == null){
System.exit(0);
}
else if (attribute.equals("")) //if the cancel button is selected or no value was entered into the
{
JOptionPane.showMessageDialog(null, "Make sure you enter a character into the textbox");
}
else {
retry = true;
}
return retry;
}
When you do this,
qtd.stringValidation(releaseDateString);
You aren't assigning the result to retry. I believe you wanted,
retry = qtd.stringValidation(releaseDateString);