Questions
Create a subclass of BinaryTree whose nodes have fields for storing preorder, post-order, and in-order numbers....

  1. Create a subclass of BinaryTree whose nodes have fields for storing preorder, post-order, and in-order numbers. Write methods preOrderNumber(), inOrderNumber(), and postOrderNumbers() that assign these numbers correctly. These methods should each run in O(n) time.

In: Computer Science

In this task you will complete the calculation and implement the Clear button. 1. When an...

In this task you will complete the calculation and implement the Clear button.

1. When an arithmetic operator is pressed retrieve the String from the JLabel, parse it to a Float value and assign it to a variable num1. Consult the Java API and the textbook to workout how to convert a String to a Float. Hint: use the same structure as when we convert a String to an Integer.

2. You should retrieve the operator and store it in a char variable op.

3. Follow the same procedure as before to input the second number. When the user presses the equals button retrieve the String from the label and assign the Float to a variable num2. Calculate the result and display it on the JLabel.

4. To complete the calculation define a private float method called calculate that accepts 3 parameters (char op, float num1, float num2). Use a switch statement to determine what operation to do and then return the result from the calculation.

5. Finally, if the user presses the Clear button then set num1 and num2 to 0 and set the text of the JLabel to 0.

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
/*
* Driver Class for the Calcultor
*
* @author
*/
public class CalculatorDriver {
public static void main(String[] args) {
// create JFrame object
JFrame frame=new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create object of CalculatorPanel class
CalculatorPanel panel=new CalculatorPanel();
frame.getContentPane().add(panel); // add panel into frame
frame.pack();
frame.setResizable(false); // frame should not be resizable
frame.setLocation(400,300); // set location of frame
frame.setVisible(true); // make frame visible
}
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
* The calculator panel
* @author
*/
public class CalculatorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final int CALC_WIDTH=250;
private static final int CALC_HEIGHT=225;

public CalculatorPanel() {
setLayout(new BorderLayout());
setBackground(Color.lightGray); // create the input/output panel
result = 0; // result variable of label
lastCommand = "=";
start = true;

// add the display
resultLabel = new JLabel("0", SwingConstants.RIGHT); // set the JLabel to RIGHT
resultLabel.setFont(new Font("Helvetica", Font.BOLD, 40)); // set the font size
add(resultLabel, BorderLayout.NORTH); // set the border layout to NORTH

// Action listener creates
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();

// CREATE A LAYOUT OF THE BUTTONS 4X4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4)); //set the 4x4 grid
panel.setBackground(Color.DARK_GRAY); //set the background color

// add the button text and assign the action
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
  
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
  
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);

addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
  
add(panel, BorderLayout.CENTER); // set the panel to center
}
  
// add button
private void addButton(String label, ActionListener listener) {
JButton button = new JButton(label);
button.setPreferredSize(new Dimension(55,30)); //set the button size
button.setFont(new Font("Helvetica", Font.BOLD, 15)); // set the font size
button.setForeground(Color.BLUE); //set the font color to blue
button.addActionListener(listener); // add the action listener
panel.add(button); // add the button to the panel
}

  
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
resultLabel.setText("");
start = false;
}
resultLabel.setText(resultLabel.getText() + input); //display the text to the label
}
}


private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();

if (start) {
if (command.equals("-")) {
resultLabel.setText(command);
start = false;
} else
lastCommand = command;
} else {
calculate(Double.parseDouble(resultLabel.getText()));
lastCommand = command;
start = true;
}
}
}

// method that calculate the result of two inputs
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x; // add
else if (lastCommand.equals("-"))
result -= x; // subtract
else if (lastCommand.equals("*"))
result *= x; // multiply
else if (lastCommand.equals("/"))
result /= x; // divide
else if (lastCommand.equals("="))
result = x; // equals
resultLabel.setText("" + result); // display the result to the label
}

//variables
private JLabel resultLabel;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}



  
  
