|
Ogunjimi Adewale wrote:
choice=input.nextLine();
<big>for(i=0;i<=12;i++){</big>
System.out.println("*1 When do you feel at your best...");
...
}
You have it in a for loop! And it is repeating itself 13 times.
If at first you don't succeed, you're not Chuck Norris.
|
|
|
|
|
You may be interested in having a look at one of my first ever programs in Java which was a quiz, similar to this, which tallied up someones lifestyle. I have changed a couple of variable names and changed the questions but it is still the same code. Have a read of it to see a more generic approach.
DrPhilQuiz.java
import java.util.ArrayList;
import java.util.Scanner;
public class DrPhilQuiz extends ArrayList<Question> {
private static final long serialVersionUID = 4452314777184430591L;
public DrPhilQuiz()
{
setQuestions();
}
private void setQuestions()
{
this.add(
new Question(
"When do you feel the happiest?",
new AnswerOption("In the morning.", 2),
new AnswerOption("In the afternoon / earliy evening.", 4),
new AnswerOption("Late at night.", 6)
)
);
this.add(
new Question(
"When do you feel the happiest?",
new AnswerOption("In the morning.", 2),
new AnswerOption("In the afternoon.", 2),
new AnswerOption("In the earliy evening.", 2),
new AnswerOption("Late at night.", 2)
)
);
}
public void startQuiz()
{
int count = 1, score = 0;
Scanner input = new Scanner(System.in);
for (Question q : this)
{
System.out.println(count + ") " +q.getQuestion());
System.out.println(q.getAnswers());
while (!q.setAnswer(input.nextLine().charAt(0)))
System.out.println("Invalid choice");
score += q.getScore();
count++;
}
input.close();
System.out.println("\nYou have finished the quiz!");
System.out.println("You Scored " + score);
}
public static void main(String[] args)
{
DrPhilQuiz dpq = new DrPhilQuiz();
dpq.startQuiz();
}
}
Question.java
public class Question {
private String question = "";
private AnswerOption[] answers = null;
private char answer = 'a';
public Question(String q, AnswerOption... a)
{
question = q;
answers = a;
}
public String getQuestion()
{
return question;
}
public String getAnswers()
{
String ret = "";
for (int i = 0; i < answers.length; i++)
ret += (char)(i + 97) + ") " + answers[i].getAnswerOption() + "\n";
return ret;
}
public boolean setAnswer(char a)
{
if(97 <= a && a < (97 + answers.length))
{
answer = a;
return true;
}
return false;
}
public int getScore()
{
return answers[answer - 97].getAnswerOptionValue();
}
}
class AnswerOption
{
private String answer = "";
private int value = 0;
public AnswerOption(String a, int v)
{
answer = a;
value = v;
}
public String getAnswerOption()
{
return answer;
}
public int getAnswerOptionValue()
{
return value;
}
}
Outputs
1) When do you feel the happiest?
a) In the morning.
b) In the afternoon / earliy evening.
c) Late at night.
c
2) When do you feel the happiest?
a) In the morning.
b) In the afternoon.
c) In the earliy evening.
d) Late at night.
a
You have finished the quiz!
You Scored 8
If at first you don't succeed, you're not Chuck Norris.
|
|
|
|
|
THanks a lot Bro, u really made my day...
U must be a real guru at this, more grease to your elbows
i'll get back to u soon but thanks....
If at first you don't succeed, you're not Abraham Lincoln.
|
|
|
|
|
how can i add the facebook bottom toolbar to my project?is there any api for that toolbar?
|
|
|
|
|
This has nothing to do with Java.
Use the CSS attribute 'position' with the value 'fixed'. Then position it using the 'top', 'bottom', 'left', 'right' attributes.
If at first you don't succeed, you're not Chuck Norris.
|
|
|
|
|
Good Day,
i have a problem with j2me programming. i was trying to implement a mp3 player using wireless toolkit, i had this error message. pls can anyone interprete it.
Creating project "player"
Place Java source files in "C:\WTK25\apps\player\src"
Place application resource files in "C:\WTK25\apps\player\res"
Place application library files in "C:\WTK25\apps\player\lib"
Settings updated
Project settings saved
Building "player"
C:\WTK25\apps\player\src\Player.java:91: reached end of file while parsing
}
^
1 error
com.sun.kvem.ktools.ExecutionException
Build failed
Running with storage root DefaultColorPhone
Running with locale: English_United States.1252
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
Execution completed.
3472532 bytecodes executed
1028 thread switches
1647 classes in the system (including system classes)
17853 dynamic objects allocated (537092 bytes)
1 garbage collections (0 bytes collected)
|
|
|
|
|
Hello,
Maybe you didn't finish properly your braces {} then the compiler couldn't complete the parsing of your "Player" class.
Good luck!
|
|
|
|
|
is there anything wrong with this code?
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class FileConnection extends MIDlet implements CommandListener {
private Command exit, start;
private Display display;
private Form form;
public FileConnection ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Write To File");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
try
{
OutputConnection connection = (OutputConnection)
Connector.open("file://c:/myfile.txt;append=true", Connector.WRITE );
OutputStream out = connection.openOutputStream();
PrintStream output = new PrintStream( out );
output.println( "This is a test." );
out.close();
connection.close();
Alert alert = new Alert("Completed", "Data Written", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( ConnectionNotFoundException error )
{
Alert alert = new Alert(
"Error", "Cannot access file.", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( IOException error )
{
Alert alert = new Alert("Error", error.toString(), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
}
}
|
|
|
|
|
Just add an extra } at the end.
|
|
|
|
|
this is the error i have after adding } at the end.
Project "player" loaded
Running with storage root DefaultColorPhone
Running with locale: English_United States.1252
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
|
|
|
|
|
Hi,
Looks like you have an error in your project configuration. Maybe it wants to load a class named "player". But it seems that "player" is the name of your project, not of a class.
If your development tool allows it then generate a sample MIDlet application so you can have a working example to start with.
I'd recommend NetBeans but Eclipse is very good too.
Cheers!!
|
|
|
|
|
Hello,
I am a genuine novice with Java. I have written the following code to accept a passed variable and open a window designed to show an enlarged graphic. It is giving the following error, which seems to indicate that the path is incorrect, however, it is the exact path is used to display the original graphic. Here is the error, followed by the code.
The Error:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /TB_09_Online/~/GearsAds/gears33.png
The Code:
<script type="text/javascript">
function OpenLargeWindow(image)
{
window.open("~/GearsAds/" + image, "", " width=760,height=300,top=200,left=200,scrollbars=0").focus();
}
</script>
<td class="tdr2">
<asp:Image ID="Image13" runat="server" ImageUrl="~/GearsAds/gears33.png" Height="200px" Width="430px" />
<a href="javascript:OpenLargeWindow('gears33.png')">
<asp:Image ID="Image18" runat="server" ImageUrl="~/GearsAds/plus_sign.png" /></a>
</td>
Seems simple enough...I cannot understand why the path is wrong, unless it is a syntax error of some sort. Any Idea's?
Thank You for your help, Pat
|
|
|
|
|
How can i catch the Mozilla firefox closing Event using Java Script,,,
Any one Please help me....
|
|
|
|
|
|
Hi Everybody
i was looking for a solution for a memory problem in big project
the problem is that we have a very large data set that fit entirely in the memory causing OutOfHeapException , even under 8 Gigabyte of memory, so i am looking for a solution that manage the data in the heap and store them in the hard disk in case i will need them again.
thanks
|
|
|
|
|
try dividing your dataset into sub sets
|
|
|
|
|
hi ,
even if divided the data to number of sets it will still have the same problem but anyway i made my homework and i found the number of solutions. first, is force garbage collection but it still got its disadvantage and the last solution and night be the best one is to cache the object according to reference or other staff
|
|
|
|
|
Hi,
I am testing a finger print reader, does any body know how to verify the input of the fingerprint reader, Example: I would let the client touch the reader 4x then i will verfiy if the four inputs are the same.
Thanks,
Eugene
|
|
|
|
|
I guess, you should check the accompayining software with the device whether it contains any Java package. They usually provide C/C++/C# libraries.
Or you should look on the web for any general related package.
Kujtim
|
|
|
|
|
I am making a web browser in java, in that I am using URLConnection object's method getHeaderFieldKey to read cookies while trying to login to any website(say gmail or yahoo mail). When I want to send that cookie to access a secure page (Page, that can be viewed after logging in), I need to send that cookie in this second method setRequestProperty of URLConnection object. But how do I find out, what cookie name the site expects?
The following function reads the cookies.
static Hashtable theCookies = new Hashtable();
public void readCookies(URLConnection urlConn, boolean printCookies, boolean reset)
{
if (reset)
theCookies.clear();
int i=1;
String hdrKey;
String hdrString;
String aCookie;
while ((hdrKey = urlConn.getHeaderFieldKey(i)) != null) {
if (hdrKey.equals("Set-Cookie")) {
hdrString = urlConn.getHeaderField(i);
StringTokenizer st = new StringTokenizer(hdrString,",");
while (st.hasMoreTokens()) {
String s = st.nextToken();
aCookie = s.substring(0, s.indexOf(";"));
// aCookie = hdrString.substring(0, s.indexOf(";"));
int j = aCookie.indexOf("=");
if (j != -1) {
if (!theCookies.containsKey(aCookie.substring(0, j))){
// if the Cookie do not already exist then when keep it,
// you may want to add some logic to update
// the stored Cookie instead. thanks to rwhelan
theCookies.put(aCookie.substring(0, j),aCookie.substring(j + 1));
if (printCookies){
System.out.println();
System.out.println("Reading Key: " + aCookie.substring(0, j));
System.out.println(" Val: " + aCookie.substring(j + 1));
}
}
}
}
}
i++;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------
What should be done before calling writeCookies function (shown below)?
Now I want to process the received cookies so as to give the server what it expects.
According to my understanding,there is a some generic way of processing the received cookies
which applies to all websites.
After processing the cookies I want to send the cookies back to the Server using the function below.
Any idea how to do the 2nd step, i.e how to process the cookies?
Any help will be highly appreciated.
--------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------
public URLConnection writeCookies(URLConnection urlConn, boolean printCookies) throws Exception
{
String cookieString = "";
Enumeration keys = theCookies.keys();
urlConn.connect();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
cookieString += key + "=" + theCookies.get(key);
if (keys.hasMoreElements())
cookieString += "; ";
}
System.out.println("\n cookies: " + cookieString);
urlConn.setRequestProperty("Cookie", cookieString);
if (printCookies)
System.out.println("Wrote cookies:\n " + cookieString);
return urlConn;
}
------------------------------------------------------------------------------------------------------END.
|
|
|
|
|
Hello Everyone,
Im using My Eclipse6.0 and have oracle10g express edition. Now actually im creating a simple web project in eclipse at first i created a package called con.avanza.test1 and added a class called TestDB1.java.
The following code is present in TestDB1.java :
package com.avanza.test1;
import java.sql.*;
import oracle.jdbc.*;
public class TestDB1
{
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
public void connect()
{
try
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","admin");
System.out.println("Connected.");
}
catch(Exception e)
{
e.getStackTrace();
System.out.println(e);
}
}
public void display()
{
try
{
ps = con.prepareStatement("select * from details");
rs = ps.executeQuery();
int count = 0;
while(rs.next())
{
System.out.println("Name :: "+rs.getString(1)+" , Age :: "+rs.getString(2)+" , Phone No :: "+rs.getString(3));
count++;
}
System.out.println(count+" records selected...");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
TestDB1 aa=new TestDB1();
aa.connect();
aa.display();
}
}
On executing the above code the records in the DB gets displayed on the Console. Now Under the webroot is my JSP file called index.jsp
The coding in my JSP File is as follows:
<%@ page language="java" import="java.sql.*" pageEncoding="ISO-8859-1"%>
<%@ page import="com.avanza.test1.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
TestDB1 aa=new TestDB1();
aa.connect();
aa.display();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
</body>
</html>
i have included my package in the above code, on running it with server i can see only a blank page in my browser but my records from my DB gets displayed on the console... I need My records to be displayed on the browser through my JSP page... Wat kind of changes should i implement on my Jsp page... Do help me with some sample codes.. I am a beginner in java... Do plzz help me...
Thanx in advance...
Cheers,
Thashif
|
|
|
|
|
This is a very big subject, too big to answer in a simple post here on this forum.
Go to Google, and search for "jsp tutorial" and "jdbc tutorial". This will bring up lots of entries that should get you started.
And, I would recommend getting a good book on JEE. There are plenty around, and many of them focus specifically on JSP and servlets.
|
|
|
|
|
David is right, this is too much to start with. You need to start with just JSPs or just JDBC.
But you could try this:
<%@ page language="java" import="java.sql.*" pageEncoding="ISO-8859-1"%>
<%@ page import="com.avanza.test1.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
TestDB1 aa=new TestDB1();
aa.connect();
aa.display();
%>
</body>
</html>
|
|
|
|
|
That still doesn't work because the display() method directs the output to System.out, i.e. the console. In order to appear in the final web page it would need to be directed to the JSP output stream (there are a number of ways to do this).
The best thing to do is to find a beginner's JSP tutorial and start from there.
|
|
|
|
|
import java.io.IOException;
import java.sql.*;
import javax.servlet.http.*;
import oracle.jdbc.*;
public class TestDB1 extends HttpServlet
{
private static final long serialVersionUID = -1L;
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
try {
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","admin");
ps = con.prepareStatement("select * from details");
rs = ps.executeQuery();
int count = 0;
while(rs.next())
{
response.getWriter().write("Name :: "+rs.getString(1)+" , Age :: "+rs.getString(2)+" , Phone No :: "+rs.getString(3)+"<br>");
count++;
}
response.getWriter().write(count+" records selected...");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Good luck
|
|
|
|
|