Simple switch statement error? - java

Let me know if you guys see anything wrong with this. I am getting this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at interaction.menu(interaction.java:15)
at driver.main(driver.java:9)
Line 15 is selection = scan.nextInt(); right inside the while loop. The main simply contains a method that calls this method in this class.
//provides the interface to be used
public void menu(){
Scanner scan = new Scanner(System.in);
database db = new database();
int selection;
while(true){
hugeTextBlock();
selection = scan.nextInt();
switch(selection){
//creates a new course
case 1: db.addCourse();
//removes a course
case 2: db.deleteCourse();
//enroll a student
case 3: db.enrollStudent();
//delete a student
case 4: db.deleteStudent();
//register for a course
case 5: db.registerStudent();
//drop a course
case 6: db.dropCourse();
//check student registration
case 7: db.checkReg();
//quit
case 8: break;
default: System.out.println("default action");
}
}
}
Below is the addCourse method inside another class. I have ran it by itself and it works just fine.
//creates a new course
public void addCourse(){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:StudentRegistration_DSN");
Statement st = conn.createStatement();
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the course title: ");
String title = scan.nextLine();
System.out.println("Please enter the course's code: ");
String code = scan.next();
st.executeUpdate("insert into course values('"+code+"','"+title+"')");
ResultSet rs = st.executeQuery("select * from course");
code = "";
title = "";
System.out.println("This is the relation as of current changes.");
while (rs.next())
{
code=rs.getString(1);
title=rs.getString(2);
System.out.println("Code: " + code + " Title: " + title);
}
rs.close();
st.close();
conn.close();
scan.close();
}
catch (Exception e){
System.out.println(e);
}
}

First of all, only breaking the switch on case 8 will cause weird things to happen. You should add a break after every case, and add System.exit(0) for case 8.
Second, did you type anything at the scanner prompt? If you type an end-of-input symbol, this will happen. Also, what stream does System.in correspond to? If you are invoking this from a genuine command line and do not type the end-of-input, I don't see how this could happen.

The exception is telling that Scanner.nextInt has no int to read. You should ensure that the next thing scanner will return is, in fact, an int. See Scanner.hasNextInt.
while (!scanner.hasNext()) {
// sleep here
}
if (scanner.hasNextInt()) {
selection = scan.nextInt();
} else {
selection = 0;
scan.next(); // reads the garbage.
}

Related

Error while using database in Java using SQLite