/**
* Define the calculate method
* Perform the calculations on <i>num1</i> and <i>num2</i> depending on
* the operation <i>op</i>
* @param op the operation
* @param num1 the first number of the calculation
* @param num2 the second number of the calculation
* @return the result of the calculation
*/

Hello, I need a help for this section... Could you please resolve it? I need a code. It's java.

Thanks a lot!

In: Computer Science

1.Write a Java program that prompts the user for a month and day and then prints...

1.Write a Java program that prompts the user for a month and day and then prints the season determined by the following rules.

If an invalid value of month (<1 or >12) or invalid day is input, the program should display an error message and stop. Notice that whether the day is invalid depends on the month! You may assume that the user will never enter anything other than integers (no random strings or floats will be tested.)

Tips: Break this problem down into smaller pieces. This is always good practice when tackling a larger problem. Break it up into pieces that you can test individually and work on one piece at a time. You might try writing the pseudo-code for each piece.

First, see if you can get a month and ensure that it is valid. Test out only this piece of functionality before continuing. Make sure you test not only the good and bad cases, but also for boundary cases. For example, try entering -5, 0, 1, 4, 12, 13, and 56.

Next, see if you can get a day and ensure that it is valid. Test this piece too.

Finally, use the now-valid month and day to determine which season it is in. If you tested the earlier pieces, you will now know that any bugs are due to a problem here.

In: Computer Science

Objectives: • Learn to write test cases with Junit • Learn to debug code Problem: Sorting...

Objectives:

Learn to write test cases with Junit

Learn to debug code

Problem: Sorting Book Objects

Download the provided zipped folder from Canvas. The source java files and test cases are in

the provided

folder. The Book class models a book. A Book has a unique id, title, and author.

The BookStore class stores book objects in a List, internally stored as an ArrayList. Also, the

following methods are implemented for the BookStore class.

addBook(Book b):

sto

res the book in the book list.

getBookSortedByAuthor():

returns a book list sorted by author name descending

alphabetically.

getBooksSortedByTitle():

returns a book listed sorted by title descending alphabetically.

getBooks():

returns the current book list

.

deleteBook(Book b5):

removes the given book from the book list.

countBookWithTitle(String title):

iterates through the book list counting the number of

books with the given title. Returns the count of books with the same title.

Write test cases to test t

he implementation.

The test case method stubs have been created.

Fill out the method stubs. After filling in the test case method stubs, run BookStoreTest to test

the BookStore.java code. Find and fix bugs in the BookStore.java code by using the debugger o

n

the test case method stubs.

Grade:

For this lab, we will need to see either

1)

Fully functional code solving the problem as specified or

Book.java


public class Book {

   private int id; // the unique id assigned to book
   private String title; // book title
   private String authorName;// author of the book

   public Book() {
       super();
   }

   public Book(int id, String authorName, String title) {
       this.id = id;
       this.title = title;
       this.authorName = authorName;
   }

   public int getId() {
       return id;
   }

   public void setId(int id) {
       this.id = id;
   }

   public String getTitle() {
       return title;
   }

   public void setTitle(String title) {
       this.title = title;
   }

   public String getAuthorName() {
       return authorName;
   }

   public void setAuthorName(String authorName) {
       this.authorName = authorName;
   }

   @Override
   public String toString() {
       return "\n Book [id=" + id + ", title=" + title + ", authorName="
               + authorName + "]";
   }

}

BookStore.java


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class BookStore {

   private List<Book> books; // store books in a list

   public BookStore() {
       books = new ArrayList<Book>();

   }

   public void addBook(Book b1) {
       books.add(b1);

   }

   public List<Book> getBooksSortedByAuthor() {
       List<Book> temp = new ArrayList<Book>(books);
       Collections.sort(temp, new Comparator<Book>() {
           public int compare(Book b1, Book b2) {
               return b1.getTitle().compareTo(b2.getAuthorName());
           }
       });
       return books;
   }

   public int countBookWithTitle(String title) {
       int count = 2;
       for (Book book : books) {
           if (book.getTitle() == title) {
               count++;
           }
       }
       return count;
   }

   public void deleteBook(Book b5) {
       books.remove(b5);
   }

   public List<Book> getBooks() {
       return books;
   }

   public List<Book> getBooksSortedByTitle() {
       List<Book> temp = new ArrayList<Book>(books);
       Collections.sort(temp, new Comparator<Book>() {
           public int compare(Book b1, Book b2) {
               return b1.getTitle().compareTo(b2.getAuthorName());
           }
       });
       return temp;
   }

}

BookStoreTest.java


import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;

public class BookStoreTest {

   private BookStore store;
   private Book b1 = new Book(1, "Harper Lee", "To Kill a Mockingbird");
   private Book b2 = new Book(2, "Harper Lee", "To Kill a Mockingbird");
   private Book b3 = new Book(3, "Frances Hodgson", "The Secret Garden");
   private Book b4 = new Book(5, "J.K. Rowling",
           "Harry Potter and the Sorcerer's Stone");
   private Book b5 = new Book(4, "Douglas Adams",
           "The Hitchhiker's Guide to the Galaxy");

   /**
   * setup the store
   *
   */
   @Before
   public void setUpBookStore() {
       store = new BookStore();
       store.addBook(b1);
       store.addBook(b2);
       store.addBook(b3);
       store.addBook(b4);

   }

   /**
   * tests the addition of book
   *
   */

   @Test
   public void testAddBook() {
       store.addBook(b1);
       assertTrue(store.getBooks().contains(b1));

   }

   /**
   * tests the deletion of book
   *
   */

   @Test
   public void testDeleteBook() {

   }

   /**
   * tests sorting of books by author name
   *
   */

   @Test
   public void testGetBooksSortedByAuthor() {

   }

   /**
   * tests sorting of books by title
   *
   */

   @Test
   public void testGetBooksSortedByTitle() {

   }

   /**
   * tests the number of copies of book in store
   *
   */

   @Test
   public void testCountBookWithTitle() {

   }

}

In: Computer Science

Create a program in Java for storing the personal information of students and teachers of a...

Create a program in Java for storing the personal information of students and teachers of a school in a .csv (comma-separated values) file.

The program gets the personal information of individuals from the console and must store it in different rows of the output .csv file.

Input Format

User enters personal information of n students and teachers using the console in the following

format:

n

Position1 Name1 StudentID1 TeacherID1 Phone1

Position2 Name2 StudentID2 TeacherID2 Phone2

Position3 Name3 StudentID3 TeacherID3 Phone3

. . .

Positionn Namen StudentIDn TeacherIDn Phonen


Please note that the first line contains only an integer counting the number of lines

following the first line.

In each of the n given input lines,

  • Position must be one of the following three strings “student”, “teacher”, or “TA”.

  • Name must be a string of two words separated by a single comma only.

  • StudentID and TeacherID must be either “0” or a string of 5 digits. If Position is “teacher”, StudentID is zero, but TeacherID is not zero. If Position is “student”, TeacherID is zero, but StudentID is not zero. If Position is “TA”, neither StudentID nor TeacherID are zero.

  • Phone is a string of 10 digits.


If the user enters information in a way that is not consistent with the mentioned format,

your program must use exception handling techniques to gracefully handle the situation

by printing a message on the screen asking the user to partially/completely re-enter the

information that was previously entered in a wrong format.



Data Structure, Interface and Classes

Your program must have an interface called “CSVPrintable” containing the following three methods:

  • String getName ();

  • int getID ();

  • void csvPrintln ( PrintWriter out);

You need to have two classes called “Student” and “Teacher” implementing CSVPrintable

interface and another class called “TA” extending Student class. Both Student and Teacher classes must have appropriate variables to store Name and ID.

In order to store Phone, Student class must have a phone variable of type long that can store a 10-digit integer; while the Teacher class must have a phone variable of type int to store only the 4-digit postfix of the phone number.

Method getName has to be implemented by both Student and Teacher classes in the same way. Class Student must implement getID in a way that it returns the StudentID and ignores the TeacherID given by the input. Class Teacher must implement getID in a way that it returns the TeacherID and ignores the StudentID given by the input. Class TA must override the Student implementation of getID so that it returns the maximum value of StudentID and TeacherID.

Method csvPrintln has to be implemented by Student and Teacher classes (and overridden by TA class) so that it writes the following string followed by a new line on the output stream out:

getName() + “,” + getID() + “,” + phone



Output .csv File

The program must store the personal information of students, teachers and TAs in a commaseparated values (.csv) file called “out.csv”. You need to construct the output file by repetitively calling the csvPrintln method of every CSVPrintable object instantiated in your program. The output .csv file stores the information of every individual in a separate row; while each column of the file stores different type of information regarding the students and teachers (i.e. Name, ID and phone columns). Please note that you should be able to open the output file of your program using MS-Excel and view it as a table.

Sample Input/Output

Assume that the user enters the following four lines in console:

Teacher Alex,Martinez 0 98765 3053489999

Student Rose,Gonzales 56789 0 9876543210

TA John,Cruz 88888 99999 1234567890

The program must write the following content in the out.csv file.

Alex Martinez,98765,9999

Rose Gonzales,56789,9876543210

John Cruz,99999,1234567890

In: Computer Science

How is a const pointer similar and different from a reference variable? And please give a...

How is a const pointer similar and different from a reference variable? And please give a good example.

Please help! Thank you!

In: Computer Science

C++ language Briefly explain and write the pseudocode to delete an element from the red-black tree....

C++ language

Briefly explain and write the pseudocode to delete an element from the red-black tree. Include all cases for full credit.

In: Computer Science

This is a question about C# programming: True / False questions: for (int i=5; i <...

This is a question about C# programming:

True / False questions:

for (int i=5; i < 55; i+=5)
{ decimal decPrcPerGal = decGalPrc + i;
decPayPrc = iBuyGall * decPrcPerGal;
if (decPrcPerGal > decMAX_GALPRC) { continue; }
if (decPrcPerGal > decMAX_GALPRC) { break; }
Console.WriteLine(" {1} gallon(s) at {0,3} would cost {2,8:$###,##0.00}", decPrcPerGal, iBuyGall, decPayPrc); }

In the code above:

1. If decGalPrc is 10.57 decPrcPerGal will always be some number of dollars and 57 cents   True/ False?
2. In some cases, the loop’s code block will run several times without showing anything on the console True/ False?
3. Removing only the code if (decPrcPerGal > decMAX_GALPRC) { continue; } would change the output of the program   True/ False?
4. Removing only the code if (decPrcPerGal > decMAX_GALPRC) { break; } would change the output of the program True/ False?
5. Removing the code if (decPrcPerGal > decMAX_GALPRC) { continue; } Would allow the program to avoid performing some unnecessary steps   True/ False?

In: Computer Science

In Java 1a. Declare a legal identifier for a variable called test as type double. 1b....

In Java

1a. Declare a legal identifier for a variable called test as type double.

1b. Create an if.. else statement that will display You get an A if grade is at least 95 else it will display Maybe you get an A next time

In: Computer Science

For this assignment, create a presentation in PowerPoint, or other presentation software, that discusses the following:...

For this assignment, create a presentation in PowerPoint, or other presentation software, that discusses the following:

A family member asks what kind of printer they should get for their home system. In a presentation, go over the different options they may have and how it would work for them. What questions should you ask them so you can formulate an adequate answer? Don't forget online options (cloud printing) for the answers you give. Also, give a best guess at cost for them to purchase and run the printer for a period of a year.

This assignment should be a minimum of 10 slides in length (not counting title or references slides)

In: Computer Science

try to find articles that deal with server roles and issues that came up when roles...

try to find articles that deal with server roles and issues that came up when roles were not properly assigned. You could also find some article that discusses any service that is worth running on a server to help administration or troubleshooting.

In: Computer Science

Given a memory address of 34Ah (10 bits) with 4 memory banks. Determine the memory bank...

