Question

Need help understanding this question from CodeStepByStep in Java, any help is appreciated! Write a method...

Need help understanding this question from CodeStepByStep in Java, any help is appreciated!

Write a method named coinFlip that accepts as its parameter a string holding a file name, opens that file and reads its contents as a sequence of whitespace-separated tokens. Assume that the input file data represents results of sets of coin flips. A coin flip is either the letter H or T, or the word Heads or Tails, in either upper or lower case, separated by at least one space. You should read the sequence of coin flips and output to the console the number of heads and the percentage of heads in that line, rounded to the nearest whole number. If this percentage is 50% or greater, you should print a "You win!" message; otherwise, print "You lose!". For example, consider the following input file:

H  T H  H    T
Tails taIlS   tAILs TailS heads   HEAds
   hEadS

For the input above, your method should produce the following output:

6 heads (50%)
You win!

The format of your output must exactly match that shown above. You may assume that the file contains at least 1 token of input, and that no tokens other than heads/tails or H/T will be in the lines. You may assume that the input file exists and is readable.

Constraints: Your solution should read the file only once, not make multiple passes over the file data.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

------------------------------------------------------------

Code

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.StringTokenizer;

public class Temp {

    

    

    public static void main(String[] args) {

        fun("sample.txt");

    }

    private static void fun(String fileName) {

        BufferedReader reader;

        int head=0,tail=0;

        try {

            reader = new BufferedReader(new FileReader(fileName));

            String line = reader.readLine();

            while (line != null) {

                StringTokenizer stk = new StringTokenizer(line);

                while(stk.hasMoreTokens()){

                    String tk = stk.nextToken();

                    if(tk.equalsIgnoreCase("heads") || tk.equalsIgnoreCase("H")){

                        head++;

                    }

                    else tail++;

                }

                line = reader.readLine();

            }

            reader.close();

            

            double hp = head*100.0/(head+tail);

            if(hp>=50.0)

                System.out.println(head+" heads ("+hp+"%) You win!");

            else{

                System.out.println(head+" heads ("+hp+"%) You Lose!");

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Add a comment
Know the answer?
Add Answer to:
Need help understanding this question from CodeStepByStep in Java, any help is appreciated! Write a method...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 2. . Write the function below per the docstring. A tuple is simply comma separated data....

    2. . Write the function below per the docstring. A tuple is simply comma separated data. In the function below, the tuple returned are 2 ints. def Htcounts (flips): "Given a list, flips, of H's and T's, returns a tuple of the number of H's and the number of T's, in that order. Uses 2 sum accumulators, one for number of heads, the other of the number of tails. Traverses the list, flips, with a for loop and uses booleans...

  • Write a program that simulates the toss of a coin. Whenever a coin is tossed the...

    Write a program that simulates the toss of a coin. Whenever a coin is tossed the result will be either a head or tail. Prompt the user as shown by entering an ‘H’ for heads or ‘T’ for tails. Use a loop for input validation of an ‘h’ or ‘t’. Make sure that both an upper case and lower case will be accepted. Have the computer generate a random number. Assign a char variable a (‘h’ ^ ’t’) head or...

  • Would you please do Pseudocode for this progarm in Java?? Using scanner algorithm, The scanner takes...

    Would you please do Pseudocode for this progarm in Java?? Using scanner algorithm, The scanner takes the name of a text file from the command line and prints out the list of tokens. If there is non-valid token in the input file, print out “error”. please help me to write Pseudocode! thank you!! The scanner takes the name of a text file from the command line. It outputs to the console error if there is any non-valid token in the...

  • Please Do it In Java: Objectives: To Java programming language To understand the lexical analysis phase...

    Please Do it In Java: Objectives: To Java programming language To understand the lexical analysis phase of program compilation Assignment: The first phase of compilation is called scanning or lexical analysis. This phase interprets the input program as a sequence of characters and produces a sequence of tokens, which will be used by the parser. Write a Java, program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described...

  • Please help me put this in order!! THANKYOU!! (CO 4 and 6) Create a program with...

    Please help me put this in order!! THANKYOU!! (CO 4 and 6) Create a program with a function named flipCoin that will flip a coin as many times as the user asks. The flipCoin function should return “heads” or “tails”. The program should continue while the user presses Y. SAMPLE OUTPUT: How many times do you want to flip a coin? 5 You got: tails You got: tails You got: tails You got: tails You got: heads To continue press...

  • Using c++ Write a function named coinToss that simulates tossing a coin. When you call the...

    Using c++ Write a function named coinToss that simulates tossing a coin. When you call the function it should generate and return a random number in the range 1 through 2. 1 represents heads and 2 represents tails. Exercise 1 (40 points) Write a function named coinToss that simulates tossing a coin. When you call the function it should generate and return a random number in the range 1 through 2.1 represents heads and 2 represents tails Use the function...

  • If i could get any guidance on how to get this started it will be great....

    If i could get any guidance on how to get this started it will be great. My prof. literally just gave us the information below (which are literally just instructions) and I am unsure on how to get started. For this assignment we are going to create a function that reads an input stream and classifies it into “tokens” from a language that we define here. In this language we make the following rules: ● An identifier is a letter...

  • (Microsoft Visual Source, C++, Course: CIS-5, Intro to Programming) Write a program that starts a player...

    (Microsoft Visual Source, C++, Course: CIS-5, Intro to Programming) Write a program that starts a player off with a bank of $15.00. A coin will flip and randomly choose heads or tails.The user will guess heads or tails to win. If the coin flip matches the player's guess his bet will be doubled. It costs 1 dollar to play and the program will bet that amount automatically each time as long as there is the available bank amount. Note: Do...

  • Write a complete Java program in a file caled Module1Progrom.java that reads all the tokens from...

    Write a complete Java program in a file caled Module1Progrom.java that reads all the tokens from a file named dota.txt that is to be found in the same directory as the running program. The program should ignore al tokens that cannot be read as an integer and read only the ones that can. After reading all of the integers, the program should print all the integers back to the screen, one per line, from the smalest to the largest. For...

  • For this assignment, you will use your knowledge of arrays and ArrayLists to write a Java...

    For this assignment, you will use your knowledge of arrays and ArrayLists to write a Java program that will input a file of sentences and output a report showing the tokens and shingles (defined below) for each sentence. Templates are provided below for implementing the program as two separate files: a test driver class containing the main() method, and a sentence utilities class that computes the tokens and shingles, and reports their values. The test driver template already implements accepting...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT