Why am I getting NoSuchElementException? - java

Here is my code:
while (menuExit == true) {
System.out.println (SEPARATE_LINE);
System.out.println ("Which do you want to do ? ");
System.out.println (SEPARATE_LINE);
System.out.println ("1.Register");
System.out.println ("2.Sign in");
System.out.println ("3.Check shop status");
System.out.println ("0.Exit");
System.out.println (SEPARATE_LINE);
System.out.print("Please enter your choice as number:");
do{
try{
int selectMain = input.nextInt();
if(selectMain == 1){
register(currentNum , customers);
customers.clear();
customers = ReadData.readCustomerData();
}else if(selectMain == 2){
signIn(customers,historys,cusData,hisData);
}else if(selectMain == 3){
CheckData.checkShopStatus(shops,shopData);
}else if(selectMain == 0){
System.out.println ("Thank you");
menuExit = false;
}else {
System.out.println ("Your input are wrong , Please enter again.");
}
continueInput = false;
}catch(InputMismatchException ex){
System.out.println("Please enter again.");
input.nextLine();
}
}while (continueInput);
input.close();
This is the menu of my program , when I enter into one of these selection and come back to the menu , I got NoSuchElementException , the error point to the line int selectMain = input.nextInt();. Please someone help me , thank you for your attention.

You have continueInput = false in the try block in such a way that it means that it will run regardless of the user input. This means the dowhile loop exits on the next try, and the input is closed. however, because this is in another while loop, it tries to get another input, even though the input scanner is closed! This gets you the NoSuchElementException.

Related

I am writing a program to act like a CoinStar. Whenever I type my sentinel 'done' there is an error

`String termination;
do {
System.out.println("Begin Transaction!");
int coinNumber;
String deposit;
do{
System.out.print(">>");
coinNumber = input.nextInt();
deposit = input.nextLine();
int search = deposit.indexOf(" ", 0);
String denominations = deposit.substring(search +1);
if (coinNumber < 0){
System.out.println("Error! Please deposit positive number.");
}
else if (denominations.equalsIgnoreCase("quarter") || denominations.equalsIgnoreCase("quarters")){
Customer.insertQuarters(coinNumber);
}
else if (denominations.equalsIgnoreCase("dime") || denominations.equalsIgnoreCase("dimes")){
Customer.insertDimes(coinNumber);
}
else if (denominations.equalsIgnoreCase("nickels") || denominations.equalsIgnoreCase("nickels")){
Customer.insertNickles(coinNumber);
}
else if (denominations.equalsIgnoreCase("penny") || denominations.equalsIgnoreCase("pennies")){
Customer.insertPennies(coinNumber);
}
else if (denominations.equalsIgnoreCase("quarter") || !denominations.equalsIgnoreCase("quarters")
|| !denominations.equalsIgnoreCase("dime") || !denominations.equalsIgnoreCase("dimes")
|| !denominations.equalsIgnoreCase("nickel") || !denominations.equalsIgnoreCase("nickels")
|| !denominations.equalsIgnoreCase("penny") || !denominations.equalsIgnoreCase("pennies")
|| !deposit.equalsIgnoreCase("done")){
System.out.println("Error! Please deposit correct denominations.");
}
} while (!deposit.contains("done"));
System.out.println(Customer.getVoucher());
System.out.print("Would you like to start another transaction (y/n): ");
termination = input.nextLine();
}
while (termination.equalsIgnoreCase("y"));
System.out.println(Customer.getCollectedFees());
input.close();
}
}`
I need it to be were user inputs: (4 quarters) and as many deposits as they want. Then, types 'done' without having lines in between the deposits.
enter image description here
Thank you.
The carriage return character isn't absorbed when you make a call to nextInt(). Try placing a Scanner.nextLine() right after your initialize coinNumber:
coinNumber = input.nextInt();
input.nextLine();
deposit = input.nextLine();

Battleship Game-Exceptions

I'm doing a java program for an assignment, and one of the exceptions are that the user cannot input a value for a row or column that does not exist. i.e If the board was 5x7 and the user entered a column of value 10 the screen would print "Error: Invalid column" . However i'm unsure how to do this final exception and i need to submit it today. If anyone could help i'd really appreciate it! Here is my code for the makeGuess() function:
public void makeGuess(){
//guesses is for keeping track of your guesses
boolean cont=true;
int rowGuess;
int columnGuess;
do{
System.out.println("Enter a row to guess >");
rowGuess = (input.nextInt()-1);
if(rowGuess<=0){
System.out.println("You did not enter a positive Integer.Please try again");
cont=false;}
else{
cont=true;}
}
while (cont==false);
do{
System.out.println("Enter a column to guess >");
columnGuess = (input.nextInt()-1);
if(columnGuess <=0){
System.out.println("You did not enter a positive integer.Please try again");
cont=false;
} else{
cont=true;
}
}while(cont==false);
Assuming that the rest of your code works, you could simply alter your if statements to ensure the entry is valid.
Using the OR operator ||:
if (columnGuess <= 0 || columnGuess >= 10){
System.out.println("Error: invalid Column");
}
just as you have an if statement to test if the number is too small you also need to test if it is too big
public void makeGuess(){
//guesses is for keeping track of your guesses
boolean cont=true;
int rowGuess;
int columnGuess;
do{
System.out.println("Enter a row to guess >");
rowGuess = (input.nextInt()-1);
if(rowGuess<=0){
System.out.println("You did not enter a positive Integer.Please try again");
cont=false;
}else if(rowGuess>7){
System.out.println("You did not enter a small enough Integer.Please try again");
cont=false;
}else{
cont=true;
}
}while (cont==false);
do{
System.out.println("Enter a column to guess >");
columnGuess = (input.nextInt()-1);
if(columnGuess <=0){
System.out.println("You did not enter a positive integer.Pleasetry again");
cont=false;
}else if(columnGuess>5){
System.out.println("You did not enter a small enough Integer.Please try again");
cont=false;
} else{
cont=true;
}
}while(cont==false);
A better way to do this in my experience is to create your own exception
public class BadMoveException extends Exception {
BadMoveException(Exception ex) {
super(ex);
}
BadMoveException(String ex) {
super(ex);
}
}
Make makeGuess throw BadMoveException, and then for any of the invalid moves the user can make, you can create a BadMoveException with that, and print it in the catch { } block outside of makeGuess
while (!gameOver) {
try {
makeGuess();
}
catch (BadMoveException ex) {
System.out.println("You tried to make an invalid move:" + ex.getMessage());
}
}

Java - If statement logic error

The sequence of events should be:
1) I enter two.
2) I am prompted to choose a name.
3) I choose either Washington/ Franklin/ Hamilton.
4) I'm asked which denomination does this name appear on.
5) I give the answer.
However, when I enter Washington for part three - I am told that is an invalid number. I cannot see why this would be.
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Type 1 to enter a denomination, 2 to enter a last name");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
if(x==1){
System.out.println("Choose a denomination");
int y = in.nextInt();
in.nextLine();
if(y==1){
System.out.println("Which person appears on the 1 bill?");
String answer = in.nextLine();
if(answer.equals("Washington")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==10){
System.out.println("Which person appears on the 10 bill?");
String answer = in.nextLine();
if(answer.equals("Hamilton")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==100){
System.out.println("Which person appears on the 100 bill?");
String answer = in.nextLine();
if(answer.equals("Franklin")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
else if(x==2){
System.out.println("Choose a name");
String y = in.nextLine();
in.nextLine();
if(y.equals("Washington")){
System.out.println("Which denomination does this name appear on?");
int answer = in.nextInt();
if(answer==1){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Hamilton")){
System.out.println("Which denomination does this name appear on");
int answer = in.nextInt();
if(answer==10){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Franklin")){
System.out.println("Which denomination does this name appear on");
int answer = in.nextInt();
if(answer==100){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
}
The problem is with the x==2 segment. x==1 works fine.
The problem does not lies with the seemingly extra in.nextLine().
I will advise you to change all your in.nextInt() to in.nextLine() followed by parsing them to the actualy type such as int
Example:
int answer = Integer.parseInt(in.nextLine());
Reason for the suggested change: When you use nextInt(), there is a tendency that nextline still lingers around there until you do an additional nextLine() to clear it.
To prevent this sort of problems, it is advisable to receive all inputs with nextLine(), then parse it to the actual type (int, double..etc).
This is also how Microsoft deals with integer input in C#.
Edited Working Codes:
public static void main(String[] args) {
System.out.println("Type 1 to enter a denomination, 2 to enter a last name");
Scanner in = new Scanner(System.in);
int x = Integer.parseInt(in.nextLine());
if(x==1){
System.out.println("Choose a denomination");
int y = Integer.parseInt(in.nextLine());
in.nextLine();
if(y==1){
System.out.println("Which person appears on the 1 bill?");
String answer = in.nextLine();
if(answer.equals("Washington")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==10){
System.out.println("Which person appears on the 10 bill?");
String answer = in.nextLine();
if(answer.equals("Hamilton")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==100){
System.out.println("Which person appears on the 100 bill?");
String answer = in.nextLine();
if(answer.equals("Franklin")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
else if(x==2){
System.out.println("Choose a name");
String y = in.nextLine();
//in.nextLine();
if(y.equals("Washington")){
System.out.println("Which denomination does this name appear on?");
int answer = Integer.parseInt(in.nextLine());
if(answer==1){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Hamilton")){
System.out.println("Which denomination does this name appear on");
int answer = Integer.parseInt(in.nextLine());
if(answer==10){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Franklin")){
System.out.println("Which denomination does this name appear on");
int answer = Integer.parseInt(in.nextLine());
if(answer==100){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
}
String y = in.nextLine();
in.nextLine();
if(y.equals("Washington")){
You're calling in.nextLine() one too many times. Remove that second line.
When you do String y = in.nextLine(), the next token is the leftover newline from the previous nextInt() call, so y ends up being equal to \n.
Place a call to nextLine() after you use nextInt():
int x = in.nextInt();
in.nextLine();
Afterwards you should be able to call nextLine only once when getting the user input:
String y = in.nextLine();
if(y.equals("Washington")){
You have to skip the line after nextInt() then take user input(in y==2 case) because nextInt() doesnot consume the whole line it consume the token.
in.nextLine();
String y = in.nextLine();
with your code the in.nextLine() in String y = in.nextLine(); is reading the same line where you entered value of x getting the value y to be "" and hence the output "That is an invalid number"

Else without if?

I was working on my assignment for my Java 1 class and I am getting an error that does not seem like it should be one. Can I get some help? It is saying that I have an else w/out if.
here is the if block
char placement = scan.next().toUpperCase().charAt(0);
if(placement == 'F')
{
System.out.print("Please Enter The Show To Be Added At The Beginning Of The List: ");
String show = scan.next();
TVShows.add(0, show);
}
else if(placement == 'R');
{
System.out.print("Please Enter The Show To Be Added At The End Of The List");
String show = scan.next();
TVShows.add(show);
}
else
{
System.out.println("Invalid Choice Please Try Again");
}
Remove the semi colon
else if (placement == 'R');
^
which is terminating the else if block statement

Java Basic Login Feature

I'm trying to implement a login feature in this program. I finally figured it out how to do a basic one, but sadly I do not know how to end it, like for example if the user had finally reached the limit of 3 it should end, but mine still continues and I don't know where and what code I should put in order for it to end than continuing to the main program.
import java.io.*;
public class Password{
public static void main(String args[]) throws IOException{
String name, un, pw;
String Username = "passwordtest";
String Password = "test123";
int stud;
double math, science, english, filipino, social, ave, sum, fingrade;
BufferedReader inpt = new BufferedReader (new InputStreamReader(System.in));
for(int trial=1; trial<=3; trial++){
System.out.print("Username: ");
un = inpt.readLine();
System.out.print("Password: ");
pw = inpt.readLine();
System.out.println("");
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
trial=trial+2;
continue;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
}
System.out.println("");
System.out.println("Welcome to ITMinions' Grading System!");
System.out.println("How many students' grades would you like to record?");
System.out.print("Answer: ");
stud=Integer.parseInt(inpt.readLine());
System.out.println("");
for (int ctr=1; ctr<=stud; ctr++){
System.out.print("Name of the student: ");
name = inpt.readLine();
System.out.println("");
System.out.println("Input the following grades");
System.out.print("Math: ");
math = Double.parseDouble(inpt.readLine());
if(math<65 || math>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("Science: ");
science = Double.parseDouble(inpt.readLine());
if(science<65 || science>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("English: ");
english = Double.parseDouble(inpt.readLine());
if(english<65 || english>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("Filipino: ");
filipino = Double.parseDouble(inpt.readLine());
if(filipino<65 || filipino>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("History: ");
social = Double.parseDouble(inpt.readLine());
if(social<65 || social>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
sum=math+science+english+filipino+social;
ave=sum/5;
System.out.println("");
System.out.println("The average of " + name + " is: " + ave);
System.out.println("");
}
}
}
Please help! And yes this is related to school work :)
Thanks!
I would rewrite the part of the loop that handles succesfull login as follows:
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
break;
}
Notice using the break keyword to break out of the loop.
You can use System.exit(0); to exit when the user has used all login attempts.
You must use another variable for example: boolean isLoggedIn, and set that if successfully logged in, and then break instead of continue as below:
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
isLoggedIn = true;
break;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
Then outside the for loop, check if(isLoggedIn) and do actions accordingly.
Modify your fi statement
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
break;;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
}
if(trail==4)
{
//Write your locking logic here
}
its not good practice to hard code things in your code. Try to use property file for simplicity or if you have time use jdbc
To avoid Null pointer exception use
Username.equals(un)
Also, make sure you follow proper Java coding standards like camel-case for variable naming, and all upper case for constants. Since username and password are hardcoded, they are infact constants. So, change
String Username = "passwordtest";
String Password = "test123";
to
final String USERNAME = "passwordtest";
final String PASSWORD = "test123";
It would also be better if you could load these constants from a properties file, because when passwords change, you need not modify your code, just edit properties file.
To clarify the previous answers:
booelan isLoggedIn = false;
for ( int trials = 3; trials > 0; trials-- )
{
<ask uname, password> // Java convention: don't capitalise variable names
if ( isLoggedIn = <uname/password are OK> {
System.out.println ( "Success" );
break;
}
System.out.printf ( "Bad uname/pass, %d attempts remaining\n", trials );
}
if ( !isLoggedIn ) {
System.out.println ( "User couldn't give valid credentials, quitting after three attempts, due to security reasons" );
Thread.sleep ( 3000 ) // try to fight brute-force attackers
System.exit ( 1 ); // Not zero, it's not a regular end
}
// Go ahead with your application

Categories