Bank class calling the Atm class.The machine class contains the start machine method. Here onwards loop will run forever calling the required methods from another classes not relevant. The create table method should be called only once.Once the Pin is validated the program runs infinitely
import java.util.Scanner;
public class Bank {
final static int PIN = 5423;//pin to start the ATM operations
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the PIN to start the machine");
for(int i = 3; i >= 1;--i) {
int n = scanner.nextInt();
if(n == PIN) {//if pin was correct , start the ATM
Atm atm = new Atm();
atm.startMachine();
break;
}
else if(i > 1)
System.out.println("Incorrect PIN. You have " + (i-1) + " tries remaining");
else {
System.out.println("Tries exhausted. Contact the main office.");
break;
}
}
scanner.close();
}
}
Atm class which has start machine method
class Atm {//class for functioning of ATM
Scanner scan;
protected String load;//loading time
protected int cashAvailable = 2000000;//initial cash available
static Database database;
Atm(){//constructor to initialize fields
scan = new Scanner(System.in);
load = "00:00";//the loading time at midnight
database = new Database();
database.createTable();//call the database class
}
public void startMachine(){//start the machine
Machine machine = new Machine();
machine.start();//call the start method
}
}
And the machine class
public void start() {//method to start the machine
Withdraw withdraw = new Withdraw();//withdraw object
Deposit deposit = new Deposit();//deposit object
while(true) {//infinite loop for functioning of machine
String currentTime = new SimpleDateFormat("HH:mm").format(new Date());//get the current time
boolean isLoadingTime = currentTime.equals(load);//if is loading time
if(isLoadingTime) {//if yes, the call load method
load();//method to load the cash
}
//show the welcome screen at every iteration
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println();
System.out.println("Welcome to National Bank");
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.print(formatter.format(date) + " ");
System.out.println(LocalDateTime.now().getDayOfWeek());
System.out.println("Press 1 to view your current balance");
System.out.println("Press 2 to withdraw cash");
System.out.println("Press 3 to deposit funds");
System.out.println();
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
while(true) {
int enter_num = scan.nextInt();//get the preferred choice
if(enter_num == 1) {
currentBalance();//method to show current balance
break;
}
else if(enter_num == 2) {
withdraw.debit();//method to withdraw cash
break;
}
else if(enter_num == 3) {
deposit.giveCash();//method to deposit cash
break;
}
else
break;//if not valid option
}
}
}
The obvious errors in your code in update() method are the comma after SET Balance = ? which you must remove and also change the indices of stmt.setInt() to 1 for balance and 2 for accountNo because you are passing 2 paremeters with that order in your UPDATE statement:
String change = "UPDATE accounts SET Balance = ? WHERE AccountNumber = ?";
try {
PreparedStatement stmt = conn.prepareStatement(change);
stmt.setInt(1,balance);
stmt.setInt(2,accountNo);
.............................
Also, the error message:
Abort due to constraint violation (UNIQUE constraint failed:
accounts.AccountNumber)
means that you are trying to insert in the table an account number that already exists in the table and this is not allowed because the column AccountNumber is the primary key of the table so it is unique.
Also, inside createTable() what is sc? Is it a resultset?
If so, what are you trying to do? Are you trying to loop through the rows of the table?
The table is just created and it is empty.
From the code that you posted, I can't see why you get 4 times the message "A new database has been created", because I don't know how you call the method createTable().

Unable to return the value after nesting while loops inside a method

I'm having issue returning the DVDs object after adding the second while loop (promptAddAgain). This function works perfect before this while loop was added. Error during compile - cannot find symbol: variable currentDVD.
public DVDs getNewDVDInfo() {
boolean keepRunning = true;
boolean promptAddAgain = true;
while (keepRunning) {
String title = input.readString("Please enter the move title.");
String releaseDate = input.readString("Please enter the release date.");
String MPAArating = input.readString("Please enter the MPAA rating.");
String directorName = input.readString("Please enter the director name.");
String studio = input.readString("Please enter the name of the studio.");
String userRating = input.readString("Please type in any comment you would "
+ "like to leave for this movie below.");
DVDs currentDVD = new DVDs(releaseDate, MPAArating, directorName, studio, userRating);
currentDVD.setTitle(title);
while (promptAddAgain) {
String userAns = input.readString("Would you like to add another DVD to the library?");
if (userAns.equals("n")) {
input.print("Thank you. Returning to main menu.");
keepRunning = false;
promptAddAgain = false;
} else if (userAns.equals("y")) {
input.print("\n");
} else {
input.print("Unknown input, please try again.");
keepRunning = false;
}
}
}
return currentDVD; //<--- error
}
The error is arising because currentDVD is currently being defined inside the outer while loop, but you are referring to it outside that loop, after it has gone out of scope. One way to fix this is to declare currentDVD before the first while loop:
DVDs currentDVD = null;
while (keepRunning) {
...
}
return currentDVD;
Keep in mind that with the above approach it is possible that your getNewDVDInfo() method might return null, so callers should be aware of that.

Ignore duplicate in string and print string once

Pretty much for my assignment I have to List all the courses (just the course code) that have classes in a given building on a given day such that any part of the class is between the given times. Each course involved should only be listed once, even if it has several classes. I have done everything except listing the course once, even if it has several classes. How do I ignore duplicate strings from a file?
public void potentialDisruptions(String building, String targetDay, int targetStart, int targetEnd){
UI.printf("\nClasses in %s on %s between %d and %d%n",
building, targetDay, targetStart, targetEnd);
UI.println("=================================");
boolean containsCourse = false;
try {
Scanner scan = new Scanner(new File("classdata.txt"));
while(scan.hasNext()){
String course = scan.next();
String type= scan.next();
String day = scan.next();
int startTime = scan.nextInt();
int endTime = scan.nextInt();
String room = scan.next();
if(room.contains(building)){
if(day.contains(targetDay)){
if(endTime >= targetStart){
if( startTime<= targetEnd){
UI.printf("%s%n", course);
containsCourse = true;
}
}
}
}
}
if(!containsCourse){
UI.println("error");
}
}
catch(IOException e){
UI.println("File reading failed");
}
UI.println("=========================");
}
You can put all the string token in Set and check if that token contain in Set befor you process further as below :-
// Declration
....
Set courseSet = new HashSet();
...
// Check befor you process further
if(!courseSet.contains(course))
{
...
// Your Code...
...
courseSet.add(course)
}
You could put the courses in a Set and loop over them since a Set always contains unique values.

Printing hello world without main method

I am using Eclipse. I am trying to make a program that doesn't contain a main function, but will still print Hello, World:
public class Q
{
static
{
System.out.println("Hello World");
System.exit(0);
}
}
But this program is not giving me expected result.An error is coming which says that main method is not found in class Q. Where I am making a mistake?
You still need to run the program for the static initialization block to execute, which you cannot do without an appropriate main method (as of Java 71). Now, that's not to say main needs to actually contain any code:
class Q {
static {
System.out.println("Hello World");
System.exit(0);
}
public static void main(String[] args) {}
}
1 Your code actually works in Java 6 and below - you don't need a main method. This is because the static initialization block executes before a main method is searched for. But, in your case, you exit the program at the end of that block with System.exit(0), and so Java never looks for main and you don't receive an error.
Every Java Application Program must contain a class with main method in it. So your error will persist until you declare a main method inside one of the classes in your program.
It is impossible. Your program MUST contain the main method, or the system doesnt know witch piece of code to run.
Your mistake is that you are trying to run class that does not have main method (exactly as you explained).
JVM is looking for public static void main method that accepts array o String as an argument as an entry point to any program.
"Java programs start executing at the main method, which has the
following method heading:
public static void main(String[] args)"
(http://en.wikipedia.org/wiki/Main_function#Java)
You should alter your class to be something similar to what I've put below.
public class Q
{
public static void main(String[] args)
{
System.out.println("Hello World");
System.exit(0);
}
}
import java.sql.*;
import java.io.*;
import javax.sql.*;
public class Emsa
{
public static void main(String args[])
{
int ch;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl","hr","hr");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from Empdirc");
while(rs.next())
do
{
System.out.println("\n");
System.out.println("ENTER EMPLOYEE DETAILS:");
System.out.println("1.Insert Record into the Table");
System.out.println("2.Update The Existing Record.");
System.out.println("3.Display all the Records from the Table");
System.out.println("4.Check PRIVILAGE LEAVE and Casual Leaves");
System.out.println("5.Exit");
System.out.println("Enter your choice: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("1.INSERT EMPLOYEE ID.");
int num= Integer.parseInt(br.readLine());
System.out.println("2.INSERT EMPLOYEE NAME");
String ename=br.readLine();
System.out.println("3.INSERT EMPLOYEE DESIGNATION");
String desig=br.readLine();
System.out.println("4.INSERT EMPLOYEE DATEOFBIRTH");
String dob=br.readLine();
System.out.println("5.INSERT EMPLOYEE PHONE NO OR ANY CONTACT");
String mob= br.readLine();
System.out.println("6.INSERT EMPLOYEE EMAIL ID");
String email= br.readLine();
System.out.println("7.INSERT EMPLOYEE SALARY");
String sal=br.readLine();
System.out.println("8.INSERT EMPLOYEE paid LEAVES");
String pl=br.readLine();
System.out.println("9.INSERT EMPLOYEE CASUAL LEAVES");
String cl=br.readLine();
System.out.println("10.INSERT EMPLOYEE FINAL SALARY");
String fi= br.readLine();
System.out.println("11.STATUS");
String s=br.readLine();
String sql="insert into EmpDirc values(?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement p=con.prepareStatement(sql);
p.setInt(1,num);
p.setString(2,ename);
p.setString(3,desig);
p.setString(4,dob);
p.setString(5,mob);
p.setString(6,email);
p.setString(7,sal);
p.setString(8,pl);
p.setString(9,cl);
p.setString(10,fi);
p.setString(11,s);
public static boolean abcd(String str)
{
int x;
for(int mob= 0 ; mob < str.length() ; mob++)
{
x = (int)str.charAt(mob);
if( x < 10 || x > 0)
return false;
}
return true;
}
p.executeUpdate();
System.out.println("Record Added");
//p.close();
//con.close();
break;
case 2:
System.out.println("UPDATE EMPLOYEE id : ");
int emnum=Integer.parseInt(br.readLine());
System.out.println("UPDATE EMPLOYEE DESIGNATION : ");
String emdesig=br.readLine();
System.out.println("UPDATE EMPLOYEE PHONE: ");
String emphn=br.readLine();
System.out.println("UPDATE EMPLOYEE EMAIL: ");
String emmail=br.readLine();
System.out.println("UPDATE EMPLOYEE SALARY: ");
String emsal=br.readLine();
System.out.println("UPDATE EMPLOYEE PL: ");
String empl=br.readLine();
System.out.println("UPDATE EMPLOYEE CL: ");
String emcl=br.readLine();
System.out.println("UPDATE EMPLOYEE FINAL SALARY: ");
String emfi=br.readLine();
sql="update EmpDirc set Desig=?, Mob=? , Email=?, Sal=? , fi=? where Eid=?";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,emdesig);
ps.setString(2,emphn);
ps.setString(3,emmail);
ps.setString(4,emsal);
//ps.setString(5,empl);
//ps.setString(6,emcl);
ps.setString(5,emfi);
ps.setInt(6,emnum);
ps.executeUpdate();
System.out.println("Record Updated");
//p.close();
//con.close();
break;
case 3 : System.out.println("Displaying the Data ");
//Statement stmt=con.createStatement();
ResultSet res=stmt.executeQuery("select * from Empdirc");
while(res.next())
System.out.println("Eid"+res.getInt(1)+"Ename "+res.getString(2)+"Design "+res.getString(3)+"Dob "+res.getString(4)+"Mobile no."+res.getString(5)+"Email "+res.getString(6)+"Salary "+res.getString(7));
break;
case 4 : System.out.println("CALCULATING");
sql="update EmpDirc set Pl=?, Cl=? where Estatus=?";
PreparedStatement pes=con.prepareStatement(sql);
pes.setInt(1,15);
pes.setInt(2,07);
pes.setString(3,"permanent");
pes.executeUpdate();
System.out.println("Record Updated");
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid Choice");
break;
}
}while(ch!=2);
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

I'm getting an error in my loop. Exception in thread "main" java.util.NoSuchElementException. The error is my scanner?

Ok, it looks like I've ran into a few problems with my main class. It breaks my loop on the 2nd run and displays and error. It says my scanner to read the user selection from the menu is creating the error? How is that, it worked the first loop, but for some reason it can't run again.
"action = new Scanner(System.in).nextInt();"
is generating the error. Does anyone know why this is happening, as it is very important to read the integer the user puts in as the user is selecting a menu option.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.String;
import java.lang.System;
public class MainActions {
public static void main(String args[]) throws IOException {
int action = 0;
while (action != 6) {
Contact.menu();
new Scanner(System.in);
action = new Scanner(System.in).nextInt();
if (action <= 0 || action > 6) {
System.out.println("Invalid selection. ");
}
switch (action) {
case 1:
MainActions.addContactInfo();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
}
}
public static void addContactInfo() {
Contact contact;
contact = new Contact();
Scanner reader = new Scanner(System.in);
System.out.println("Enter Contact Last Name:");
String lastname = reader.nextLine();
contact.setLastName(lastname);
System.out.println("Enter Contact First Name: ");
contact.setFirstName(reader.nextLine());
System.out.println("Enter Contact Street Address: ");
contact.setHouseAddress(reader.nextLine());
System.out.println("Enter Contact City: ");
contact.setCity(reader.nextLine());
System.out.println("Enter Contact Zip Code: ");
contact.setZip(reader.nextLine());
System.out.println("Enter Contact Email: ");
contact.setEmail(reader.nextLine());
System.out.println("Enter Contact Phone Number: ");
contact.setPhone(reader.nextLine());
System.out.println("Enter Contact Notes: ");
contact.setNotes(reader.nextLine());
if (lastname.trim().equals("")) {
System.out.println("\nLast name was blank, contact not saved.");
System.exit(0);
} else {
ContactList list;
list = new ContactList();
list.add(contact);
list.save();
Contact c = contact;
try (PrintWriter output = new PrintWriter(new FileWriter("contactlist.csv", true))) {
output.printf("%s\r\n", c);
} catch (Exception e) {}
}
reader.close();
}
}
Console:
1. Enter a new person
2. Print the contact list
3. Retrieve a person's information by last name
4. Retrieve a person's information by email address
5. Retrieve all people who live in a given zip code
6. Exit
1
Enter Contact Last Name:
asdf
Enter Contact First Name:
asdf
Enter Contact Street Address:
asdf
Enter Contact City:
asdf
Enter Contact Zip Code:
asdf
Enter Contact Email:
asdf
Enter Contact Phone Number:
asdf
Enter Contact Notes:
asdf
Contact information has been saved.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at MainActions.main(MainActions.java:33)
1. Enter a new person
2. Print the contact list
3. Retrieve a person's information by last name
4. Retrieve a person's information by email address
5. Retrieve all people who live in a given zip code
6. Exit
Replace
new Scanner(System.in);
action = new Scanner(System.in).nextInt();
With
Scanner scan = new Scanner(System.in);
action = scan.nextInt();
new Scanner(System.in); // Remove this. Not needed.
action = new Scanner(System.in).nextInt();
Wait up, this is not the problem. Here is the actual problem.
reader.close();
This line in your addContactInfo() is the culprit. Remove this and your code will work.
This reader.close() closes your Scanner(scanning the System.in) in your method, as both are scanning System.in.
Hope this solves your problem. I just happened to find this question on SO. Check this out for more detailed explanations.
Docs says this:-
public void close() throws IOException
Closes this input stream and releases any system resources associated
with this stream. The general contract of close is that it closes the
input stream. A closed stream cannot perform input operations and
cannot be reopened.

Categories