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);
}
}
}
Related
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().
I am having a hard time how to return into specific variable or how to return without getting any error base on my program.
class Facebook {
public static void main(String[]args){
String user = JOptionPane.showInputDialog(null,"Enter Username: ");
String pass = JOptionPane.showInputDialog(null,"Enter Password: ");
if(user.equals("jas")&&(pass.equals("bsit"))){
JOptionPane.showMessageDialog(null,"Welcome "+ user);
Selection Class = new Selection();
Selection.Selection1();
}
else if (!user.equals("jas")||(!pass.equals("bsit"))) {
JOptionPane.showMessageDialog(null,
"Invalid Username or Password",
"Wrong Authentication",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
class Selection{
public Selection1(){
try{
String select = JOptionPane.showInputDialog("[1]Home\n[2]Profile\n[3]Logout");
int numbers = Integer.parseInt(select);
if (numbers == 1){
JOptionPane.showMessageDialog(null,"Mang Tani: Lumakas ang hanging amihan halos nilipad ang mga bubong ng mga bahay\n\nJessica Soho: Isang sikat na pagkain sa davao inubos ng kabataan \n\n Boying Remulla: Walang pasok dahil sa malakas na ulan\n#WalangPasok.");
return select;
}
else if (numbers == 2){
JOptionPane.showMessageDialog(null,"Name: Ralph Jasper \n\n Age: 17 \n\n Address: Tierra Nevada, General Trias, Cavite");
}
else if (numbers == 3){
}
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please input only numbers","Invalid Input",JOptionPane.ERROR_MESSAGE);
}
}
}
1) you want a method with a return value of a string
Replace
public Selection1(){
with
public String select()
2) all "paths" of a non-void method must result in a return statement. This does not mean a return statement needs to be inside any if else's, but you do need to return something within the method.
Suggestion: declare a String result = ""; outside of the try catch, return it after, outside of the catch, and assign it to your JOptionPane value in between like result = JOptionPane...
3) I'm assuming you actually want that value that's returned?
Selection selector = new Selection();
String selected = selector.select();
// TODO use that value
Notice: Java naming conventions -- methods are lowerCase, classes are UpperCase.
I've got a class named "User" which has a method that makes the User type his name. This name is saved in an array that is empty at first.
Question is, how can I use this "stored" name in another class (I want to show the name in this other class)
Here's what I've got (Sorry for the spanish lol)
public class Usuario {
private Scanner entrada = new Scanner(System.in);
private String Usuario[] = new String[20];
private int Posicion = 0;
private int punteo;
public void Datos() {
System.out.println("Ingresa tu nombre");
if(Usuario[Posicion] == null) {
this.Usuario[0] = entrada.nextLine();
Posicion++;
}
}
public String Usuario() {
return Usuario[Posicion-1];
}
And I want to use the name (Usuario[Posicion-1]) for example in a class like this:
public class Score extends Usuario {
Usuario usr = new Usuario();
String[] Name = new String[20];
public void Score () {
Name[0]=usr.Usuario();
System.out.println("------------Scores ------------------");
System.out.println(" Name "+ " Score");
for(int i=0;i<11;i++) {
System.out.println(i+".- " + " "+Name[0] +" 200 ");
}
}
}
But Everytime I try to retrieve this data in this class I get a "null" value or an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" error, which makes me believe that I can't use the information from the array in another class :(
I'd appreciate any help. (also Sorry for the not-so-good english).
Each new version of a class or an object is not going to have the same values.
you will have to get the name from the object User.name then set it in your other object secondObject.name = User.name
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.
}
I'm trying to do an exercise from a java book. The code comes as is and I have not added anything to the code besides setting the path for the database. I'm on OSX, so I had to install Apache Derby. Everytime I build and run the program I get this:
Derby has been started.
Product list:
bvbn Murach's Beginning Visual Basic .NET $49.50
cshp Murach's C# $49.50
java Murach's Beginning Java $49.50
jsps Murach's Java Servlets and JSP $49.50
mcb2 Murach's Mainframe COBOL $59.50
sqls Murach's SQL for SQL Server $49.50
zjcl Murach's OS/390 and z/OS JCL $62.50
Exception in thread "main" java.lang.NullPointerException
First product:
at DBTesterApp.printProduct(DBTesterApp.java:117)
at DBTesterApp.printFirstProduct(DBTesterApp.java:66)
at DBTesterApp.main(DBTesterApp.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I'm confused as to why this exception keeps happening. I don't seem to find anything wrong with the 'main' code (see below) and I feel like I've tried everything. Any clue as to what could be causing this?
import java.sql.*;
public class DBTesterApp
{
private static Connection connection = null;
public static void main(String args[])
{
// get the connection and start the Derby engine
connection = MurachDB.getConnection();
if (connection != null)
System.out.println("Derby has been started.\n");
// select data from database
printProducts();
printFirstProduct();
printLastProduct();
printProductByCode("java");
// modify data in the database
Product p = new Product("test", "Test Product", 49.50);
insertProduct(p);
printProducts();
deleteProduct(p);
printProducts();
// disconnect from the database
if (MurachDB.disconnect())
System.out.println("Derby has been shut down.\n");
}
public static void printProducts()
{
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Products"))
{
Product p = null;
System.out.println("Product list:");
while(rs.next())
{
String code = rs.getString("ProductCode");
String description = rs.getString("Description");
double price = rs.getDouble("Price");
p = new Product(code, description, price);
printProduct(p);
}
System.out.println();
}
catch(SQLException e)
{
e.printStackTrace(); // for debugging
}
}
public static void printFirstProduct()
{
Product p = null;
// add code that prints the record for the first product in the Products table
System.out.println("First product:");
printProduct(p);
System.out.println();
}
public static void printLastProduct()
{
Product p = null;
// add code that prints the record for the last product in the Products table
System.out.println("Last product:");
printProduct(p);
System.out.println();
}
public static void printProductByCode(String productCode)
{
Product p = null;
// add code that prints the product with the specified code
System.out.println("Product by code: " + productCode);
printProduct(p);
System.out.println();
}
public static void insertProduct(Product p)
{
System.out.println("Insert test: ");
// add code that inserts the specified product into the database
// if a product with the specifed code already exists, display an error message
printProduct(p);
System.out.println();
}
private static void deleteProduct(Product p)
{
System.out.println("Delete test: ");
// add code that deletes the specified product from the database
// if a product with the specified code doesn't exist, display an error message
printProduct(p);
System.out.println();
}
// use this method to print a Product object on a single line
private static void printProduct(Product p)
{
String productString =
StringUtils.padWithSpaces(p.getCode(), 8) +
StringUtils.padWithSpaces(p.getDescription(), 44) +
p.getFormattedPrice();
System.out.println(productString);
}
}
This sequence of code will produce an NPE as Product phas not been instantiated:
Product p = null;
System.out.println("First product:");
printProduct(p);
private static void printProduct(Product p)
{
String productString =
StringUtils.padWithSpaces(p.getCode(), 8) + // <-- This guy is angry when the 'p' passed to it is null
StringUtils.padWithSpaces(p.getDescription(), 44) +
p.getFormattedPrice();
System.out.println(productString);
}
}
Then
public static void printFirstProduct()
{
Product p = null;
// add code that prints the record for the first product in the Products table
System.out.println("First product:");
printProduct(p); //<--- This 'p' is null when you pass it to it because you never assgin it after setting it to null.
System.out.println();
}
You are passing null here
public static void printFirstProduct()
{
Product p = null;
// add code that prints the record for the first product in the Products table
System.out.println("First product:");
printProduct(p);
System.out.println();
}
Another possible weakness:
connection = MurachDB.getConnection();
if (connection != null)
System.out.println("Derby has been started.\n");
If connection is null the code goes ahead anyway and later tries to invoke methods on null.
I'm not saying that it causes your problems now but definitely could at some point.