I am completing an assignment and am having a hard time figuring out the logic need to make the program work. I do not want a direct answer but could someone point me in the right direction?
Assignment:
Define a class named UnfairCandyDistributor. An UnfairCandyDistributor object represents a mean big brother who is going to divide a set of candies between himself and his hungry little brother. This will be done unfairly: for every candy given to the sibling, the big brother takes for himself a number of additional candies equal to the younger sibling's total. Each UnfairCandyDistributor object should have the same method:
public void nextCandy()
Each time nextCandy is called, the method prints a message about who gets a candy. Each call to nextCandy produces a single line of output. This time the output is the following:
public class TestCandy2 {
public static void main(String[] args) {
UnfairCandyDistributor mean = new UnfairCandyDistributor();
mean.nextCandy(); // 1 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for me.
Here The class I have made so far:
public class UnfairCandyDistributor {
private int you;
private int me;
private int extra;
public void nextCandy()
{
if (you != me || extra != you - 1)
{
me++;
System.out.println(me + " for me");
}
else
{
you++;
System.out.println(you + " for you");
extra = 0;
}
}
}
Can't you just add a boolean variable that tells you who to dole out candy to?
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
for (int i=0; i<you; i++) {
System.out.println("one for me");
me++;
}
else
{
System.out.println("one for you");
you++;
}
candyToMe = !candyToMe;
}
}
or
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
System.out.println(you + " for me");
me += you;
}
else
{
System.out.println("1 for you");
you++;
}
candyToMe = !candyToMe;
}
}
..depending on whether you want the candies doled out one at a time or in hand-fulls where appropriate.
Related
I am trying to create java application.
It ask questions and have 4 choices for each question.
I want to count total right and wrong answers selected by the user.
I am using function like this-
public void checkAnswer(String choice)
{
int correctcount=0;
int wrongcount=0;
if(counter==1) {
if (choice.equalsIgnoreCase("a")) {
correctAnswerDisplay();
correctcount = correct count + 1;
} else {
wrongAnswerDisplay();
wrongcount = wroungcount + 1;
}
}
else if(counter==2) {
if (choice.equalsIgnoreCase("d")) {
correctAnswerDisplay();
} else {
wrongAnswerDisplay();
}
}
Basically I hardcoded answers for each question.
For e.g- For this question, correct answer is "A". so I said if its "a" call the correct answer function else wrong answer in question#1. Counter variable is to display next questions
How can i calculate total right and wrong answer of all question. I have allowed users to select another option if they answer wrong, so they don't get to next question until they select right answer. But every time when they select wrong answer counter will add more numbers it should allow only 1 addition and stop there.
Also, lets says i selected wrong answer, I won't get next question until i hit continue button, and continue button appears only when i select correct answer. So if i select wrong answer 2 times, counter will be 2. It should work as i select wrong answer even three times, total wrong answer count should be just 1. and person will always select correct answer once for each question because continue button doesn't appear until then. So it should not increase correct counter if wrong answer was selected first.
Sorry I am a new programmer. Please help.
package org.test.main;
import java.util.Scanner;
public class TestMain {
public int correctcount = 0;
public int wrongcount = 0;
public int counter = 1; // lets assume you have counter as 1 to start with
public void checkAnswer(String choice) {
if (counter == 1) {
if (choice.equalsIgnoreCase("a")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
} else {
wrongAnswerDisplay();
wrongcount = wrongcount + 1;
}
} else if (counter == 2) {
if (choice.equalsIgnoreCase("d")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
} else {
wrongAnswerDisplay();
wrongcount = wrongcount + 1;
}
}
}
private void wrongAnswerDisplay() {
System.out.println("Wrong");
}
private void correctAnswerDisplay() {
System.out.println("Correct");
}
public static void main(String[] args) {
TestMain testM = new TestMain();
Scanner scanNext = new Scanner(System.in);
for(int i = 0; i < 2;i++) {
System.out.print("Question#"+(i+1)+": ");
String ans = scanNext.nextLine();
testM.checkAnswer(ans);
testM.counter++;
}
System.out.println("Number of Correct Answer:" + testM.correctcount);
System.out.println("Number of Wrong Answer:" + testM.wrongcount);
}
}
Make your correctcount and wrongcount as instance variable. because every time you call the method checkAnswer(), 0 will be assigned in the 2 variables you created in your method.
I tried to simulate your logic. so try this. The numbers of question and the answers are hardcoded. so change it in your logic to be dynamic. I write this code to understand how the incrementation works.
It is a really good thing that you have started using communities like Stackoverflow.
Form the question it is clear that there is a continue button which will be enabled only if you select the correct answer. (Then there is no point in counting correct answers since with such a button, at the end you will have all the questions answered correctly. Anyway if you really want this logic to work try the following.)
Let's create a method incrementWrongCount() to increment the variable wrongcount.
public class AnswerTester{
int correctcount = 0;
int wrongcount = 0;
/*Following variable indicates whether you have selected any wrong answers before
selecting the right answer. Obviously its default value is false since you
have selected no wrong answers (in fact no answers) when you first
you first answers a question*/
boolean wronganswerselected = false;
public void checkAnswer(int counter, String choice){
if(counter==1) {
if (choice.equalsIgnoreCase("a")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
incrementWrongCount();
wronganswerselected = false;//For the next question
enableContinueButton();
} else {
wrongAnswerDisplay();
wronganswerselected = true;//just indicate that you have selected a wrong answer. We will increment wrong count in incrementWrongCount()
disableContinueButton();
}
} else if(counter==2) {
if (choice.equalsIgnoreCase("d")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
incrementWrongCount();
wronganswerselected = false;
enableContinueButton();
} else {
wrongAnswerDisplay();
wronganswerselected = true;
disableContinueButton();
}
}
}
private void incrementWrongCount(){
if(wronganswerselected){//Should increment wrongcount only if the user have selected atleast one wrong answer.
wrongcount = wrongcount + 1;
}
}
private void correctAnswerDisplay(){
System.out.println("Correct..");
}
private void wrongAnswerDisplay(){
System.out.println("Wrong..");
}
public int getCorrectCount(){
return correctcount;
}
public int getWrongCount(){
return wrongcount;
}
}
Its a good practice to use switch instead of if...else if to match a variable against multiple values.
// ************************************************************
// ELEVATOR.java
//
// ELEVAOTR SIMULATION
// PROBLEM: NEED TO FIND A WAY TO AMKE IT SO THAT THE PROGRAM KEEPS RNNING AFTER USER INPUTS
// THIER FIRST DESIRED FLOOR.
// ************************************************************
import java.util.*;
public class Elevator_Simulation {
public static void main (String[] args) {
Person User = new Person();
Floor floors = new Floor();
floors.moveElevator(User.getDesiredFloor());
}
}
class Elevator { //NEEDS SETTER & GETTER METHODS
private int mass=0;
private int capcity=0;
private String name="";
private String color="";
}
class Floor {
ArrayList<Object> floorLevel = new ArrayList<Object>();
Elevator Lift = new Elevator();
Person Man = new Person();
Floor() { //Floors 0-9
floorLevel.add(Lift); //0
floorLevel.add(null); //1
floorLevel.add(null); //2
floorLevel.add(null); //3
floorLevel.add(null); //4
floorLevel.add(null); //5
floorLevel.add(null); //6
floorLevel.add(null); //7
floorLevel.add(null); //8
floorLevel.add(null); //9
}
System.out.println("Elevator is at Floor: " + floorLevel.indexOf(Lift) );
public void moveElevator (int chosenFloor) {
if (chosenFloor > 9) {
System.out.println("Woooooah Buddy! You can only choose 0-9!");
return;
}
if (chosenFloor == floorLevel.indexOf(Lift)) {
System.out.println("Bro you're already on that floor...");
}
while (floorLevel.indexOf(Lift)>chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)-1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
while (floorLevel.indexOf(Lift)<chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)+1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
}
}
class Person {
Scanner scan = new Scanner(System.in);
public int getDesiredFloor() {
int desiredFloor = scan.nextInt();
return desiredFloor;
}
}
Above is an Elevator Simulator Code (before I attempt to make one with a GUI) and my only problem, aside from the obvious beginner flaws, is that I'm having trouble of finding a way to make it so that the program doesn't just end once the user inputs one floor. I at least want the program to run until the user ends it with a command. I'm thinking of using a while loop somewhere but where? Please help and point out anything I should improve in this code.
You can put the while loop around the line
floors.moveElevator(User.getDesiredFloor());
Just add an input check for a value that represents exiting.
public void onResult(QuestionAdResult questionAdResult) {
if (questionAdResult.wasCorrect()) {
// Additional Exp +5
// Additional HP +5
Hero.instance.earnExp(5);
Hero.instance.earnHP(5);
//
} else {
// Stuff
}
}
So I'm building a game and it has 2 methods.
Hero.instance.earnExp(5);
Hero.instance.earnHP(5);
I can uncomment either one for whichever specific action, but I'd like the actions to be random so it does either or, instead of having to comment one out. How would I go about it?
import java.util.Random;
public void onResult(QuestionAdResult questionAdResult) {
Random random = new Random();
int expOrHealth = random.nextInt(2);
if (questionAdResult.wasCorrect()) {
if (expOrHealth == 0)
{
// Additional Exp +5
}
if (expOrHealth == 1)
{
// Additional HP +5
}
Hero.instance.earnExp(5);
Hero.instance.earnHP(5);
//
} else {
// Stuff
}
}
I'm stuck on Task2 where i have to increment the counter of enemyships each time an enemy is created. I have created the enemey ships already and made the counter field static (i'm suppose to call the counter number)
The final solution should increment the counter of number enemyships which i need to declare a static field, the field should start at 0, when the first enemyship is created should increment this field to 1, second increment to 2 and so on, then you can use the value of this feild when printing the first line of output. that is for the first enemy, you should print "Enemy #1" second enemy should print "Enemy #2" and so on.
So this is what I tried from my Enemyship class:
public class EnemyShip
{
private int position;
private int velocity;
private int life;
private static int number = 0;
private boolean justHit;
public EnemyShip()
{
System.out.println("Enemy #1");
System.out.print("- Initial position: ");
position = Global.keyboard.nextInt();
System.out.print("- Initial velocity: ");
velocity = Global.keyboard.nextInt();
}
}
i made the public void increment method and tried to use this to increment but it didn't work. wondering if someone could help me explain how i can fix this problem and how to increment a variable in java.
thanks
public class Game {
private PlayerShip player;
private EnemyShip enemy1;
private EnemyShip enemy2;
private EnemyShip enemy3;
public Game() {
player = new PlayerShip();
enemy1 = new EnemyShip();
enemy2 = new EnemyShip();
enemy3 = new EnemyShip();
}
}
From the information you have provided, I understand you have to increment the value of counter everytime an enemy ship is created. So every time you call the constructor you should increment counter.So your increment function should look like this:
public void increment()
{
number = number + 1;
System.out.println("Enemy " + number + "#");
}
Why do you need an increment() method and why do you increment by 3 every time?
The number variable is static so you have access to it anywhere inside your class.
Use it and increment it in the Constructor.
public EnemyShip()
{
System.out.print("- Initial position: ");
position = Global.keyboard.nextInt();
System.out.print("- Initial velocity: ");
velocity = Global.keyboard.nextInt();
life = 10;
boolean justHit = false;
number++;
System.out.println("Enemy #" + number);
}
Every time you call
new EnemyShip();
you will see the statement
Enemy #[some number]
If you want to remember which EnemyShip has which number, you can add an instance field.
private int shipNumber;
public EnemyShip()
{
System.out.print("- Initial position: ");
position = Global.keyboard.nextInt();
System.out.print("- Initial velocity: ");
velocity = Global.keyboard.nextInt();
life = 10;
boolean justHit = false;
shipNumber = ++number;
System.out.println("Enemy #" + shipNumber);
}
This solution is dangerous in a multithreaded environment. I still don't know what your increment() method is for.
EDIT
You seem to be all over the place, lacking some bacis java knowledge of how classes work.
Read this and all of these.
Then run this code
public class EnemyShip {
private static int number = 0;
public EnemyShip() {
number++;
System.out.println("Enemy #" + number);
}
public static void main(String[] args) {
new EnemyShip();
new EnemyShip();
new EnemyShip();
}
}
It will output
Enemy #1
Enemy #2
Enemy #3
OP, you need to call the increment method from somewhere. The method won't run unless you call the method.
public class Game {
private PlayerShip player;
private EnemyShip enemy1;
private EnemyShip enemy2;
private EnemyShip enemy3;
public Game() {
player = new PlayerShip();
enemy1 = new EnemyShip(); EnemyShip.increment();
enemy2 = new EnemyShip(); EnemyShip.increment();
enemy3 = new EnemyShip(); EnemyShip.increment();
}
}
Should do better for you.
I'm a beginner/intermediate java programmer that is attempting to code something that is "out-of-my-league". The program is supposed to judge a boxing/MMA match in real time by pressing keys that correspond to different scoring values. I've figured out that I need a KeyListener, and the only way I've found to use that is with an applet.
The problem I've run into is the only cues I have to print out a score come from keyPresses and keyReleases. I want the score to print EVERY second, along with the time. I'm made a clock function and can print every second using another class with a main method, but I don't know how to do this in the applet.
Here's what I have so far:
import java.applet.Applet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.*;
public class KeyPressTwo
extends Applet
implements KeyListener{
private long t;
private ArrayList<Integer> keysDown = new ArrayList<Integer>();
private double controlOnlyValue = 1; //Stores the score per second for control only
private double threateningValue = 2.5; //Score for threatening with strikes, i.e. landing sig strikes, or sub attempts
private double damagingValue = 4; //Score for doing significant damage and dominating hea
private static double redTotal = 0; //Stores fighter score
private static double blueTotal = 0;
private static boolean firstRun = true;
private static boolean start = false;
private static boolean releasePressed = false; //Tells KeysReleased method when to wipe keysDown list
private static long roundBeganAt = 0; //System time when the round began 5
private static String redName;
private static String blueName;
public void init(){
this.addKeyListener(this);
//If names aren't hardcoded in, get them when the program is run
if (redName == null){
redName = JOptionPane.showInputDialog("Enter the red corner fighter's name.");
blueName = JOptionPane.showInputDialog("Enter the blue corner fighter's name.");
}
}
public void paint(){
setSize(500,500);
}
#Override
public void keyPressed(KeyEvent e) {
if(!keysDown.contains(e.getKeyCode()))
keysDown.add(e.getKeyCode());
//Starts the timer, don't print anything until started
if(keysDown.contains(KeyEvent.VK_SPACE)){
start = true;
roundBeganAt = System.currentTimeMillis();
}
//If it's been more than 1s
if(nextStep()){
//If space has been pushed
if(start){
if(keysDown.contains(KeyEvent.VK_Z) || keysDown.contains(KeyEvent.VK_NUMPAD1)){
redTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_X) || keysDown.contains(KeyEvent.VK_NUMPAD4)){
redTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_C) || keysDown.contains(KeyEvent.VK_NUMPAD7)){
redTotal += damagingValue;
}
if(keysDown.contains(KeyEvent.VK_COMMA) || keysDown.contains(KeyEvent.VK_NUMPAD3)){
blueTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_M) || keysDown.contains(KeyEvent.VK_NUMPAD6)){
blueTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_N) || keysDown.contains(KeyEvent.VK_NUMPAD9)){
blueTotal += damagingValue;
}
System.out.print("\n" +redName +": " +redTotal +" \t" +blueName +": " +blueTotal +"\t\t" +time());
releasePressed = true;
}
}
}
//Prints time since start (e.g. 2:05)
private static String time() {
String minutes = "";
String seconds = "";
int sRaw; //Gets time directly from system, will go above 60
int s; //Gets time from sRaw, (0 - 59)
sRaw = (int)((System.currentTimeMillis() - roundBeganAt))/1000;
s = sRaw%60;
minutes = Integer.toString(sRaw/60);
if(s < 10)
seconds = "0" +Integer.toString(s);
else seconds = Integer.toString(s);
return minutes +":" +seconds;
}
//Returns true if it's been more than1s since the last time it ran
public boolean nextStep() {
if(firstRun){
t = System.currentTimeMillis();
firstRun = false;
return true;
}
if(System.currentTimeMillis() > t + 1000){
t = System.currentTimeMillis();
return true;
}else
return false;
}
public void printList(){
for(int i : keysDown)
System.out.print(i +" ");
System.out.println();
}
#Override
public void keyReleased(KeyEvent e) {
if(releasePressed){
keysDown.clear();
releasePressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Maybe something along these lines would work for you:
Thread timerOutputThread = new Thread(new Runnable(){
public boolean running = true;
public void run(){
output();
}
private void output(){
try {
Thread.sleep(1000);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("PRINT THE SCORE HERE");
if(running){
output();
}
}
});
timerOutputThread.start();
Stick that code wherever you want the Thread timer to be started, and then fill in that spot where it says "PRINT THE SCORE HERE".
I've figured out that I need a KeyListener,.."
Or preferably key bindings.
..and the only way I've found to use that is with an applet.
Where on Earth did you hear that?!? It is definitely wrong. Start using a JFrame for this app. and it will work better because focus will be more reliable.