Questions
6.6 Parsing strings (Java) (1) Prompt the user for a string that contains two strings separated...

6.6 Parsing strings (Java)

(1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)

  • Examples of strings that can be accepted:
  • Jill, Allen
  • Jill , Allen
  • Jill,Allen

Ex:

Enter input string: Jill, Allen

(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings. (2 pts)

Ex:

Enter input string: Jill Allen

Error: No comma in string

Enter input string: Jill, Allen

(3) Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings. (2 pts)

Ex:

Enter input string: Jill, Allen

First word: Jill

Second word: Allen

(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit. (2 pts)

Ex:

Enter input string: Jill, Allen

First word: Jill

Second word: Allen

Enter input string: Golden , Monkey

First word: Golden

Second word: Monkey

Enter input string: Washington,DC

First word: Washington

Second word: DC

Enter input string: q

********must use this as part of the solution:

import java.util.Scanner;

public class ParseStrings {

   public static void main(String[] args) {

/* Type your code here. */

Scanner scnr = new Scanner(System.in);

String lineString = "";

String firstName;

String lastName;

boolean inputDone;

System.out.println("Enter input string: ");

lineString = scnr.nextLine();

while (lineString.indexOf(',') == -1){

   System.out.println("Error: No comma in string");

   System.out.println("Enter input string: ");

   lineString = scnr.nextLine();

inSS = new Scanner(userInfo);

      // Parse name and age values from string
      firstName = inSS.next();
      lastName = inSS.next();

}

      return;

   }

In: Computer Science

Part (a): Computing odd parity Digital-communication hardware and software often include circuitry and code for detecting...

Part (a): Computing odd parity

Digital-communication hardware and software often include circuitry and code for

detecting errors in data transmission. The possible kinds of errors are large in

number, and their detection and correction is sometimes the topic of upper-level

Computer Science courses. In a nutshell, however, the concern is that bits sent by a

data transmitter are sometimes not the same bits that arrive at the data receiver.

That is, if the data transmitter sends this word:

0x00200020

but this is received instead:

0x00204020

then the data receiver has the wrong data, and would need some way to determine

that this was the case. In response to the error, the same receiver might discard the

word, or ask the sender to retransmit it, or take some other combination of steps.

A technique for detecting one-bit errors is to associate with each word a parity bit . If

an odd parity bit is transmitted along with the word, then the number of all set bits in

the word plus the value of the parity bit must sum to an odd number . In our example

above involving the data transmitter, the chosen parity bit would be 1 (i.e., two set

bits in 0x00200020 , plus one set parity bit, equals three set bits). The data receiver

has the corrupted byte as shown ( 0x00204020 ) plus the parity bit value, and

determines that the number of set bits is four(i.e., three bits in the word, plus the set

parity bit, resulting in four set bits, which is an even number). Given that four is not

an odd number, the receiver can conclude there was an error in transmission. Note

that the receiver can only detect an error with the parity bit; more is needed to

correct the error. (Also notice that if two bits were in error, then our scheme would

not detect this event.)

Your main task for part (a) is to complete the code in the file named parity.asm

that has been provided for you. You must also draw by hand the flowchart of your

solution and submit a scan or smartphone photo of the diagram as part of your

assignment submission; please ensure this is a JPEG or PDF named

“ parity_flowchart.jpg ” or “ parity_flowchart.pdf ” depending on the file

format you have chosen.

Some test cases are provided to you.

# Compute odd parity of word that must be in register $8
# Value of odd parity (0 or 1) must be in register $15


.text

start:
        lw $8, testcase1  # STUDENTS MAY MODIFY THE TESTCASE GIVEN IN THIS LINE
        
# STUDENTS MAY MODIFY CODE BELOW
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

        nop
        addi $15, $0, -10


# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# STUDENTS MAY MODIFY CODE ABOVE


exit:
        add $2, $0, 10
        syscall
                

.data

testcase1:
        .word   0x00200020    # odd parity is 1

testcase2:
        .word   0x00300020    # odd parity is 0
        
testcase3:
        .word  0x1234fedc     # odd parity is 0

In: Computer Science

Please provide assistance to fix the segmentation fault error I am receiving and solve the following...

Please provide assistance to fix the segmentation fault error I am receiving and solve the following problem I am working on:

My goal is to build a Trie data structure in C++ that can do the following:

- Capable to insert any given dictionary .txt file filled with a single word per line (i.e. file includes ant, bat, car, desk, etc.) into the Trie. A sample dictionary file that I'm working with can be found at http://txt.do/1pht5

- Prompts the user to input some prefix search and provides an autocomplete suggestion (i.e. file includes bat, bar, bass, and user inputs ba which should suggest bat, bar, bass, etc.)

- Lastly, if the user inputs a prefix search that is not within the Trie, it will recommend the top 3 most similar entries in the Trie (i.e. user prefix input is baq which is not part of the dictionary txt file but bat, bar, bass are which should be suggested)

I have been able to write the following code so far but I'm having difficulties in fixing the segmentation error and making it run.

#include<bits/stdc++.h>
#define alphabet_size 26
using namespace std;

class TrieNode {
    public:
    TrieNode* children[alphabet_size];
    bool endofLeaf;
    
    TrieNode(){
        for(int i = 0; i < alphabet_size; i++)
            children[i] = NULL;
            endofLeaf = false;
    }        
};

class Trie {        
    public:
        TrieNode* root;
        Trie() {root = new TrieNode();}      
        void Dict_insert(string word){
            TrieNode* temp = root;
            for(int i = 0; i < word.length(); i++){
                if(temp->children[word[i]-'a'] == NULL){
                    temp->children[word[i]-'a'] = new TrieNode(); 
                }
                temp = temp->children[word[i]-'a'];        
            }
            temp->endofLeaf = true;
        }

        bool search (string word){
            TrieNode* tmp = root;
            for(int i = 0; i < word.size(); i++)
            {
                if(tmp->children[word[i]-'a'] == NULL){
                    return false;
                }
                tmp = tmp->children[word[i]-'a'];
            }
            return tmp;
        }

        void auto_recommendation(string word){
            TrieNode* autorec = root;
            if(autorec->endofLeaf == true)
                cout << word << endl;
            for(int i = 0; i < alphabet_size; i++){
                if(autorec->children[i] != NULL){ 
                    word.push_back((char)i); 
                    auto_recommendation(word); 
                    word.pop_back(); 
                }
            }
        }
};

int main(){
    Trie* t = new Trie();    
    fstream dictionaryfile;
    dictionaryfile.open("Dictionary.txt",ios::in);  
    if (dictionaryfile.is_open()){ 
        string DictEntry;
        while(getline(dictionaryfile, DictEntry)){ 
            t->Dict_insert(DictEntry);
        }
    dictionaryfile.close(); 
    } 
    string searchQuery;
    cout << "Type in a search: " << endl;
    getline(cin,searchQuery); 
    cout << "/nDid you mean: \n" << endl;
    t->search(searchQuery);
    if (t->search(searchQuery) == false)
        /* Call a recommendation search function which recommends the top 3 most similar entries within the Trie*/
        cout<<"Did you mean:\n";
        //cout top 3 most similar entries within the Trie
    else
        t->auto_recommendation(searchQuery);
    return 0;
}

In: Computer Science

Please Write C++ PROGRAM : That will write a program that initially prompts the user for...

Please Write C++ PROGRAM :

That will write a program that initially prompts the user for a file name. If the file is not found, an error message is output, and the program terminates. Otherwise, the program prints each token in the file, and the number of times it appeared, in a well formatted manner. To accomplish all this, do the following:

- Open the file - the user must be prompted and a file name input. DO NOT hardcode a file name.

- Read the words in the file, placing them in an array of struct with capacity I 00, where each struct has a string (the word) and an int (number of occurrences)

- Sort the array, eliminating duplicates

- Report the results

- You must write appropriate functions for each task. At minimum, you must write a function for each of the following:

• Open the file:

o    Pass in an ifstream (must be a reference argument [what type of parameter is it?]). The function prompts the user and, if the file is found, it returns true and the ifstream will be a handle for that text file. Otherwise the function returns false , and the argument is assumed to be undefined.

• Populate the array of struct with the words in the file:

o    Pass in two reference arguments, the ifstrcam, and the l 00 element array of word/count structs. When the function completes, the array will hold the words in the file.

• Output results:

o    Pass in the variables that bold the file name and the word/count array. Use this data to

produce the desired ouput, which should be appropriately fonnatted.

• Sort an array of structs (the name/int pairs), eliminating duplicates:

o    Pass in the array of struct, and the number of elements in the array. The function sorts the array, in ascending order of words, eliminating duplicates and tabulating counts as it goes. It definitely uses other functions for specific purposes, e.g. identifying duplicate tokens and swapping structs.

• Increment the counter member of a struct that holds a word and its multiplicity:

o    Pass in a single struct; it will be an import/export parameter. Simply increment its counter member.

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

Notes:

» A word, or token, is whatever is read using the >> operator. A word followed by a period is distinct from the same word without the period. Words are also case sensitive, i.e. heLLo is not equal to Hello.

» When a word is placed into the array of struct, its counter is initially 1.

» When the array reaches capacity:

If there aren't 100 unique words already in the array, run the sort function to eliminate duplicates.

If the file has 100 unique words, then after the tooth unique word is added to the array, only repeats will be tabulated. New tokens will be discarded.

» While several functions are required, other functions should be written as well.

No function..should handle multiple tasks on its own. Non-modular designs will be penalized.

» In sorting, if the word being placed is a duplicate, the already placed word must have its counter incremented, and the duplicate must be removed from the array.

- The program must be well written, properly indented, and commented

In: Computer Science

Please answer the following questions in your own word 250 word count What competencies were you...

Please answer the following questions in your own word 250 word count

What competencies were you able to develop in researching and writing the course comprehensive project about healthcare? How did you leverage knowledge gained in the assignments in completing the comprehensive project? How will these competencies and knowledge support your career advancement in Healthcare management?

In: Nursing

This is the code that needs to be completed... import java.util.ArrayList; import java.util.Collections; /** * Write...

This is the code that needs to be completed...

import java.util.ArrayList;
import java.util.Collections;

/**
* Write a description of class SpellChecker here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class SpellChecker
{
private ArrayList words;
private DictReader reader;
/**
* Constructor for objects of class SpellChecker
*/
public SpellChecker()
{
reader = new DictReader("words.txt");
words = reader.getDictionary();
}

/**
* This method returns the number of words in the dictionary.
* Change this.
*/

public int numberOfWords()
{
return 0;
}

/**
* This method returns true, if (and only if) the given word is found in the dictionary.
* Complete this.
*/
public boolean isKnownWord(String word)
{
return false;
}
  
/**
* This method returns true if (and only if) all words in the given wordList are found in the dictionary.

// Complete this.

*/
public boolean allKnown(ArrayList wordList)
{
return false;
}
  
/**
* This method tests the allKnown method. You do not need to change this method.
*/
public boolean testAllKnown()
{
ArrayList testWords = new ArrayList();
testWords.add("Abu");
testWords.add("Chou");
if(allKnown(testWords))
{
return true;
}
else
{
return false;
}
  
}
  
/**
* This method returns a list of all words from the dictionary that start with the given prefix.
* Complete this.
*/
public ArrayList wordsStartingWith(String prefix)
{
return null;
}
  
/**
* This method returns a list of all words from the dictionary that include the given substring.
* Complete this.
*/
public ArrayList wordsContaining(String text)
{
return null;
}
  
/**
* Insert the given word into the dictionary.
* The word should only be inserted if it does not already exist in the dictionary.
* If it does, the method does nothing.
* Make sure that the alphabetic order of the dictionary is maintained.
* Complete this.
*/
public void insert(String newWord)
{
  
}
  
/**
* Remove the given word from the dictionary.
* If the word was successfully removed, return true.
* If not (for example it did not exist) return false.
*/ Complete this.
public boolean remove(String word)
{
return false;
}
  
  
/**
* Save the dictionary to disk.
* This is not meant to be hard – there is a method in the DictReader class that you can use.
* Complete this
*/
public void save()
{
  
  
}
  
}

And this is the other class that is completed but helps run the incomplete code above.

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


/**
* Class DictReader offers functionality to load a dictionary from a file,
* and to save it back to a file.
*
* To use this class, create an instance of this class with the file name as
* a parameter. Then call 'getDictionary' to receive the dictionary object.
*
* @author M. Kolling
* @version 2006-10-24
*/
public class DictReader
{
private ArrayList dict;
private String filename;

/**
* Create a DictReader instance from a file.
*/
public DictReader(String filename)
{
loadDictionary(filename);
this.filename = filename;
}
  
/**
* Return the dictionary as a list of words.
*/
public ArrayList getDictionary()
{
return dict;
}

/**
* Accept a new dictionary and save it under the same name. Use the new
* one as our dictionary from now on.
*/
public void save(ArrayList dictionary)
{
try {
FileWriter out = new FileWriter(filename);
for(String word : dictionary) {
out.write(word);
out.write("\n");
}
out.close();
dict = dictionary;
}
catch(IOException exc) {
System.out.println("Error writing dictionary file: " + exc);
}
}

/**
* Load the dictionary from disk and store it in the 'dict' field.
*/
private void loadDictionary(String filename)
{
dict = new ArrayList();
  
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String word = in.readLine();
while(word != null) {
dict.add(word);
word = in.readLine();
}
in.close();
}
catch(IOException exc) {
System.out.println("Error reading dictionary file: " + exc);
}
}
}

In: Computer Science

Write an essay about bacteria (400 word). Use your own words. Essay should continue introduction, body...

Write an essay about bacteria (400 word). Use your own words. Essay should continue introduction, body (3 paragraphs),and conclusion.

Please send me a soft copy to my email ( Microsoft word document)

In: Biology

Write a class to accept a sentence from the user and prints a new word in...

Write a class to accept a sentence from the user and prints a new word in a terminal formed out of the third letter of each word. For example, the input line “Mangoes are delivered after midnight” would produce “neltd”.

Program Style : Basic Java Programming

In: Computer Science

In python Using the example code from the HangMan program in our textbook, create a Word...

In python Using the example code from the HangMan program in our textbook, create a Word Guessing Game of your choice. Design a guessing game of your own creation. Choose a theme and build your words around that theme. Keep it simple.

Note: I would highly recommend closely reviewing the HangMan code and program from Chapter 10 before starting work on this project. You can run the program via my REPL (Links to an external site.).

Using python Similar to our Number Guessing game, be sure to allow the player the option to keep playing and keep score. You can design the game however you see fit but it must meet these requirements:

General Requirements

  • Remember to comment your code - include your name, date, class, and assignment title.
  • Provide comments throughout your program to document your code process.
  • Create a greeting/title to your program display output.
  • Your program should ask the player if they wish to play again.
  • Be creative! Have fun with this. Don't overthink it.

Word lists

  • You must have wordlists totaling at least 30 words to select from divided into themes or topics that you have identified. For example, say your words are all related to United States state names and world country names. You might choose to have one list named statelist and one list named countrylist. Each list might contain 15 words. Break these themes/topics into whatever works best but be sure to have at least a total of 30 words to work from.
  • Your game should randomly choose one of the words in the wordlists.

Output in python test and paste code

  • The player should be given the theme/topic of the word.
  • The player should be told how many letters the word contains.
  • The player should be shown a list of the letters that they have guessed already.
  • Output the correct guesses and location of the letters in the word. For example say the word is banana. The user has guesses the letter A as their first guess. Your output will display something like _ a _ a _ a so that the player can guess the word.
  • Your program should keep score of wins/losses and display them to the player.

Guesses in python code show

  • The player should be given ten guesses. *Note depending on the complexity of your theme/topic area you may wish to modify the maximum guesses.
  • The program should ask for a letter guess. Validate that the player inputs only 1 letter in their guess. Handle other inputs with feedback and a request to try again.
  • Your program should REMOVE the word they just played from the wordlist so they do not get the same word twice.

Think the program through

Break this down into smaller sized concepts first. Walk through the program functions step by step. Here is some of my thought processes to get you started. Thank you for helping me

  • First create your word lists and organize them by theme/topic. Maybe I want my game to be "Things You Find in a Grocery Store" and I will have 3 lists - fruits, vegetables and proteins. I will create each of my list structures and come up with 10 words for each list. fruits =["banana", "apple", "grapes", "orange", "pear", "peach", "plum"] etc.
  • Then I will try to randomly select an index from my list. I can use the random module to help me and get a value between 0 and the length of the list -1 (to take into account that the index starts at 0).
  • Once I have that part of the program working, I would celebrate my win and take a little break.
  • Next, I will store the random word from my list to a variable so that I can compare the input guesses against that word. This is where I will need to make use of string functions from Chapter 10 and use the Hangman code for inspiration.
  • I would use string functions like find() to search and find if the letter guess found a match.
  • If a match was found, I would print out a message.
  • If a match wasn't found, I would print out a message, and store the guessed letter to a list.
  • I would then output the word with the correctly guessed letters in the position they should be in.
  • and so on... until the game worked and produced the correct output.


  • Here is the book hangman code to refere to:

    import wordlist

    # Get a random word from the word list
    def get_word():
    word = wordlist.get_random_word()
    return word.upper()

    # Add spaces between letters
    def add_spaces(word):
    word_with_spaces = " ".join(word)
    return word_with_spaces

    # Draw the display
    def draw_screen(num_wrong, num_guesses, guessed_letters, displayed_word):
    print("-" * 79)
    print("Word:", add_spaces(displayed_word),
    " Guesses:", num_guesses,
    " Wrong:", num_wrong,
    " Tried:", add_spaces(guessed_letters))

    # Get next letter from user
    def get_letter(guessed_letters):
    while True:
    guess = input("Enter a letter: ").strip().upper()
      
    # Make sure the user enters a letter and only one letter
    if guess == "" or len(guess) > 1:
    print("Invalid entry. " +
    "Please enter one and only one letter.")
    continue
    # Don't let the user try the same letter more than once
    elif guess in guessed_letters:
    print("You already tried that letter.")
    continue
    else:
    return guess

    # The input/process/draw technique is common in game programming
    def play_game():
    word = get_word()
      
    word_length = len(word)
    remaining_letters = word_length
    displayed_word = "_" * word_length

    num_wrong = 0   
    num_guesses = 0
    guessed_letters = ""

    draw_screen(num_wrong, num_guesses, guessed_letters, displayed_word)

    while num_wrong < 10 and remaining_letters > 0:
    guess = get_letter(guessed_letters)
    guessed_letters += guess
      
    pos = word.find(guess, 0)
    if pos != -1:
    displayed_word = ""
    remaining_letters = word_length
    for char in word:
    if char in guessed_letters:
    displayed_word += char
    remaining_letters -= 1
    else:
    displayed_word += "_"
    else:
    num_wrong += 1

    num_guesses += 1

    draw_screen(num_wrong, num_guesses, guessed_letters, displayed_word)

    print("-" * 79)
    if remaining_letters == 0:
    print("Congratulations! You got it in",
    num_guesses, "guesses.")   
    else:
    print("Sorry, you lost.")
    print("The word was:", word)

    def main():
    print("Play the H A N G M A N game")
    while True:
    play_game()
    print()
    again = input("Do you want to play again (y/n)?: ").lower()
    if again != "y":
    break

    if __name__ == "__main__":
    main()

In: Computer Science

In a 500 word journal entry, describe the strategies used to prioritize organizational and community needs...

In a 500 word journal entry, describe the strategies used to prioritize organizational and community needs and resources for public health programs/initiatives.In a 500 word journal entry, describe the strategies used to prioritize organizational and community needs and resources for public health programs/initiatives.

In: Nursing