Apply static method requirements on class (Static interface methods)?
I have a set of classes where is class is identified with a unique ID number. So each class has a public static int getId() method. Each class also has either a constructor that takes a byte array or a static factory method that takes a byte array.
I would like to maintain a hashmap of these classes keyed to the ID's however I am not sure how to have some interface of abstract parent class that requires each of these classes to implement these static methods.
What I was hoping to do was something like this>>>
public interface MyClasses{
static MyClasses createInstance(byte[] data);
HashMap<Integer, MyClasses> map;
public void init() {
map = new HashMap<Integer, MyClasses>();
map.put(Class1.getId(), Class1.class);
map.put(Class2.getId(), Class2.class);
public void createInstance (int id, byte[] data) {
map.get(id).createInstance(data);
}Is there some way I could do this?
What about something like this?
public interface Initializable
public void initialize(byte[] data);
public class Factory
private final Map<Integer, Initializable> map = new HashMap<Integer, Initializable>();
public void registerClass(int id, Class klass)
if (! Initializable.class.isAssignableFrom(klass))
// you may also want to ensure the class declares a parameterless constructor
throw new IllegalArgumentException("duff class");
if (this.map.keySet().contains(id))
throw new IllegalArgumentException("duff id");
this.map.put(id, klass);
public Initializable createInstance(int id, byte[] data)
// need some exception handling of course
Initializable i = map.get(id).newInstance();
i.initialize(data);
return i;
}
Similar Messages
-
Why a static class can implements a non-static interface?
public class Test {
interface II {
public void foo();
static class Impl implements II {
public void foo() {
System.out.println("foo");
}Why a static class can implements a non-static interface?
In my mind, static members cann't "use" non-static members.Why a static class can implements a
non-static interface?There's no such thing as a non-static member interface. They are always static even if you don't declare them as such.
An interface defines, well, a public interface to be implemented. It doesn't matter whether it is implemented by a static nested class or by an inner class (or by any class at all). It wouldn't make sense to enforce that it should be one or the other, since the difference between a static and non-static class is surely an irrelevant detail to the client code of the interface.
In my mind, static members cann't "use" non-static
members.
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#246026
Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier. -
Using static interface inner class.. how?
Can anyone tell me how I'm able to use an inner class that is a static interface?
Specifically I'm getting DocumentEvents through a DocumentListener..
Then within DocumentEvents there is an inner class which is a static interface called:
DocumentEvent.ElementChange, I'm trying to use the methods contained within the interface ElementChange.
Can anyone throw a helping hand as to how I go about this?
Thanks :)public class A ... {
public static interface B {
}Just creates a public interface called A.B
How are you supposed to use this with your DocumentEvent? I can't say -
Static interface Vs Static nested interface declaration
Hi,
I have observed that static interface declaration is not allowed in Java. However static nested interface declaration is allowed.
I could not understood reason behind this behavior.
e.g.
interface A{
void AA();
public static abstract interface Aa{
} ........... this is allowed in Java.
static interface d{
} ...... This is not allowed in Java...
I already know that static mean one for class and interface has only abstract method.
Please let me know if any one know resign behind this.
Thanks .Why don't you go to a Java forum?
-
Abstract class and interface having same method
Hello,
Here is my problem. Suppose we have one abstarct class and one interface.Here is code-
//Abstarct class
abstract class X{
abstract void myMethod();
//Interface
public interface Y{
abstract void myMethod(){}
Now i have a class which extends both abstarct class X and interface Y.
If i call myMethod() from this class. Whose myMethod would be called.Will it be of abstract class or interface?
Many ThanksHello,
Here is my problem. Suppose we have one abstarct class
and one interface.Here is code-
//Abstarct class
abstract class X{
abstract void myMethod();
}OK, so far...
//Interface
public interface Y{
abstract void myMethod(){}
}An interface cannot have code (the {} part), so this won't work.
Lets pretend though, it read
//Interface
public interface Y{
abstract void myMethod();
However, the abstract class above can have code;
If you extended X and implemented Y (with no code in it), you would have to have a myMethod() implementation in your code. That's the one that would run.
Now, let's pretend the abstract class above did have code in it.
//Abstract class
abstract class X {
abstract void myMethod() { System.out.println("Hello"); }
Then, you wouldn't have to have a myMethod() implementation in your class which extends X and implements Y (it's defined in X). If you didn't have one, the method in X would run. If you defined your own myMethod() implementation in your class (which extends X and implements Y), then your own implementation would run. -
Hi everybody,
I could not find eny information about static interfaces (not static members of an interfaces - static interfaces itself).
Could anybody give me some information about it ?
I came accross with many interfaces wich are declared as:
public static interface name_of_interface
Thank you for all the answers.
AdrianInner interfaces can be declared static.Well, there you go. I should Google myself before answering!
Never thought of inner interfaces.
Cheers! -
I am very new to java and need to do an assignment for my course. I am trying to get a connection to a database and retrieve information but I get the below error when I try to compile my program - any ideas?
D:\javawork\Bike.java:16: 'class' or 'interface' expected
public Bike()
^
Here is the actual code:
//Bike Class
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
public class Bike extends JFrame
private Connection Database;
private JTable table;
public Bike()
// Use JDBC to connect to a Microsoft ODBC source
String url = "jdbc:odbc:Mikesdb";
String username = "guest";
String password = "guest";
Statement DataRequest;
ResultSet Results;
//Load the driver to allow connection to the database
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Database = DriverManager.getConnection(url);
System.out.println("Successful Connection" + Database);
catch(ClassNotFoundException cnferr)
System.err.println("Failed to load JDBC/ODBC bridge" + cnferr);
System.exit(1); //exit program
catch(SQLException sqlex)
System.err.println("Unable to connect to the database" + sqlex);
System.exit(2); //exit program
FindBike();
setSize(200,200);
show();
public void FindBike(String type, String gender, String status)
String t = type;
String g = gender;
String s = status;
this.getConnection();
Statement DataRequest;
ResultSet Results;
try
//get user input for three fields in future
String query = "Select * FROM Bike WHERE Status = 'Ready'";
DataRequest = Database.createStatement();
Results = DataRequest.executeQuery (query);
displayResults (Results);
DataRequest.close();
catch(SQLException err)
System.out.println("SQL Error: " + err);
System.exit(3);
public void Disconnect()
try
Database.close();
catch(SQLException err)
System.out.println("Cannot close database connection: " + err);
System.exit(4);
public static void main(String[] arguments) {
Bike b = new Bike();
b.show();
Having moved the { to the end I get lots of new errors!
D:\javawork\Bike.java:49: FindBike(java.lang.String,java.lang.String,java.lang.String) in Bike cannot be applied to ()
FindBike();
^
D:\javawork\Bike.java:60: cannot resolve symbol
symbol : method getConnection ()
location: class Bike
this.getConnection();
^
D:\javawork\Bike.java:71: cannot resolve symbol
symbol : method DisplayResults (java.sql.ResultSet)
location: class Bike
DisplayResults (Results);
^
3 errors
Finished -
How to fix 'class' or 'interface' expected for jsp
below is the stack trace
org.apache.jasper.JasperException: Unable to compile class for JSP
Generated servlet error:
/home/sherali/.netbeans/5.5/apache-tomcat-5.5.17_base/work/Catalina/localhost/UVSDataSearch/org/apache/jsp/pager_002ddemo_jsp.java:7: 'class' or 'interface' expected
import java.util.*;
^
Generated servlet error:
/home/sherali/.netbeans/5.5/apache-tomcat-5.5.17_base/work/Catalina/localhost/UVSDataSearch/org/apache/jsp/pager_002ddemo_jsp.java:8: 'class' or 'interface' expected
import java.io.*;
^
2 errors
thanks a lot in advance.
my jsp is
<%@ page session="false" %>
<%@ page import="tauvex.*;" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>
<html>
<head>
<title>Tauvex Search Results</title>
<%
* Pager Tag Library
* Copyright (C) 2002 James Klicman <[email protected]>
* The latest release of this tag library can be found at
* http://jsptags.com/tags/navigation/pager/
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%>
<style type="text/css">
A.nodec { text-decoration: none; }
</style>
</head>
<body bgcolor="#ffffff">
<%
String style = getParam(request, "style", "simple");
String position = getParam(request, "position", "top");
String index = getParam(request, "index", "center");
int maxPageItems = getParam(request, "maxPageItems", 3);
int maxIndexPages = getParam(request, "maxIndexPages", 3);
%>
<%
String query1=(String)request.getAttribute("query1");
String query=(String)request.getAttribute("query");
String ShowFile=(String)request.getAttribute("ShowFile");
String ShowRA=(String)request.getAttribute("ShowRA");
String ShowDEC=(String)request.getAttribute("ShowDEC");
String Telescope=(String)request.getAttribute("Telescope");
String ObservationDates=(String)request.getAttribute("ObservationDates");
String Filter=(String)request.getAttribute("Filter");
String RA=(String)request.getAttribute("RA");
String DEC=(String)request.getAttribute("DEC");
String DATE=(String)request.getAttribute("DATE");
String DATE1=(String)request.getAttribute("DATE1");
String Radious=(String)request.getAttribute("Radious");
String FILTER[]=(String[])request.getAttribute("FILTER");
String OrderBy1=(String)request.getAttribute("OrderBy1");
String OrderBy2=(String)request.getAttribute("OrderBy2");
String OrderBy3=(String)request.getAttribute("OrderBy3");
%>
<%
out.println("<form action=\"PlainSQLQuery\" method=POST>");
out.println("<textarea rows = 5 cols = 40 name=query id=\"query\">");
out.println(query);
out.println("</textarea>");
out.println("<input type = submit value = \"Submit\">");
out.println("<input type = reset value = \"Reset\">");
out.println("</form>");
%>
<center>
<table border="0" width="90%" cellpadding="4">
<tr>
<td colspan="2" align="left" valign="top">
<table border="0" cellspacing="2" cellpadding="0">
<tr><td>Max. Page Items </td>
<td><input type="text" size="4" name="maxPageItems" value="<%= maxPageItems %>" onChange="this.form.submit();"></td></tr>
<tr><td>Max. Index Pages </td>
<td><input type="text" size="4" name="maxIndexPages" value="<%= maxIndexPages %>" onChange="this.form.submit();"></td></tr>
</table>
</td>
</tr>
</table>
<pg:pager
index="<%= index %>"
maxPageItems="<%= maxPageItems %>"
maxIndexPages="<%= maxIndexPages %>"
url="TauvexDataServlet"
export="offset,currentPageNumber=pageNumber"
scope="request">
<%-- keep track of preference --%>
<pg:param name="style"/>
<pg:param name="position"/>
<pg:param name="index"/>
<pg:param name="maxPageItems"/>
<pg:param name="maxIndexPages"/>
<pg:param name="RA"/>
<pg:param name="DEC"/>
<pg:param name="DATE"/>
<pg:param name="DATE1"/>
<pg:param name="Radious"/>
<pg:param name="FILTER"/>
<pg:param name="ShowRA"/>
<pg:param name="ShowDEC"/>
<pg:param name="Telescope"/>
<pg:param name="ObservationDates"/>
<pg:param name="Filter"/>
<pg:param name="OrderBy1"/>
<pg:param name="OrderBy2"/>
<pg:param name="OrderBy3"/>
<%-- save pager offset during form changes --%>
<input type="hidden" name="pager.offset" value="<%= offset %>">
<%-- warn if offset is not a multiple of maxPageItems --%>
<% if (offset.intValue() % maxPageItems != 0 &&
("alltheweb".equals(style) || "lycos".equals(style)) )
%>
<p>Warning: The current page offset is not a multiple of Max. Page Items.
<br>Please
<pg:first><a href="<%= pageUrl %>">return to the first page</a></pg:first>
if any displayed range numbers appear incorrect.</p>
<% } %>
<%-- the pg:pager items attribute must be set to the total number of
items for index before items to work properly --%>
<% if ("top".equals(position) || "both".equals(position)) { %>
<br>
<pg:index>
<% if ("texticon".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/>
<% } else if ("jsptags".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/jsptags.jsp" flush="true"/>
<% } else if ("google".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/google.jsp" flush="true"/>
<% } else if ("altavista".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/altavista.jsp" flush="true"/>
<% } else if ("lycos".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/lycos.jsp" flush="true"/>
<% } else if ("yahoo".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/yahoo.jsp" flush="true"/>
<% } else if ("alltheweb".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/alltheweb.jsp" flush="true"/>
<% } else { %>
<jsp:include page="/WEB-INF/jsp/simple.jsp" flush="true"/>
<% } %>
</pg:index>
<% } %>
<hr>
<form action="ZipServlet" method="get" name="download" onsubmit="return Form1_Validator(this)">
<table id="output">
<CAPTION><EM>Fits file Search Results</EM></CAPTION><tr>
<%
out.println("<th>Check Box</th>");
out.println("<th>File Name</th>");
if(ShowRA != null && "on".equals(ShowRA))
out.println("<th>RA_START</th>");
if(ShowRA != null && "on".equals(ShowRA))
out.println("<th>RA_END</th>");
if(ShowDEC != null && "on".equals(ShowDEC))
out.println("<th>DEC_START</th>");
if(ShowDEC != null && "on".equals(ShowDEC))
out.println("<th>DEC_END</th>");
if(Telescope!=null && "on".equals(Telescope))
out.println("<th>Telescope</th>");
if(ObservationDates !=null && "on".equals(ObservationDates))
out.println("<th>STARTOBS</th>");
if(ObservationDates !=null && "on".equals(ObservationDates))
out.println("<th>ENDOBS</th>");
if(Filter!=null && "on".equals(Filter))
out.println("<th>FILTER</th>");
out.println("</tr>");
%>
<%--
<table width="90%" cellspacing="4" cellpadding="4">
Since the data source is static, it's easy to offset and limit the
loop for efficiency. If the data set size is not known or cannot
be easily offset, the pager tag library can count the items and display
the correct subset for you.
The following is an example using an enumeration data source of
unknown size. The pg:pager items and isOffset attributes must
not be set for this example:
--%>
<%
Enumeration myDataList1 = (Enumeration)request.getAttribute("myDataList1");
if (myDataList1 == null)
throw new RuntimeException("myDataList1 is null");
%>
<% while (myDataList1.hasMoreElements()) { %>
<% TauvexData elem = (TauvexData)myDataList1.nextElement(); %>
<pg:item> <%
out.println("<tr>");
%>
<td><input type= "checkbox" name="cb" value="<%=elem.getDownload()%>"></td>
<td><a href="<%= elem.getDownload() %>"><%= elem.Fitsfilename %></a></td>
<%
// out.println("<td> "+elem.Fitsfilename+" </td>");
if(ShowRA != null && "on".equals(ShowRA))
out.println("<td> "+elem.RA_START+" </td>");
if(ShowRA != null && "on".equals(ShowRA))
out.println("<td> "+elem.RA_END+"</td>");
if(ShowDEC != null && "on".equals(ShowDEC))
out.println("<td> "+elem.DEC_START+" </td>");
if(ShowDEC != null && "on".equals(ShowDEC))
out.println("<td> "+elem.DEC_END+" </td>");
if(Telescope!=null && "on".equals(Telescope))
out.println("<td> "+elem.telescope+" </td>");
if(ObservationDates !=null && "on".equals(ObservationDates))
out.println("<td> "+elem.STARTOBS+" </td>");
if(ObservationDates !=null && "on".equals(ObservationDates))
out.println(" <td> "+elem.ENDOBS+" </td>");
if(Filter!=null && "on".equals(Filter))
out.println("<td> "+elem.FILTER+" </td>");
out.println("</tr>");
%> </pg:item>
<% } %>
</table>
<input type="button" name="CheckAll" value="Check All Boxes" onclick="modify_boxes(true,3)">
<input type="button" name="UnCheckAll" value="UnCheck All Boxes" onclick="modify_boxes(false,3)">
<input type="submit" value="Download">
</form>
<hr>
<pg:pages>
<a href="<%= pageUrl %>"><%= pageNumber %></a>
</pg:pages>
<pg:last>
<a href="<%= pageUrl %>">[ Last >| (<%= pageNumber %>) ]</a>
</pg:last>
<% if ("bottom".equals(position) || "both".equals(position)) { %>
<pg:index>
<% if ("texticon".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/>
<% } else if ("jsptags".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/jsptags.jsp" flush="true"/>
<% } else if ("google".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/google.jsp" flush="true"/>
<% } else if ("altavista".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/altavista.jsp" flush="true"/>
<% } else if ("lycos".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/lycos.jsp" flush="true"/>
<% } else if ("yahoo".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/yahoo.jsp" flush="true"/>
<% } else if ("alltheweb".equals(style)) { %>
<jsp:include page="/WEB-INF/jsp/alltheweb.jsp" flush="true"/>
<% } else { %>
<jsp:include page="/WEB-INF/jsp/simple.jsp" flush="true"/>
<% } %>
</pg:index>
<% } %>
</pg:pager>
</center>
</body>
</html>
<%!
private static int num =1;
private static String getName(){
String str="cb";
str=str+num;
num++;
return str ;
private static final String getParam(ServletRequest request, String name,
String defval)
String param = request.getParameter(name);
return (param != null ? param : defval);
private static final int getParam(ServletRequest request, String name,
int defval)
String param = request.getParameter(name);
int value = defval;
if (param != null) {
try { value = Integer.parseInt(param); }
catch (NumberFormatException ignore) { }
return value;
private static void radio(PageContext pc, String name, String value,
boolean isDefault) throws java.io.IOException
JspWriter out = pc.getOut();
String param = pc.getRequest().getParameter(name);
out.write("<input type=\"radio\" name=\"");
out.write(name);
out.write("\" value=\"");
out.write(value);
out.write("\" onChange=\"this.form.submit();\"");
if (value.equals(param) || (isDefault && param == null))
out.write(" checked");
out.write('>');
%>Well, putting all that Java code into a JSP was a bad idea in the first place, just on general design principles. But you've done it in such a way that the result of compiling the JSP is malformed Java code. Frankly I would just throw it away and put the Java code into a servlet or some other Java class, where it belongs.
But if you're really working in a place where nobody has learned anything since 2003, and you're forced to support that old junk, then I would point out that the error occurs before the place which generates this line:
import java.util.*;You only need to look at two of the thousand lines of code you posted. -
Hi,
I have to buid a report in ECM with complete details of the engineering as well as production. This include workflow as well as various fucntionality depends upon the criterion and user's event.
I am implementating in OOPS and I Want to know that when I should use the Abstract class and when interface ?
Because as per me both serve the same purpose. Kindly send me the exact difference so that i can efficiently use the same.
Thanks
PrinceWhen inheriting A Interface We have to inherit all the methods of the Interface there's no other option whereas with abstract classes we can inherit the members that we are in need of.
Just the interface has to have body of the method and the method is to be used by the classes inheriting it. Whereas in the case of Abstract Class it can have declarations (Other than the abstract method) and it can be further extended in the classes inheriting the Abstract Class.
Interface contains all abstract methods,all methods compulsory implemented by particular class, interface does not contain Constructor
abstract classes are designed with implemantion gaps for sub-class to fill in.
interfaces are sintacticlly similar to classes but they lack insance variables & methods.
abstract classes can also have both abstract methods & non-abstract methods. where as in interface methods are abstract only, & variables are implicitly static&final
regards
Preetesh -
Urgent: 'Class' or 'interface' expected
Hello,
I am working on a piece of work which has to be in for tomorrow, i have been trying to compile it for so,me time now and everytime i try it says 'Class' or 'interface' expected.
I have not finished writing the program and i am not sure how correct it is. Any help would be much appreciated,
Thank you,
James
Error Message: -
U:\ManXP\My Documents\myjava>javac emailclient2.java
emailclient2.java:181: 'class' or 'interface' expected
private static int readListFromFile(String filename, Message[]
^
messageList, int maxLines)
1 errorI am working on a piece of work which has to be in
for tomorrow, i have been trying to compile it for
so,me time now and everytime That's quite a bit of superfluous information. Please don't mark your questions as urgent. Thanks!
i try it says 'Class' or 'interface' expected.You've got a syntax error in your code on line 181. Look at the lines before that. Are you trying to declare that method inside another method?
Careful adherence to standard Code Conventions for the Java� Programming Language can make this type of problem very easy to spot... -
ERROR: class' or 'interface' expected
Hello, I'm new to Java. I'm having trouble figuring out this 1 error in my code. Need Help Plzzzzzz....
java:81: 'class' or 'interface' expected
public void actionPerformed(ActionEvent e)
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
public class Checkerboard extends Frame implements ActionListener
//declare variables
int start, stop, step;
Panel boardPanel = new Panel();
TextArea boardDisplay [] = new TextArea[16];
Panel buttonPanel = new Panel();
Button goButton = new Button ("Go");
Button clearButton = new Button("Clear");
Panel inputPanel = new Panel();
Label startLabel = new Label ("Start");
TextField startField = new TextField();
Label stopLabel = new Label ("Stop");
TextField stopField = new TextField();
Label stepLabel = new Label ("Step");
TextField stepField = new TextField();
public Checkerboard()
this.setLayout(new BorderLayout());
boardPanel.setLayout(new GridLayout (4, 4, 2, 3));
inputPanel.setLayout(new FlowLayout());
buttonPanel.setLayout(new FlowLayout());
for (int i=0; i<16; i++)
boardDisplay = new TextArea(null,3,5,3);
if (i<16)
boardDisplay[i].getText();
else
boardDisplay[i].setEditable(false);
boardDisplay[i].setBackground(Color.white);
boardPanel.add(boardDisplay[i]);
//add components to the button
buttonPanel.add(goButton);
//add components to input panel
inputPanel.add(startField);
inputPanel.add(stopField);
inputPanel.add(stepField);
inputPanel.add(startLabel);
inputPanel.add(stopLabel);
inputPanel.add(stepLabel);
//add panels to frame
add(buttonPanel, BorderLayout.SOUTH);
add(inputPanel, BorderLayout.CENTER);
add(boardPanel, BorderLayout.NORTH);
goButton.addActionListener(this);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
}//end Checkerboard frame
public void actionPerformed(ActionEvent e)
String arg = e.getActionCommand();
try
if (arg == "GO")
start=Integer.parseInt(startTF.getText());
stop=Integer.parseInt(stopTF.getText());
step=Integer.parseInt(stepTF.getText());
for(int i=0;<textArray.length;i++)
textArray[i].setBackground(Color.blue);
for(int i=start;<textArray.length;i+=step)
textArray[i].setBackground(Color.yellow);
catch(Exception x)
JOptionPane.showMessageDialog(null,"Data Entry Error","Error",JOptionPane.INFORMATION_MESSAGE);
arg = "Clear")
startTF.setText("");
stopTF.setText("");
stepTF.setText("");
for(int i=0;<textArray.length;i++)
textArray[i].setBackground(Color.white);
}//end actionPerformed
public static void main(String[]args)
Checkerboard f = new Checkerboard();
f.setBounds(50,100,300,300);
f.setTitle("Checkerboard Array");
f.setVisible(true);
}//end main method
}//end Checkerboard classimport javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
public class Checkerboard extends Frame implements ActionListener
//declare variables
int start, stop, step;
Panel boardPanel = new Panel();
TextArea boardDisplay [] = new TextArea[16];
Panel buttonPanel = new Panel();
Button goButton = new Button ("Go");
Button clearButton = new Button("Clear");
Panel inputPanel = new Panel();
Label startLabel = new Label ("Start");
TextField startField = new TextField();
Label stopLabel = new Label ("Stop");
TextField stopField = new TextField();
Label stepLabel = new Label ("Step");
TextField stepField = new TextField();
public Checkerboard()
this.setLayout(new BorderLayout());
boardPanel.setLayout(new GridLayout (4, 4, 2, 3));
inputPanel.setLayout(new FlowLayout());
buttonPanel.setLayout(new FlowLayout());
for (int i=0; i<16; i++)
boardDisplay = new TextArea(null,3,5,3);
if (i<16)
boardDisplay[i].getText();
else
boardDisplay[i].setEditable(false);
boardDisplay[i].setBackground(Color.white);
boardPanel.add(boardDisplay[i]);
//add components to the button
buttonPanel.add(goButton);
//add components to input panel
inputPanel.add(startField);
inputPanel.add(stopField);
inputPanel.add(stepField);
inputPanel.add(startLabel);
inputPanel.add(stopLabel);
inputPanel.add(stepLabel);
//add panels to frame
add(buttonPanel, BorderLayout.SOUTH);
add(inputPanel, BorderLayout.CENTER);
add(boardPanel, BorderLayout.NORTH);
goButton.addActionListener(this);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
}//end Checkerboard frame
public void actionPerformed(ActionEvent e)
String arg = e.getActionCommand();
try
if (arg == "GO")
start=Integer.parseInt(startTF.getText());
stop=Integer.parseInt(stopTF.getText());
step=Integer.parseInt(stepTF.getText());
for(int i=0;<textArray.length;i++)
textArray[i].setBackground(Color.blue);
for(int i=start;<textArray.length;i+=step)
textArray[i].setBackground(Color.yellow);
catch(Exception x)
JOptionPane.showMessageDialog(null,"Data Entry Error","Error",JOptionPane.INFORMATION_MESSAGE);
arg = "Clear")
startTF.setText("");
stopTF.setText("");
stepTF.setText("");
for(int i=0;<textArray.length;i++)
textArray[i].setBackground(Color.white);
}//end actionPerformed
public static void main(String[]args)
Checkerboard f = new Checkerboard();
f.setBounds(50,100,300,300);
f.setTitle("Checkerboard Array");
f.setVisible(true);
}//end main method
}//end Checkerboard class -
'class' or 'interface' expected, advice please!
Hi! I have problems running a program. it is supposed to 1) open a file 2) find word 1-3, 2-4, 3-5 a.s.o. 3) write the wordstrings it found in a system.out.println. In the former version, I only had private static void and got this: Exception in thread "main" java.lang.NoSuchMethodError: main when i ran it. I was adviced to add public static void but now it says: 'class' or 'interface' expected, does someone know why this is?
this is what the code looks like:
import java.io.*;
import java.io.*;
import java.util.*; //tillagd f�r att removeFirst4 skall funka
import javax.swing.*; //tillagd f�r att removeFirst4 skall fungera
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.lang.*;
import javax.swing.*;
public static void main(String[] foo) {
public class AttLaesaEnFil2 {
private static void main(String name, BufferedReader in) throws
IOException {
String a;
WordExtractor b;
String c = " ";
String d;
WordExtractor e;
String f;
String g;
WordExtractor h;
String i;
String j;
String k;
String l;
String line;
do {
line = in.readLine();
if (line != null)
b = new WordExtractor(line);
c = b.getFirst();
d = b.getRest();
e = new WordExtractor(d);
f = e.getFirst();
g = e.getRest();
h = new WordExtractor(g);
i = h.getFirst();
j = h.getRest();
k = c + f + i;
l = c + " " + f + " " + i;
System.out.println("The first three words are: " + l);
a = b.getRest();
while (line != null);
System.out.println("Klart!");
private static void main(String fileName) {
BufferedReader in = null;
try {
FileReader fileReader = new FileReader(fileName);
in = new BufferedReader(fileReader);
main(fileName, in);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
private static void main(String streamName, InputStream input) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(inputStreamReader);
main(streamName, in);
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
i tried to add public static void before each private but with the same result.
Thank you in advanceThis wins the award for Funniest Code Snippet of the
Day. Four main methods, with a class nested inside
the first main method.Hey! stop mocking me, i'm doing my best!
this is the code i'm learning this from, it also includes four methods (not main though, maybe that's the pr.) but works fine but mine still won't:
import java.io.*;
* Command line program to count lines, words and characters
* in files or from standard input, similar to the wc
* utility.
* Run like that: java WordCount FILE1 FILE2 ... or
* like that: java WordCount < FILENAME.
* @author Marco Schmidt
public class WordCount {
* Count lines, words and characters in given input stream
* and print stream name and those numbers to standard output.
* @param name name of input source
* @param input stream to be processed
* @throws IOException if there were I/O errors
private static void count(String name, BufferedReader in) throws
IOException {
long numLines = 0;
long numWords = 0;
long numChars = 0;
String line;
do {
line = in.readLine();
if (line != null)
numLines++;
numChars += line.length();
numWords += countWords(line);
while (line != null);
System.out.println(name + "\t" + numLines + "\t" +
numWords + "\t" + numChars);
* Open file, count its words, lines and characters
* and print them to standard output.
* @param fileName name of file to be processed
private static void count(String fileName) {
BufferedReader in = null;
try {
FileReader fileReader = new FileReader(fileName);
in = new BufferedReader(fileReader);
count(fileName, in);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
* Count words, lines and characters of given input stream
* and print them to standard output.
* @param streamName name of input stream (to print it to stdout)
* @param input InputStream to read from
private static void count(String streamName, InputStream input) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(inputStreamReader);
count(streamName, in);
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
* Determine the number of words in the argument line.
* @param line String to be examined, must be non-null
* @return number of words, 0 or higher
private static long countWords(String line) {
long numWords = 0;
int index = 0;
boolean prevWhitespace = true;
while (index < line.length()) {
char c = line.charAt(index++);
boolean currWhitespace = Character.isWhitespace(c);
if (prevWhitespace && !currWhitespace) {
numWords++;
prevWhitespace = currWhitespace;
return numWords;
public static void main(String[] args) {
if (args.length == 0) {
count("stdin", System.in);
} else {
for (int i = 0; i < args.length; i++) {
count(args); -
Class or interface expected in Javabeans
Hi Netbeans Guru,
I have run out of ideas when trying to run the Juggler example below from Chapter 22: JavaBeans, Learning Java published by Oreilly in
Netbeans 5.0, Windows XP:
* LearningJava1.java
* Created on 3 August 2006, 02:59
* @author abc
import javax.swing.*
public class LearningJava1 extends javax.swing.JFrame {
/** Creates new form LearningJava1 */
public LearningJava1() {
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
juggler1 = new magicbeans.sunw.demo.juggler.Juggler();
jButton1 = new javax.swing.JButton();
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
juggler1.setAnimationRate(500);
org.jdesktop.layout.GroupLayout juggler1Layout = new org.jdesktop.layout.GroupLayout(juggler1);
juggler1.setLayout(juggler1Layout);
juggler1Layout.setHorizontalGroup(
juggler1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 144, Short.MAX_VALUE)
juggler1Layout.setVerticalGroup(
juggler1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 125, Short.MAX_VALUE)
getContentPane().add(juggler1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 70, -1, -1));
jButton1.setText("Start");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 220, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
juggler1.setJuggling(true);
}//GEN-LAST:event_jButton1ActionPerformed
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LearningJava1().setVisible(true);
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private magicbeans.sunw.demo.juggler.Juggler juggler1;
// End of variables declaration//GEN-END:variables
This program failed to compiled with the message "Class or interface expected" when declaring the JavaLearning1 constructor (line 17) and the private juggler1 variable (last line of code). It is not possible to see the code within initComponents methods in Netbeans Source Workspace. Is it possible that this is due to CLASSPATH not set correctly?
I am new to JavaBeans and would appreciate any guidances.
Many Thanks,
Netbeans FanHi itchyscratchy,
Thanks for pointing the missing semi colon out but it was just a copy & paste error. The import statement does have the semi colon in it. Nevertheless, below is the output when compiling from Netbeans:
init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\abc\Java Tutorial\build\classes
C:\Documents and Settings\abc\Java Tutorial\src\LearningJava1.java:17: 'class' or 'interface' expected
public LearningJava1() {
C:\Documents and Settings\abc\Java Tutorial\src\LearningJava1.java:76: 'class' or 'interface' expected
private magicbeans.sunw.demo.juggler.Juggler juggler1;
C:\Documents and Settings\abc\Java Tutorial\src\LearningJava1.java:79: 'class' or 'interface' expected
C:\Documents and Settings\abc\Java Tutorial\src\LearningJava1.java:80: 'class' or 'interface' expected
4 errors
BUILD FAILED (total time: 1 second)
Thanks,
Netbeans Fan -
'class' or 'interface' expected" on Connection class in java.sql.*
I am currently getting an exception "Main.java:20: 'class' or 'interface' expected". I had the database connection working, but then I tried to add something else and I feel like I might have changed something. I am wondering if there is a problem importing the java.sql. library; since that is where the Connection class is located. Thanks for your feedback.
package javaaaplication2;
import java.sql.*;
public class Main {
/** Creates a new instance of Main */
public Main() {
public static void main(String[] args) {
Connection con = getConnection();
System.out.println("The connection is: " +con );
private static Connection getConnection()
Connection con = null;
try
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/patients";
String user = "root";
String pw = "qwerty";
con = DriverManager.getConnection(url, user, pw);
catch (ClassNotFoundException e)
System.out.print(e.getMessage());
System.exit(0);
catch (SQLException e)
System.out.print(e.getMessage());
System.exit(0);
return con;
}You closed your Main class with a bracket, so your getConnection() method isn't in a class
public class Main {
/** Creates a new instance of Main */
public Main() {
public static void main(String[] args) {
Connection con = getConnection();
System.out.println("The connection is: " +con );
}That is your entire Main class. Anything below it isn't in the class. -
Unable to resolve 'class' or 'interface' expected compile error
Any help would be appreciated - I can't resolve the following compile errors:
E:\j2sdk1.4.0\bin\RandomApp3\src\RandomApp3.java:85: 'class' or 'interface' expected private void initComponents() {
E:\j2sdk1.4.0\bin\RandomApp3\src\RandomApp3.java:97: 'class' or 'interface' expected }
E:\j2sdk1.4.0\bin\RandomApp3\src\RandomApp3.java:97: 'class' or 'interface' expected }
3 errors
here is the source:
import javax.swing.JOptionPane;
import java.applet.Applet;
import java.awt.Graphics;
import java.util.Random;
public class RandomApp3 extends javax.swing.JApplet {
public RandomApp3() {
public static void main(String args[]) {
/** Creates a new instance of RandomApp3 */
public class RandInt {
private Random randNum;
//constructor for RandInt class
public RandInt(int endInt) {
int randNum;
int range;
int[] lottery = new int[5];
for (int x = 0; x <=49; x++) {
range = (int) (Math.floor(Math.random()*5 + 1));
lottery[range]++;
/** Initializes the applet RandomApp3 */
public void initComponents() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
} catch (Exception ex) {
ex.printStackTrace();
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
panell = new java.awt.Panel();
getContentPane().add(panell, java.awt.BorderLayout.CENTER);
// </editor-fold>
// Variables declaration - do not modify
private java.awt.Panel panel1;
// End of variables declaration
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
panel1 = new java.awt.Panel();
getContentPane().add(panel1, java.awt.BorderLayout.CENTER);
// </editor-fold>
// Variables declaration - do not modify
private java.awt.Panel panel1;
// End of variables declaration
}Re-posted with code tags. This may show that there is an extra } just before initComponents()
public class RandomApp3 extends javax.swing.JApplet {
public RandomApp3() {
public static void main(String args[]) {
/** Creates a new instance of RandomApp3 */
public class RandInt {
private Random randNum;
//constructor for RandInt class
public RandInt(int endInt) {
int randNum;
int range;
int[] lottery = new int[5];
for (int x = 0; x <=49; x++) {
range = (int) (Math.floor(Math.random()*5 + 1));
lottery[range]++;
/** Initializes the applet RandomApp3 */
public void initComponents() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
} catch (Exception ex) {
ex.printStackTrace();
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
panell = new java.awt.Panel();
getContentPane().add(panell, java.awt.BorderLayout.CENTER);
// </editor-fold>
// Variables declaration - do not modify
private java.awt.Panel panel1;
// End of variables declaration
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
panel1 = new java.awt.Panel();
getContentPane().add(panel1, java.awt.BorderLayout.CENTER);
// </editor-fold>
// Variables declaration - do not modify
private java.awt.Panel panel1;
// End of variables declaration
} -
Question about Classes, Abstract Classes and Interfaces.
I have been experimenting with Classes, Abstract Classes and Interfaces and wonder if anyone can explain this to me.
I was looking for a way to assign a value to a variable and then keep it fixed for the session and have devised this.
First I create an abstract class like this:
public abstract class DatabaseConnection {
private static String ServerName = null;
public static void setServerName(String serverName) {
ServerName = serverName;
public static String getServerName() {
return ServerName;
}and then I created an interface
public interface DatabaseAccess {
String servername = DatabaseConnection.getServerName();
}And finally the class itself with some test lines in it so I could see what was going on:
public class CreateDatabase extends DatabaseConnection implements DatabaseAccess {
public static void main (String args[]){
new CreateDatabase();
public CreateDatabase(){
setServerName("Server Name 1");
System.out.println ("Before update ");
System.out.println ("ServerName from Interface = " + servername);
System.out.println ("ServerName from Abstract Class = " + getServerName());
System.out.println ("After update ");
setServerName("Server Name 2");
System.out.println ("ServerName from Interface = " + servername);
System.out.println ("ServerName from Abstract Class = " + getServerName());
System.out.println ("==========================");
}The output I get from the above is:
Before update
ServerName from Interface = Server Name 1
ServerName from Abstract Class = Server Name 1
After update
ServerName from Interface = Server Name 1
ServerName from Abstract Class = Server Name 2
==========================I also tried this in another class which calls the above class to see if I get the same effect
public class CheckDatabaseAccess {
public static void main (String args[]){
new CreateDatabase();
CreateDatabase.setServerName("Server 3");
System.out.println("CreateDatabase "+CreateDatabase.servername);
CreateDatabase.setServerName("Server 4");
System.out.println("CreateDatabase "+CreateDatabase.servername);
CreateDatabase.setServerName("Server 5");
System.out.println("CreateDatabase "+CreateDatabase.servername);
}The output of which is this:
Before update
ServerName from Interface = Server Name 1
ServerName from Abstract Class = Server Name 1
After update
ServerName from Interface = Server Name 1
ServerName from Abstract Class = Server Name 2
==========================
CreateDatabase Server Name 1
CreateDatabase Server Name 1
CreateDatabase Server Name 1Can anyone explain why I appear to only be able to change or set the ServerName only the once?
Is this the correct way to do it? If it is it's exactly what I am looking for, a way to set the value of variable once in a session and then prevent it being changed.
Or is there a better way of doing this.
What I want to use this for is for example, storing the accesses to a database on a server. I won't know what server the database will be stored on nor what the database is called so I create an INI file which stores this information in encrypted format, which is set by the database administrator. It occurs to me I can use this method to then retrieve that data once and once only from the INI file and use that throughout the life of the session to access the database.
Any help appreciated
Regards
JohnNot gonna read all of it, but this jumps out:
public abstract class DatabaseConnection {
private static String ServerName = null;
public interface DatabaseAccess {
String servername = DatabaseConnection.getServerName();
}You have two completely separate variables (with two different names, for that matter, since you were inconsistent in your capitalization, but it wouldn't make a difference if they did have the same name with the same case). And the one in the interface is implicitly public, static, and final.
Anytime you refer to "servername" through a reference of type DatabaseAccess, it refers to the one declared in the interface.
Anytime you refer to "ServerName" inside the DatabaseConnection class, it refers to the one declared in that class.
Maybe you are looking for
-
When I sync my phone it gets to step 6 the does not complete the sync i get a message that says itunes has stopped working and needs to close anyone else have this issue
-
How do I set the default font in Acrobat XI Pro?
I would like to enquire how I can set a default font in Acrobat XI Pro.
-
Release results to snp or r/3
helo sir good morning how r u?? could u plz tell in which format the planning we release to SNP OR R/3??? where the unconstrained demand pland stores in SNP, in which key figure stores the demand plan in snp??? help me out sir.... thanx a lot...waiti
-
Need some more fields displayed in record history of oracle forms
Hi , I am using oracle forms 6.0.8.8.0 . My requirement is to display PROGRAM_ID , PROGRAM_APPLICATION_ID , PROGRAM_UPDATE_DATE , REQUEST_ID in the record history of the forms along with CREATION DATE , CREATED BY , LAST UPDATE DATE , LAST UPDATE LOG
-
Instr function syntax error in MDX quary
Hi all Wen Iam excuting this MDX quary its giving error;syntax error line at 3 ',' SELECT Filter( [PERIOD].Generations(5).Members, InStr( [PERIOD].currentmember.[2010], "Cola" ) >0 ) ON COLUMNS FROM REP.Rep; but wen iam excuting this below example SE