Given a memory address of 34Ah (10 bits) with 4 memory banks. Determine the memory bank address and the address of the word in the bank using Low Order Interleaving (LOI).

In: Computer Science

C Programming Language Please Given a string S and keyword string K, encrypt S using keyword...

C Programming Language Please

Given a string S and keyword string K, encrypt S using keyword Cipher algorithm.

Note: The encryption only works on alphabets. Numbers and symbols such as 1 to 9, -, &, $ etc remain unencrypted.

Input:

    Zombie Here

    secret

    where:

  • First line represents the unencrypted string S.
  • Second line represents the keyword string K.

Output:

    ZLJEFT DTOT

Explanation: We used "secret" keyword there.

  • Plain Text: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z, When "secret" keyword is used, the new encrypted text becomes
  • Encrypting: S E C R T A B D F G H I J K L M N O P Q U V W X Y Z This means 'A' means 'S', 'B' means 'E' and 'C' means 'C' and so on.

In: Computer Science

Read the input one line at a time until you have read all lines. Now output...

Read the input one line at a time until you have read all lines. Now output these lines in the opposite order from which they were read..

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Part12 {
  
   /**
   * Your code goes here - see Part0 for an example
   * @param r the reader to read from
   * @param w the writer to write to
   * @throws IOException
   */
   public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
       // Your code goes here - see Part0 for an example
   }

   /**
   * The driver. Open a BufferedReader and a PrintWriter, either from System.in
   * and System.out or from filenames specified on the command line, then call doIt.
   * @param args
   */
   public static void main(String[] args) {
       try {
           BufferedReader r;
           PrintWriter w;
           if (args.length == 0) {
               r = new BufferedReader(new InputStreamReader(System.in));
               w = new PrintWriter(System.out);
           } else if (args.length == 1) {
               r = new BufferedReader(new FileReader(args[0]));
               w = new PrintWriter(System.out);              
           } else {
               r = new BufferedReader(new FileReader(args[0]));
               w = new PrintWriter(new FileWriter(args[1]));
           }
           long start = System.nanoTime();
           doIt(r, w);
           w.flush();
           long stop = System.nanoTime();
           System.out.println("Execution time: " + 1e-9 * (stop-start));
       } catch (IOException e) {
           System.err.println(e);
           System.exit(-1);
       }
   }
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Part0 {
  
   /**
   * Read lines one at a time from r. After reading all lines, output
   * all lines to w, outputting duplicate lines only once. Note: the order
   * of the output is unspecified and may have nothing to do with the order
   * that lines appear in r.
   * @param r the reader to read from
   * @param w the writer to write to
   * @throws IOException
   */
   public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
Set<String> s = new HashSet<>();

for (String line = r.readLine(); line != null; line = r.readLine()) {
s.add(line);
}

for (String text : s) {
w.println(text);
}
   }

   /**
   * The driver. Open a BufferedReader and a PrintWriter, either from System.in
   * and System.out or from filenames specified on the command line, then call doIt.
   * @param args
   */
   public static void main(String[] args) {
       try {
           BufferedReader r;
           PrintWriter w;
           if (args.length == 0) {
               r = new BufferedReader(new InputStreamReader(System.in));
               w = new PrintWriter(System.out);
           } else if (args.length == 1) {
               r = new BufferedReader(new FileReader(args[0]));
               w = new PrintWriter(System.out);              
           } else {
               r = new BufferedReader(new FileReader(args[0]));
               w = new PrintWriter(new FileWriter(args[1]));
           }
           long start = System.nanoTime();
           doIt(r, w);
           w.flush();
           long stop = System.nanoTime();
           System.out.println("Execution time: " + 1e-9 * (stop-start));
       } catch (IOException e) {
           System.err.println(e);
           System.exit(-1);
       }
   }
}


In: Computer Science

Write the steps to use the vi editor command to create myfile. Insert the following lines...

Write the steps to use the vi editor command to create myfile. Insert the following lines of text save and display the result to STDOUT with cat command. line 5 line 6 line 3 line 2

In: Computer Science