Help finishing program
So I need to right a program where the user has to guess a number from 1 to 100 and the computer then says either higher or lower. The user then guesses again, and again until he gets the number right. Upon guessing the number right his score will come up which is the number of guesses it took him. I have no idea where to go from here, or how to have the score come up with the number of guesses. This is all I have and im not sure if its even right..
import java.util.Random;
import javax.swing.JOptionPane;
public class randomNumber {
public static void main(String[] args) {
Random generator=new Random ();
String playerInput;
playerInput=JOptionPane.showInputDialog (null,"Pick a number between 1 and 100");
double input2=generator.nextInt (100);
double input = Double.parseDouble (playerInput);
while (input != input2) {
if (input > input2) {
playerInput=JOptionPane.showInputDialog (null, "The number is lower, pick again");
if (input < input2){
playerInput=JOptionPane.showInputDialog (null, "The number is Higher, pick again");
if (input == input2) {
JOptionPane.showInputDialog (null, "You are correct!");
}
I think that writing the whole of your program in the main method isn't a very good idea , I think that you can use a class that encapsulates a game , you can put a variable which is incremented each time the user guess a number and when it's right it calls another method that shows the result in another JOptionPane with the variable(s) you used
Edited by: cyberjavacs on Apr 2, 2009 1:34 PM
Similar Messages
-
Hi there people, I would like some help finishing this off, but before I explain it, this is me practising my java this is not coursework, and I'm not trying to create and form of spyware!
Ok =D right what im trying to do is make a program like msn messenger, but when the user enters their username and password, that data gets sent to the listener which prints it out into a text file.
I am having trouble with the following area and would apprecitate a little help:
Layout - I'm not too sure how to work gridbaglayout
Background - How to you set a picture in the background?
Getting the entered text to the listener - I can't work out who I get the text the user has entered and print it out into the text file.
And if any of you have an idea on things I could add change etc then =D
Please don't b***h about me trying to make some spyware or rubbish like that, I'm just trying to have fun practising my java :)
Msn class
* Main class
* @author
* @date 25/05/06
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Msn extends SimpleFrame{
PanelArea panelArea = new PanelArea();
* Main method
public static void main(String[] args){
Msn msn = new Msn();
msn.showIt("MSN Messenger");
* Make the buttons to go at the top
public JMenuBar menuBar = new JMenuBar();
// Menu
public JMenu file = new JMenu("File");
public JMenu contacts = new JMenu("Contacts");
public JMenu actions = new JMenu("Actions");
public JMenu tools = new JMenu("Tools");
public JMenu help = new JMenu("Help");
// Submenu for file
public JMenuItem signIn = new JMenuItem("Sign In");
public JMenuItem signOut = new JMenuItem("Sign Out");
public JMenuItem openReceived = new JMenuItem("Open Received Files");
public JMenuItem close = new JMenuItem("Close");
// Submenu for contacts
public JMenuItem addContact = new JMenuItem("Add a Contact");
public JMenuItem searchContact = new JMenuItem("Search a Contact");
public JMenuItem addressBook = new JMenuItem("Go To My Address Book");
public JMenuItem displayPicture = new JMenuItem("View Display Picture");
public JMenuItem manageContacts = new JMenuItem("Manage Contacts");
public JMenuItem manageGroups = new JMenuItem("Manage Groups");
public JMenuItem sortContacts = new JMenuItem("Sort Contacts");
public JMenuItem saveContacts = new JMenuItem("Save Contacts By");
public JMenuItem importContacts = new JMenuItem("Import Contacts From a File");
// Submenu for actions
public JMenuItem sendInstantMessage = new JMenuItem("Send an Instant Message");
public JMenuItem videoVoice = new JMenuItem("Video/Voice");
public JMenuItem startActivity = new JMenuItem("Start an Activity");
public JMenuItem playGame = new JMenuItem("Play a Game");
public JMenuItem remoteAssistance = new JMenuItem("Request Remote Assistance");
// Submenu for tools
public JMenuItem allwaysOnTop = new JMenuItem("Always on Top");
public JMenuItem myEmotions = new JMenuItem("My Emotions");
public JMenuItem myBackground = new JMenuItem("My Background");
public JMenuItem changeDisplayPicture = new JMenuItem("Change Display Picture");
public JMenuItem myWinks = new JMenuItem("My WInks");
public JMenuItem webCam = new JMenuItem("Web Cam Settings");
// Submenu for help
public JMenuItem helpTopics = new JMenuItem("Help Topics");
public JMenuItem termsOfUse = new JMenuItem("Tersm of Use");
public JMenuItem sendFeedback = new JMenuItem("Send Feedback");
public JMenuItem aboutMsn = new JMenuItem("About MSN Messenger");
* Constructor to add the buttons onto the panel
Msn(){
MsnListener msnListener = new MsnListener();
// Add menuBar
this.setJMenuBar(menuBar);
// Add Items to the menuBar
menuBar.add(file);
menuBar.add(contacts);
menuBar.add(actions);
menuBar.add(tools);
menuBar.add(help);
// Add items to file
file.add(signIn);
file.add(signOut);
file.add(openReceived);
file.add(close).addActionListener(msnListener);
// Add items to contacts
contacts.add(addContact);
contacts.add(searchContact);
contacts.add(addressBook);
contacts.add(displayPicture);
contacts.add(manageContacts);
contacts.add(manageGroups);
contacts.add(sortContacts);
contacts.add(saveContacts);
contacts.add(importContacts);
// Add items to actions
actions.add(sendInstantMessage);
actions.add(videoVoice);
actions.add(startActivity);
actions.add(playGame);
actions.add(remoteAssistance);
// Add items to tools
tools.add(allwaysOnTop);
tools.add(myEmotions);
tools.add(myBackground);
tools.add(changeDisplayPicture);
tools.add(myWinks);
tools.add(webCam);
// Add items to help
help.add(helpTopics);
help.add(termsOfUse);
help.add(sendFeedback);
help.add(aboutMsn);
this.getContentPane().add(panelArea,BorderLayout.CENTER);
pack();
}Listener class
* Listener class
* @author
* @date 25/05/06
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class MsnListener implements ActionListener {
PanelArea pArea;
public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Close"))
leave();
if(actionCommand.equals("Sign In"))
popUp();
enter();
else if(actionCommand.equals("Ok"))
System.exit(0);
* Method to close the programme
* Called when user selects "Close" from the menu
public void leave(){
System.out.println("Testing");
System.exit(0);
* Method which takes the user name and password entered
* and puts it into a text file
* file is located in the same place as the java files
public void enter(){
System.out.println("Running");
PrintWriter outputStream = null;
try
outputStream =
new PrintWriter(new FileOutputStream("password.txt"));
catch(FileNotFoundException e)
System.out.println("Error opening the file");
System.out.println("written to file");
outputStream.println("User Name: ");
outputStream.println("Password: ");
outputStream.close();
* Pop for when the user tries to log in
public void popUp(){
Runnable runner = new Runnable() {
public void run()
try
Thread.sleep(1500);
} catch (InterruptedException e)
JFrame frame = new JFrame("MSN Error");
JLabel label = new JLabel("Error xdsf34234fd");
JButton okButton = new JButton("Ok");
frame.add(label, BorderLayout.CENTER);
frame.add(okButton, BorderLayout.SOUTH);
frame.setSize(200, 200);
frame.setVisible(true);
EventQueue.invokeLater(runner);
}Panel class
* PanelArea clas
* @author
* @date 35/05/06
* TextField, Buttons etc that go in the main panel
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PanelArea extends JPanel{
private static final long serialVersionUID = 1L;
// Makes the buttons and labels
private JLabel emailAddress = new JLabel("E-mail address");
private JTextField email = new JTextField();
private JLabel enterPassword = new JLabel("Password:");
private JPasswordField password = new JPasswordField();
private JButton signIn = new JButton("Sign In");
private JRadioButton remember = new JRadioButton();
private JRadioButton rememberPassword = new JRadioButton();
private JRadioButton autoSignIn = new JRadioButton();
private JLabel msPass = new JLabel("Microsoft Passport Network");
* Constructor to set things in palce
PanelArea(){
MsnListener msnListener = new MsnListener();
// Set Size and background Colour
this.setBackground(Color.WHITE);
this.setPreferredSize(new Dimension(500,600));
// Grid Layout
BorderLayout borderLayout = new BorderLayout();
this.setLayout(borderLayout);
this.setLayout(new GridLayout(0,1));
// Set the Buttons and Labels in place
this.add(emailAddress);
this.add(email);
this.add(enterPassword);
this.add(password);
this.add(signIn);
this.add(remember);
this.add(rememberPassword);
this.add(autoSignIn);
this.add(msPass);
signIn.addActionListener(msnListener);
public String getEmail(){
return email.getText();
public String getPassword(){
return password.getText();
}Simpleframe class
* SimpleFrame class
* @author
* @date 25/05/06
import javax.swing.*;
public class SimpleFrame extends JFrame {
public void showIt()
this.setVisible(true);
public void showIt(String title)
this.setTitle(title);
this.setVisible(true);
public void showIt(String title,int x,int y)
this.setTitle(title);
this.setLocation(x,y);
this.setVisible(true);
}nullbut it throws loads of awt exceptions! what am I doing wrong?you've changed the method to reference pArea
pArea.getEmail()
but pArea is null
PanelArea pArea;
you need to pass some references
Msn(){
//MsnListener msnListener = new MsnListener();<------comment out this
this.getContentPane().add(panelArea,BorderLayout.CENTER);
pack();
class MsnListener implements ActionListener {
PanelArea pArea;//<--------see next line
MsnListener(PanelArea p){pArea = p;}//<--------------add the constructor, and pass the reference
public void actionPerformed(ActionEvent e){
PanelArea(){
//MsnListener msnListener = new MsnListener();<-----------change to next line
MsnListener msnListener = new MsnListener(this);//<----pass the reference
// Set Size and background Colour
this.setBackground(Color.WHITE);make these changes to a backup copy of your program
(in case they don't do what you want) -
No matter what I try I can never get the Acrobat Reader to be added to the group of "Choose Helper Application" programs available in that window when downloading a pdf. I always have to browse to the Acrobat reader and select it that way.
I have enabled Acrobat in the add-ons manager, but that has not solved the problem.
In the options > applications menu I've selected use Acrobat Reader for pdf files but that doesn't work and furthermore doesn't seem to stick. That is, sometimes when I check that menu later the selection has reverted to "always ask".
I'm using Firefox 32 on Windows 7. I have used Firefox on XP for years and never had this problem.Here are some screen shots to backup my claims.
-
Need help finishing off slideshow
Hello there,
I have posted here a few times before, i have had great help from members but now i just need help finishing off my project. It is for a client and i am trying to do it as fast as i can but i do not have the knowledge to finish off the code. I did post this question previously but it has gone unanswered,
I just need help on a roll out effect, i have it so if the mouse rolls of the button before the second image is up, it fades out. That is good. But when the second image IS up, the mouse rolls off the button and then the 2nd image fades out, but the 1st images shows up and also fades out. How can i prevent this from happening so it is always only the visible image that will fade out.
Thanks in advance,
Declan.I don't have time to go thru your code in detail to figure out what it's supposed to be doing, and no one is likely to try to help if you don't provide it here. If I look at your other posting I see one line that you should correct... who knows, it might be the source of your problem... this line needs to be fixed....
if (image2.visible = true) -
Hai,
Can any one give example for search help with Programming?
I hope we can create search help with help of coding.
With Regards,Jaheer.yes u can create search help by using match code in programs
for eq
go with abap editor se 38
provide the name of program
parameters : vendor like lfa1-lifnr matchcode object yzob.
double click on yzob
provide description for search help
provide selection method
provide search help parameter
enable check box for import and export
provide lpos
spos
save check activate
press f4 for check and import values i.e it will display a records list available in database table
rewards points please -
I switched to Apple Mail in the last two months. When I attempt to print an email message, I get a blank piece of paper. When I attempt to use the print options suggested in "Mail Help", the program crashes and has to be reopened. Any ideas?
Which version of Mail are you using as well as which Snow Leopard version you are using?
-
Adding the search help in program
hi i want to add a search help in program for a particular field of a parameter how to do this?
U need to create a serach help exit for this purpose.
F4IF_SHLP_EXIT_EXAMPLE - documents the different reasons to use a search help exit, and shows how it is done.
http://www.sapdevelopment.co.uk/dictionary/shelp/shelp_exit.htm
http://www.sapdevelopment.co.uk/dictionary/shelp/shelp_basic.htm
Create an Elementary Search help:
Eg: Zsearch
In the defintion tab:
Give the search help exit name: Zsearch_exit.
Also give the search help param and data element.
Copy F4IF_SHLP_EXIT_EXAMPLE into Zsearch_exit
Comment:
callcontrol-step = 'SELECT'. (1st line)
Inside:
IF CALLCONTROL-STEP = 'SELECT'.
Select required data for the search help
Select stmnts as per your requirement and populate in itab.
Move all the selected records to Record_Tab
LOOP AT itab INTO wa_itab.
MOVE wa_itab TO record_tab-string.
APPEND record_tab.
CLEAR record_tab.
ENDLOOP.
RC = 0 .
IF RC = 0.
CALLCONTROL-STEP = 'DISP'.
ELSE.
CALLCONTROL-STEP = 'EXIT'.
ENDIF.
EXIT. "Don't process STEP DISP additionally in this call.
Let me know if its working for you.
Also, chek this link if it helps you:Re: Find Storage location with respect to Plant -
I want parameters with f4 help for program names in value request
I want parameters with f4 help for program names in value request
points will be awarded if usefullv_name1 TYPE name1, "Vendor Name
CALL FUNCTION 'POPUP_TO_SEARCH_VALUE'
EXPORTING
textline1 = 'Vendor Name'(f09)
titel = 'Enter'(f17)
valuelength = 35
IMPORTING
value = lv_name1.
try this out .. -
Hi all,
is anyone able to explain me how to use Search Help freely programmed?
thanks
GNHi Gabriele,
Please go through the component DEMO_VALUE_HELP. This explains all the input help types. The freely programmed search help has been implemented for the CONNID input field of view V1. The Web Dynpro component FREE_VALUE_HELP in the same package is the component where the search help is coded.
Also below are the steps to be followed for implementing the freely programmed search help.
This kind of value help is implemented as a Web Dynpro component implementing the Web Dynpro
component interface IWD_VALUE_HELP. To be able to use the value help for a certain input field, the following steps are necessary:
1) A component usage of the value help component (HC) has to be declared
by the consumer component (CC).
2) A usage of the HC interface controller has to be declared in the CC view.
3) The input help mode User-Defined Programming has to be chosen for the attribute that is bound to the input field under consideration. The HC usage must be related to this attribute. The component interface of the HC has only one method: set_value_help_listener( ). This method is called by the Web Dynpro runtime if the value help button of the input field under consideration is clicked. The HC has to be implemented as follows:
1) The method set_value_help_listener( ) has an import parameter. This means that the reference to the listener, provided by the Web Dynpro runtime, is passed to the user-defined HC. This reference has to be saved as a user defined controller attribute.
2) To close the help value dialog box, the close_window( ) method of the listener has to be used.
3) All views have to be embedded into a window having the name WD_VALUE_HELP. This name is used by the Web Dynpro runtime.
4) To exchange data between the CC and the HC, context mapping can be used.
For implementing the component interface IWD_VALUE_HELP, you need to choose the Reimplement button in the HC. The implementation status changes to green and the events and the method of the component interface are visible in the HC controller.
Regards,
Uday -
This computer will not update to 5.0. I have tried to download and install 5.0 for many weeks. My OTHER computer updated fine. When I try to install 5.0 it say to restart to finish installation of another firefox. Restart does not change anything.
I click on ff help, about ff and it says 5.0 is installed. I look on programs and features and only ff 3.6.8 is listed. I have tried clean ups, update java, plugins and stuff like that with no change to this issue.I guess no one cares.
-
Please help, java program terminating unexpectedly without reason
ok, so I have a project I'm working on, here's its description:
Create a new project named FML_Pig where F is your first initial, M is your middle initial, and L is your last initial. For example, if your name is Alfred Edward Neuman then you would name your project AEN_Pig. If necessary, add a new Java file to this project named FML_Pig.
Add a java file to the project named FML_Dice.
Design and implement a Dice class as follows. The Dice class has 2 twenty‑sided dice with numbers on the faces (1 � 20) and 2 twenty-six-sided dice with letters on the faces (a � z).
import java.util.Random;
public class FML_Dice
private static Random gen = new Random();
private final static int NUM_SIDES = 20;
private int die1, die2, numSnakeEyes, numVowels, totalPoints;
private char die3, die4;
Part 1
Add a rollDice() method to your FML_Dice class that sets die1 and die2 to a random number between 1 and 20 and it sets die3 and die4 to a random character between �a� and �z�.
Helpful Hint:
dice3 = (char)(�a� + gen.nextInt(26)); // sets dice3 to a random char between �a� and �z�.
Part 2
Write a constructor that sets die1 and die2 to a random number between 1 and 20 and it sets die3 and die4 to a random character. Your constructor can simply call rollDice() to do this. It should also initialize numSnakeEyes, numVowels, and totalPoints to 0 (after you roll the dice).
Part 3
Write methods getDie1(), getDie2(), getDie3(), and getDie4() that returns the value of the respective die. Write a method numSnakes() that returns the number of snake eyes that have been rolled. Write a method numVowels() that returns the number of vowels that have been rolled. Write a method totalPts() that returns the totalPoints.
Part 4
Write a toString() method that overwrites the default toString() method. It should return a String representation of the value of all 4 die. For example, 17 2 h w.
Part 5
Write a method updateTotals that updates numVowels, numSnakeEyes, and totalPoints based on the current values of die1, die2, die3, and die4. numVowels should be incremented by 1 if either die3 or die4 are a vowel. However, if both die3 and die4 are vowels, the totalPoints should be reset to 0 and numVowels should be reset to 0 also. numSnakeEyes should be incremented by 1 if either die1 or die2 have a face value of 1 (this is not truly a snake eyes, but it gives better odds for the game). totalPoints should be incremented by the sum of die1 and die2 multiplied by (numSnakeEyes + 1).
Part 6
Write a main program (use the one in FML_Pig.java) that plays a game of Pig. In this game, two people play against each other. Player1 begins by rolling the dice. The total of die1 and die2 is added to his total score. Player1�s turn continues until he/she rolls a total of 4 vowels then the turn switches to Player2. Whenever a turn switches to the other player, the number of vowels is reset to zero. Also, if at any time both die3 and die4 are vowels, the total score is reset to 0 and the turn switches to the other player. (So the turn switches to the other player whenever the total number of vowels reaches four or there are two vowels rolled at the same time.)
If a player rolls snakeeyes (for our game, snakeeyes occurs whenever either of the dice have a face value of one � in reality, both die1 and die2 should have a face value of one but then snakeeyes would occur only once every 400 rolls), then his point values are doubled from that point on (all future rolls for the rest of the game, point values for this player are doubled). When a player rolls snake eyes again, point values are tripled for that roll and all future rolls. (Three snake eyes, quadrupled, etc.)
(continued on the next page)
Be sure to display the results of the roll for each turn.
First player to get to 2000 points wins the game and gets to oink like a pig.
Note: Both players need their own set of Dice since the Dice keeps track of the totalPoints, the number of snake eyes rolled so far, and the number of vowels rolled so far for that particular player. You can do this simply by declaring it that way in the main program:
Dice player1 = new Dice();
Dice player2 = new Dice();
You may add additional methods and instance variables to the class as needed. For example, I would probably write a private helper method isVowel() that is passed a char argument ch and returns true if ch is a vowel.
Also, you can have the computer play for both player 1 and player 2. Simply loop it until somebody wins. Print out the result for each turn including who rolled the dice (player 1 or player 2), what they rolled, how many snakeeyes do they have, how many points did they get for this turn, and how many total points do they have.
When you are completely finished, hand in just the java files (FLM_Dice & FLM_Pig). If you happened to write any other classes, make sure they are named with the FML format, and turn these in as well. I do not need EasyReader or p.
Oink! Oink!
This pig won the game --------->
so here's my code:
this isn't my code but is required to compile my code: // package com.skylit.io;
import java.io.*;
* @author Gary Litvin
* @version 1.2, 5/30/02
* Written as part of
* <i>Java Methods: An Introduction to Object-Oriented Programming</i>
* (Skylight Publishing 2001, ISBN 0-9654853-7-4)
* and
* <i>Java Methods AB: Data Structures</i>
* (Skylight Publishing 2003, ISBN 0-9654853-1-5)
* EasyReader provides simple methods for reading the console and
* for opening and reading text files. All exceptions are handled
* inside the class and are hidden from the user.
* <xmp>
* Example:
* =======
* EasyReader console = new EasyReader();
* System.out.print("Enter input file name: ");
* String fileName = console.readLine();
* EasyReader inFile = new EasyReader(fileName);
* if (inFile.bad())
* System.err.println("Can't open " + fileName);
* System.exit(1);
* String firstLine = inFile.readLine();
* if (!inFile.eof()) // or: if (firstLine != null)
* System.out.println("The first line is : " + firstLine);
* System.out.print("Enter the maximum number of integers to read: ");
* int maxCount = console.readInt();
* int k, count = 0;
* while (count < maxCount && !inFile.eof())
* k = inFile.readInt();
* if (!inFile.eof())
* // process or store this number
* count++;
* inFile.close(); // optional
* System.out.println(count + " numbers read");
* </xmp>
public class EasyReader
protected String myFileName;
protected BufferedReader myInFile;
protected int myErrorFlags = 0;
protected static final int OPENERROR = 0x0001;
protected static final int CLOSEERROR = 0x0002;
protected static final int READERROR = 0x0004;
protected static final int EOF = 0x0100;
* Constructor. Prepares console (System.in) for reading
public EasyReader()
myFileName = null;
myErrorFlags = 0;
myInFile = new BufferedReader(
new InputStreamReader(System.in), 128);
* Constructor. opens a file for reading
* @param fileName the name or pathname of the file
public EasyReader(String fileName)
myFileName = fileName;
myErrorFlags = 0;
try
myInFile = new BufferedReader(new FileReader(fileName), 1024);
catch (FileNotFoundException e)
myErrorFlags |= OPENERROR;
myFileName = null;
* Closes the file
public void close()
if (myFileName == null)
return;
try
myInFile.close();
catch (IOException e)
System.err.println("Error closing " + myFileName + "\n");
myErrorFlags |= CLOSEERROR;
* Checks the status of the file
* @return true if en error occurred opening or reading the file,
* false otherwise
public boolean bad()
return myErrorFlags != 0;
* Checks the EOF status of the file
* @return true if EOF was encountered in the previous read
* operation, false otherwise
public boolean eof()
return (myErrorFlags & EOF) != 0;
private boolean ready() throws IOException
return myFileName == null || myInFile.ready();
* Reads the next character from a file (any character including
* a space or a newline character).
* @return character read or <code>null</code> character
* (Unicode 0) if trying to read beyond the EOF
public char readChar()
char ch = '\u0000';
try
if (ready())
ch = (char)myInFile.read();
catch (IOException e)
if (myFileName != null)
System.err.println("Error reading " + myFileName + "\n");
myErrorFlags |= READERROR;
if (ch == '\u0000')
myErrorFlags |= EOF;
return ch;
* Reads from the current position in the file up to and including
* the next newline character. The newline character is thrown away
* @return the read string (excluding the newline character) or
* null if trying to read beyond the EOF
public String readLine()
String s = null;
try
s = myInFile.readLine();
catch (IOException e)
if (myFileName != null)
System.err.println("Error reading " + myFileName + "\n");
myErrorFlags |= READERROR;
if (s == null)
myErrorFlags |= EOF;
return s;
* Skips whitespace and reads the next word (a string of consecutive
* non-whitespace characters (up to but excluding the next space,
* newline, etc.)
* @return the read string or null if trying to read beyond the EOF
public String readWord()
StringBuffer buffer = new StringBuffer(128);
char ch = ' ';
int count = 0;
String s = null;
try
while (ready() && Character.isWhitespace(ch))
ch = (char)myInFile.read();
while (ready() && !Character.isWhitespace(ch))
count++;
buffer.append(ch);
myInFile.mark(1);
ch = (char)myInFile.read();
if (count > 0)
myInFile.reset();
s = buffer.toString();
else
myErrorFlags |= EOF;
catch (IOException e)
if (myFileName != null)
System.err.println("Error reading " + myFileName + "\n");
myErrorFlags |= READERROR;
return s;
* Reads the next integer (without validating its format)
* @return the integer read or 0 if trying to read beyond the EOF
public int readInt()
String s = readWord();
if (s != null)
return Integer.parseInt(s);
else
return 0;
* Reads the next double (without validating its format)
* @return the number read or 0 if trying to read beyond the EOF
public double readDouble()
String s = readWord();
if (s != null)
return Double.parseDouble(s);
// in Java 1, use: return Double.valueOf(s).doubleValue();
else
return 0.0;
}same with this:
public class p
public static void l(String S)
{ System.out.println(S);}
public static void o(String S)
{System.out.print(S);}
public static void l(int i)
{ System.out.println(i);}
public static void o(int i)
{System.out.print(i);}
public static void l(boolean b)
{ System.out.println(b);}
public static void o(boolean b)
{System.out.print(b);}
public static void l(char c)
{ System.out.println(c);}
public static void o(char c)
{System.out.print(c);}
public static void l(double d)
{ System.out.println(d);}
public static void o(double d)
{System.out.print(d);}
public static void l(Object obj)
{ System.out.println(obj.toString());}
public static void o(Object obj)
{System.out.print(obj.toString());}
public static void l()
{System.out.println();}
} here's my code:
import java.util.*;
public class JMM_Pig
public static void main(String[] args)
int winner=0;
int pts=0;
JMM_Dice player1=new JMM_Dice();
JMM_Dice player2=new JMM_Dice();
p.l("Player 1 rolls the dice...");
player1.rollDice();
player1.updateTotals();
boolean loop=true;
while(loop)
while(player1.numVowels()<=4)
p.l("Player 1 continues his turn...");
player1.rollDice();
player1.updateTotals();
p.l("Player 1 rolled a "+player1.getDie1()+" and a "+player1.getDie2()+" and a '"+player1.getDie3()+"' and a '"+player1.getDie4()+"'");
p.l("Player 1 rolled "+player1.currvowels()+" vowels.");
p.l("Player 1 has "+player1.totalvowels()+" total vowels.");
//if(player1.getMagic()==1)
//player1.totalPoints=(player1.totalPoints+player1.getDie1()+player1.getDie2())*player1.mult;
//pts=(player1.totalPts()+player1.getDie1()+player1.getDie2())*player1.getMult();
//player1.setTpts(pts);
//if(player1.getMagic()!=1)
//player1.totalPoints=player1.totalPoints+player1.getDie1()+player1.getDie2();
//pts=player1.totalPts()+player1.getDie1()+player1.getDie2();
//player1.setTpts(pts);
p.l("Player 1 has "+player1.numSnakes()+" snake eyes.");
p.l("Player 1 earned "+player1.ptsreturn()+" points this turn.");
p.l("Player 1 has "+player1.totalPts()+" total points.");
pts=0;
if(player1.totalPts()>=2000)
winner=1;
player1.setNv(4);loop=false;
if((player1.isavowel(player1.getadice()))&&player1.isavowel(player1.getadice2()))
player1.setTpts(0);player1.setNv(0);player1.setNv(4);
p.l("Player 1's turn has ended...");
player1.setNv(0);
p.l("Player 2 rolls the dice...");
player2.rollDice();
player2.setTpts(player2.totalPts()+player2.getDie1()+player2.getDie2());
while(player2.numVowels()<=4)
p.l("Player 2 continues his turn...");
player2.rollDice();
player2.updateTotals();
p.l("Player 2 rolled a "+player2.getDie1()+" and a "+player2.getDie2()+" and a '"+player2.getDie3()+"' and a '"+player2.getDie4()+"'");
p.l("Player 2 rolled "+player2.currvowels()+" vowels.");
p.l("Player 2 has "+player2.totalvowels()+" total vowels.");
//if(player1.getMagic()==1)
//player1.totalPoints=(player1.totalPoints+player1.getDie1()+player1.getDie2())*player1.mult;
//pts=(player1.totalPts()+player1.getDie1()+player1.getDie2())*player1.getMult();
//player1.setTpts(pts);
//if(player1.getMagic()!=1)
//player1.totalPoints=player1.totalPoints+player1.getDie1()+player1.getDie2();
//pts=player1.totalPts()+player1.getDie1()+player1.getDie2();
//player1.setTpts(pts);
p.l("Player 2 has "+player2.numSnakes()+" snake eyes.");
p.l("Player 2 earned "+player2.ptsreturn()+" points this turn.");
p.l("Player 2 has "+player2.totalPts()+" total points.");
pts=0;
if(player2.totalPts()>=2000)
winner=2;
player2.setNv(4);loop=false;
if((player2.isavowel(player2.getadice()))&&player2.isavowel(player2.getadice2()))
player2.setTpts(0);player2.setNv(0);player2.setNv(4);
p.l("Player 2's turn has ended...");
player2.setNv(0);
if(player1.totalPts()>=2000)
winner=1;
loop=false;
if(player2.totalPts()>=2000)
winner=2;
loop=false;
} //main loop
if(winner==1)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 1 wins, oink oink!");
if(winner==2)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 2 wins, oink oink!");
and dice class:
import java.util.*;
public class JMM_Dice {
private static Random gen = new Random();
private final static int NUM_SIDES = 21;
private int die1, die2, numSnakeEyes, numVowels, totalPoints;
private char die3, die4;
private int dice=0;
//dice=
private int dice2=0;
//dice2=;
private String adice="";
//adice=;
private String adice2="";
//adice2;
private int magic=0;
private int mult=0;
private int currvowels=0;
private int totalvowels=0;
public static EasyReader key = new EasyReader();
public JMM_Dice()
dice=0;dice2=0;
String alpha="abcdefghijklmnopqrstuvwxyz";
adice="";adice2="";
rollDice();
numSnakeEyes=0;numVowels=0;totalPoints=0;
public void setTpts(int tpts)
this.totalPoints=tpts;
public void setNv(int nv)
this.numVowels=nv;
public int getDie1()
return dice;
public int getDie2()
return dice2;
public String getDie3()
return adice;
public String getDie4()
return adice2;
public int numSnakes()
return numSnakeEyes;
public void setSnakes(int s)
this.numSnakeEyes=s;
public String getadice()
return this.adice;
public String getadice2()
return this.adice2;
public int numVowels()
return numVowels;
public int getMagic()
return this.magic;
public int getNv()
return this.numVowels;
public void setMagic(int mag)
this.magic=mag;
public int getMult()
return this.mult;
public void setMult(int m)
this.mult=m;
public int totalPts()
return totalPoints;
public String toString()
return dice+""+dice2+""+adice+""+adice2;
public boolean isavowel(String str)
if(str.equals("a")||str.equals("e")||str.equals("i")||str.equals("o")||str.equals("u"))
return true;
else
return false;
public int ptsreturn()
return dice+dice2;
public int currvowels()
int tmp=currvowels;
currvowels=0;
return tmp;
public int totalvowels()
return numVowels;
public void updateTotals()
if(adice.equalsIgnoreCase("a")||adice.equalsIgnoreCase("e")||adice.equalsIgnoreCase("i")||adice.equalsIgnoreCase("o")||adice.equalsIgnoreCase("u")||adice2.equalsIgnoreCase("a")||adice2.equalsIgnoreCase("e")||adice2.equalsIgnoreCase("i")||adice2.equalsIgnoreCase("o")||adice2.equalsIgnoreCase("u"))
numVowels++;currvowels++;
if((isavowel(adice))&&isavowel(adice2))
totalPoints=0;numVowels=0;
if(dice==1||dice2==1)
numSnakeEyes++;
int fd=dice;
int sd=dice2;
int sum=fd+sd;
totalPoints+=sum*(numSnakeEyes+1);
public void rollDice()
dice=gen.nextInt(20)+1;
dice2=gen.nextInt(20)+1;
String alpha="abcdefghijklmnopqrstuvwxyz";
adice=String.valueOf(alpha.charAt(gen.nextInt(26)));
adice2=String.valueOf(alpha.charAt(gen.nextInt(26)));
public static void sleep (int wait)
{ long timeToQuit = System.currentTimeMillis() + wait;
while (System.currentTimeMillis() < timeToQuit)
; // take no action
}the program works fine except it's supposed to terminate when one of the two AIs get a score of 2000, right now it terminates no matter what score the AIs get and no matter what I've tried to do it keeps doing that...can someone please tell me why it's terminating so oddly? Thanks! :)Here's how my code works in a nutshell, the main program starts with the boolean loop=true;
while(loop)
{then comes the loops for the two AIs, first the player 1 AI goes with this loop: while(player1.numVowels()<=4)
{there the player 1 roles the dice and it keeps going until player 1 gets a total of 2000 points at which time this is supposed to execute: if(player1.totalPts()>=2000)
winner=1;
player1.setNv(4);loop=false;
}, player1.setNv(4); sets numVowels to 4 so that the inner loop exits, loop=false exits the other loop and winner=1; specifies that player 1 won which is used outside of the loops here: if(winner==1)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 1 wins, oink oink!");
if(winner==2)
p.l("It ended with the following statistics...");
p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
p.l("Player 2 wins, oink oink!");
} the same thing happens for player 2 if player 1 didn't already get 2000 points...but the if statement despite everything pointing to the variables containing the right values don't seem to be working, as shown by the example program output I posted it just ends at any random number...hopefully this helps make figuring out what's wrong easier :) ...so can anyone please help me out? thanks! :) -
Hi everybody,
I designed a calculator, and I need help with the rest of the scientific actions. I know I need to use the different Math methods, but what exactly? Also, it needs to work as an applet and application, and in the applet, the buttons don't appear in order, how can I fix that?
I will really appreciate your help with this program, I need to finish it ASAP. Please e-mail me at [email protected].
Below is the code for the calcualtor.
Thanks in advance,
-Maria
// calculator
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class calculator extends JApplet implements
ActionListener
private JButton one, two, three, four, five, six, seven,
eight, nine, zero, dec, eq, plus, minus, mult, div, clear,
mem, mrc, sin, cos, tan, asin, acos, atan, x2, sqrt, exp, pi, percent;
private JLabel output, blank;
private Container container;
private String operation;
private double number1, number2, result;
private boolean clear = false;
//GUI
public void init()
container = getContentPane();
//Title
//super("Calculator");
JPanel container = new JPanel();
container.setLayout( new FlowLayout( FlowLayout.CENTER
output = new JLabel("");
output.setBorder(new MatteBorder(2,2,2,2,Color.gray));
output.setPreferredSize(new Dimension(1,26));
getContentPane().setBackground(Color.white);
getContentPane().add( "North",output );
getContentPane().add( "Center",container );
//blank
blank = new JLabel( " " );
container.add( blank );
//clear
clear = new JButton( "CE" );
clear.addActionListener(this);
container.add( clear );
//seven
seven = new JButton( "7" );
seven.addActionListener(this);
container.add( seven );
//eight
eight = new JButton( "8" );
eight.addActionListener(this);
container.add( eight );
//nine
nine = new JButton( "9" );
nine.addActionListener(this);
container.add( nine );
//div
div = new JButton( "/" );
div.addActionListener(this);
container.add( div );
//four
four = new JButton( "4" );
four.addActionListener(this);
container.add( four );
//five
five = new JButton( "5" );
five.addActionListener(this);
container.add( five );
//six
six = new JButton( "6" );
six.addActionListener(this);
container.add( six );
//mult
mult = new JButton( "*" );
mult.addActionListener(this);
container.add( mult );
//one
one = new JButton( "1" );
one.addActionListener(this);
container.add( one );
//two
two = new JButton( "2" );
two.addActionListener(this);
container.add( two );
//three
three = new JButton( "3" );
three.addActionListener(this);
container.add( three );
//minus
minus = new JButton( "-" );
minus.addActionListener(this);
container.add( minus );
//zero
zero = new JButton( "0" );
zero.addActionListener(this);
container.add( zero );
//dec
dec = new JButton( "." );
dec.addActionListener(this);
container.add( dec );
//plus
plus = new JButton( "+" );
plus.addActionListener(this);
container.add( plus );
//mem
mem = new JButton( "MEM" );
mem.addActionListener(this);
container.add( mem );
//mrc
mrc = new JButton( "MRC" );
mrc.addActionListener(this);
container.add( mrc );
//sin
sin = new JButton( "SIN" );
sin.addActionListener(this);
container.add( sin );
//cos
cos = new JButton( "COS" );
cos.addActionListener(this);
container.add( cos );
//tan
tan = new JButton( "TAN" );
tan.addActionListener(this);
container.add( tan );
//asin
asin = new JButton( "ASIN" );
asin.addActionListener(this);
container.add( asin );
//acos
acos = new JButton( "ACOS" );
cos.addActionListener(this);
container.add( cos );
//atan
atan = new JButton( "ATAN" );
atan.addActionListener(this);
container.add( atan );
//x2
x2 = new JButton( "X2" );
x2.addActionListener(this);
container.add( x2 );
//sqrt
sqrt = new JButton( "SQRT" );
sqrt.addActionListener(this);
container.add( sqrt );
//exp
exp = new JButton( "EXP" );
exp.addActionListener(this);
container.add( exp );
//pi
pi = new JButton( "PI" );
pi.addActionListener(this);
container.add( pi );
//percent
percent = new JButton( "%" );
percent.addActionListener(this);
container.add( percent );
//eq
eq = new JButton( "=" );
eq.addActionListener(this);
container.add( eq );
//Set size and visible
setSize( 190, 285 );
setVisible( true );
public static void main(String args[]){
//execute applet as application
//applet's window
JFrame applicationWindow = new JFrame("calculator");
applicationWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//applet instance
calculator appletObject = new calculator();
//init and start methods
appletObject.init();
appletObject.start();
} // end main
public void actionPerformed(ActionEvent ae)
JButton but = ( JButton )ae.getSource();
//dec action
if( but.getText() == "." )
//if dec is pressed, first check to make shure there
is not already a decimal
String temp = output.getText();
if( temp.indexOf( '.' ) == -1 )
output.setText( output.getText() + but.getText() );
//clear action
else if( but.getText() == "CE" )
output.setText( "" );
operation = "";
number1 = 0.0;
number2 = 0.0;
//plus action
else if( but.getText() == "+" )
operation = "+";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//minus action
else if( but.getText() == "-" )
operation = "-";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//mult action
else if( but.getText() == "*" )
operation = "*";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//div action
else if( but.getText() == "/" )
operation = "/";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//eq action
else if( but.getText() == "=" )
number2 = Double.parseDouble( output.getText() );
if( operation == "+" )
result = number1 + number2;
else if( operation == "-" )
result = number1 - number2;
else if( operation == "*" )
result = number1 * number2;
else if( operation == "/" )
result = number1 / number2;
//output result
output.setText( String.valueOf( result ) );
clear = true;
operation = "";
//default action
else
if( clear == true )
output.setText( "" );
clear = false;
output.setText( output.getText() + but.getText() );Multiple post:
http://forum.java.sun.com/thread.jsp?forum=31&thread=474370&tstart=0&trange=30 -
I need help finishing the java install
i have windows Millenium Edition & am trying to download J2SDK 1.5.0_4 so that i can write small programs at home. However, i cannot get the install software to finish putting java onto my desktop. it just keeps telling me that the install is complete but, there is no java icon to open the package. i have removed the program completely and tried a second time to install the software but i can get no further that the installshield wizard. i am at a loss and desperately want to start writing programs with java. someone out there, please help!
i tried downloading an installing " Windows Offline Installation, Mult-language jdk-1_5_0_04-windows-i586-p.exe ( J2SE Develop. Kit 5.0 Update 4 ) " but it won't let me open java to write any programs.
Thank you for your help in this matter.
kind regards
eric d.Java does not have a desktop icon to click. You open the command window and type commands to compile and execute the programs you write.
I strongly suggest that you go to this tutorial
http://java.sun.com/docs/books/tutorial/
and click the First Steps: link. Be sure to click the link to the installation instructions and read them, especially the instructions about setting the PATH environment variable and the coaution regarding the use of Windows' Notepad. -
Help having program sleep during execution
Hello,
I am writing a program in which alot of data is being displayed, but I want to slow down the speed of the text so it can be viewed. (Like sports commentary, play by play)
I tried using a thread (perhaps incorrectly, as a thread doesn't seem needed here anyway) sleep and wait functions, but they both cause my GUI to be "busy". (ie. my screen is blank until the thread finishes)
Basically, the program does some analysis, prints out the data to the JTextArea, and then analyzes more data, prints it to the textarea, etc..
How can I slow down the text display to the user, so they can view the data slowly without the GUI being killed?
I would greatly appreciate any help/comments/tips!!
Thanks,
PaulThanks everyone for your help. I got it working. I made the entire routine a thread, and then after writing the data to the textarea, used a sleep.
It didn't work until I made the entire routine (not just the part that writes to the textarea) a thread.
Thanks again for everyone's help! -
HELP - ABAP Program Cancelled After Running for 2.5 Hours in Background
I have an ABAP report program that was being tested in our QA system and it died after running for 2.5 hours with the status of "Cancelled" (which, I assume, means it was terminated by SAP for exceeding some type of governor).
I ran Code Analyzer and no performance issues were recognized.
I am running several SELECT statements during program execution. These are a list of all the SELECT statements used in my program. Also, I'm using PNPCE to get a list of pernrs for which to pull data at the beginning of the program.
SELECT *
INTO CORRESPONDING FIELDS OF TABLE gt_p0167
FROM pa0167
WHERE pernr EQ gt_selected_pernrs
AND bplan IN s_bplan
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE fgbdt fasex
INTO (lv_dob, lv_gender)
FROM pa0021
WHERE pernr EQ gt_selected_pernrs
AND subty EQ <fs_dtyxx>
AND objps EQ <fs_didxx>
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE agency ansvh
INTO (p_agency_out, lv_ansvh)
FROM pa0001
WHERE pernr EQ p_pernr_in
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE vorna nachn gbdat perid gesch
INTO (gt_control_table-fname, gt_control_table-lname, gt_control_table-dob, gt_control_table-mskssn, gt_control_table-gender)
FROM pa0002
WHERE pernr EQ p_pernr_in
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE perid
INTO (lv_ssn)
FROM pa0106
WHERE pernr EQ p_pernr_in
AND subty EQ p_subty_in
AND objps EQ p_objps_in
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE smoke
INTO (p_smoker_out)
FROM pa0376
WHERE pernr = p_pernr_in
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE state pstlz zcounty
INTO (p_state_out, lv_zip, p_county_out)
FROM pa0006
WHERE pernr EQ p_pernr_in
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE werks btrtl
INTO (lv_werks, lv_btrtl)
FROM pa0001
WHERE pernr EQ p_pernr_in
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE region
INTO (p_region_out)
FROM zpat_county_code
WHERE county EQ p_county_in.
SELECT SINGLE pernr
INTO lv_pernr
FROM pa0002
WHERE perid EQ gt_cobra_table-l_essn.
SELECT SINGLE eecst ercst
INTO (lv_eecst, lv_ercst)
FROM t5ubi
WHERE barea EQ '01'
AND bplan EQ lv_bplan
AND bcost EQ p_bcost_in
AND cstv1 EQ '0001'
AND smoke EQ p_smoker_in
AND begda LE pn-endda
AND endda GE pn-begda.
SELECT SINGLE kwert
INTO lv_kwert
FROM t511k
WHERE molga EQ '10'
AND konst EQ 'ZCOB1'
AND begda LE pn-endda
AND endda GE pn-begda.The screen shot the tester sent me only says that it was canceled. However, the log shows the following:
09/17/2008 16:54:32 Job Started
09/17/2008 16:54:32 Step 001 started (program ZBNI001...
09/17/2008 19:22:09 ABAP/4 processor: DATASET_NOT_OPEN
09/17/2008 19:22:09 Job cancelled
I'm not sure it was an error, per se, but maybe SAP canceled it because it had been running too long? The "DATASET_NOT_OPEN" is curious although I've no idea what it means.
Thanks for your help.
Maybe you are looking for
-
ABAP/4 processor: TSV_TNEW_PAGE_ALLOC_FAILED
Hi, Please help me. I'm having ABAP/4 processor: TSV_TNEW_PAGE_ALLOC_FAILED job cancelled for my payment run F110. Before this we having performance issue for the payment run F110. We implemented notes (SNOTE 1343823) to solve the performance issue.
-
Getting the name of the superclasses?
I'm using a subclass. But I want to show all of the classes it is inheriting from in a Applet. But I can't find the method. Who knows?
-
Capitalised value from legacy system
My client tried capturing all costs from previous years i.e. before launch of PS from a legacy system. So for this they created WBS for earlier years. Posted actual costs through Manual Allocation through FI postings. For this they created a dummy co
-
Contact number choices... can they all be listed?
When I put in my contacts with Multiple numbers (eg.. mobile, Home ect) Only one option number shows when I click on them. For example I made my husband a favorite and when I choose him from contacts it only says call mobile. I would like to know if
-
i have downloaded cs6 trial off the web site but after takeing 7 hours to download it has the error mesage 101 check disc space i have 85 gig free