Jump to content

Problem with an exercise??

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
A.N.H

A.N.H

    Newbie

  • Members
  • Pip
  • 8 posts
Hey all, how are u!!?

While reading my book and answering some exercises i got stuck in this exercise, it kinda easy i just got stuck in a small part. anyways here is the question, for u guys who have Java How to program ( Deitel) its page 282 question 6.29

it basicly says that i have to stimulate a coin tossing app, that in the end calculates the average times the coin landed on its head and on its tail.

here is my code



import java.util.Scanner;

import java.util.Random;;



public class TossCoin 

{

	int NumTails = 0;

	int NumHeads = 0;

	int AverageHeads;

	int AverageTails;

	int Sum = NumTails + NumHeads;

	

	private double CalculateAverage( int x, int y)

	{

		return ( x / y);

	}

	

	private void ToToss()

	{

		Random randomnum = new Random();

		

		if ( randomnum.nextInt(1) == 0)

		{

			NumTails++;

		}

		else

		{

			NumHeads++;

		}

	}

	

	public void Tossed()

	{

		

		

		System.out.println("to stop tossing press <ctrl> z otherwise press any key");

		Scanner input = new Scanner ( System. in );

		

		

		if ( input.hasNext())

		{

			ToToss();

		}

		else

		{

			if ( Sum == 0)

			{

				System.out.println("Average is zero");

			}

			

			else

			{

			System.out.println("Average of Tails is");

			CalculateAverage( NumTails, Sum);

			System.out.println("Average of Heads is");

			CalculateAverage( NumHeads, Sum);

			}

		}

	}

}





now the problem is when i try to run it, and i press any key the program stops, but it is supposed to contenuie and stop only after i press ctrl and z, can someone help me please.

here is the main method if u wants it.




public class TossCoinTest 

{

	public static void main(String args[])

	{

		TossCoin tossed = new TossCoin();

		tossed.Tossed();

		

	}


}






#2
icepack

icepack

    Programmer

  • Members
  • PipPipPipPip
  • 115 posts
What would happen if you just removed the input scanner? i only skimmed through it, but do you ever take input from the keyboard?

ctrl z will stop whatever program from running regardless of whether or not the program is taking input.(at least in UNIX)

#3
A.N.H

A.N.H

    Newbie

  • Members
  • Pip
  • 8 posts
nvm i fixed the problem


i changed some of the code but it works now, plus the code is more elegant, i'll post the new code later.

thanks ice ;)