I need to create two class files for creating a multiplication table based upon what size the user specifies (<=15) and use the following for the assignment. I was on Thanksgiving Break and was not able to retrieve the instructions for creating the two classes so I wrote one program that prompts the user and now I am not sure how I can break that into two classes. One class is the Table, which specifies the table size and the other class is the Table App. Here are the instructions that I didn't have access to:
The smallest allowed table size is a 2x2 table; and the largest is a 15x15 table. The number of rows and columns will always be the same (i.e., the program won't create a 5x10 table).
It won't let me post a picture here but the table goes from 1 to 15 along the column headers which are separated by dashes. Then the row header is separated by dashes as it goes from 1 to 15
The number in each cell of the table is the product of the column heading above it, and the row label to its left. All of the numbers should be right-justified.
The table shall be generated by a class named Table. This class can consist of as many methods as you feel it appropriate to create, but must include at least the following:
(constructor)--Takes one input parameter: the size of the table. Valid values range from 2 to 15 (inclusive).
print---No input parameters and no return value. This is the method that will display the multiplication table.
printLine---Takes one input parameter: the number of dashes to print in line form. This is a helper method that you'll use from the print method. It is for creating the three horizontal lines in the table.
Without having the instructions I wrote the code to make the table a variable size and width based on the user input and did not make it inclusive to 2 to 15. I am still very new to Java and I was very proud of the code I wrote until I was able to get to the internet and see the instructions.
This is the code that I wrote and it creates the table but I can't get the dashes perfect like the picture and I did not create two class files..I just wrote it in one. Can someone please help me??
import java.util.Scanner;
public class Table {
private static Scanner s;
public static void main(String[] args)
{
s = new Scanner(System.in);
System.out.print("How big is the table: ");
int size = s.nextInt();
int formatStringLength = Integer.toString(size*size).length();
int axesFormatStringLength = Integer.toString(size).length();
String formatString = String.format("%%%ds", formatStringLength);
String axesFormatString = String.format("%%%ds",
axesFormatStringLength);
System.out.println();
System.out.println();
System.out.print("* | ");
for (int i = 1; i <= size; i++)
{
//System.out.print(i + " ");
System.out.printf(formatString + " ", i);
}
System.out.print("\n----");
//for (int i = 1; i <= size; i++)
for (int i = 1; i <= size*formatStringLength; i++)
{
System.out.print("--");
}
System.out.println();
for (int i = 1; i <= size; i++) {
System.out.printf(axesFormatString + " | ", i);
for (int j = 1; j <= size; j++) {
System.out.printf(formatString + " ", i * j);
}
System.out.println();
}
}
}
You should really follow instruction and make two classes. You need to create a class named Table then create a runnable application class to run use the Table class
Table.java
public class Table{
private int size;
// constructor
public Table(int size){
this.size = size;
}
public int getSize(){
return size;
}
public void print(){
// do some printing
printline(20);
// do some more printing
printline(20);
// do some more printing
printline(20);
// do some more printing
}
public void printLine(int dashes){
// loop to print number of dashes
}
}
TestTable.java Example run
public class TextTable{
public static void main(String[] args){
// create an instance of Table
Table table = new Table(5);
// print table
table.print();
}
}
This is a basic outline/template of what your code should look like, as per the instructions.
Related
I have participated in coding contest, where I have attempt the given problem, so I am supposed to come up with solution which should not only passing all the test cases, also well optimized in terms of time and space complexity, I have passed 3 out of 7 but I am still not able to identify the rest of the test cases, it is possible that I might be missing something, please help me to rectify the below problem statement.
PROBLEM STATEMENT:
The Powerpuff Girls (100 Marks)
Professor Utonium is restless because of the increasing crime in the world. The number of villains and their activities has increased to a great extent. The current trio of Powerpuff Girls is not well to fight the evils of the whole world. Professor has decided to create the maximum number of Powerpuff Girls with the ingredients he has.
There are N ingredients required in a certain quantity to create a Powerpuff Girl. Professor has all the N ingredients in his laboratory and knows the quantity of each available ingredient. He also knows the quantity of a particular ingredient required to create a Powerpuff Girl. Professor is busy with the preparations and wants to start asap.
The villains, on the other hand, want to destroy the laboratory and stop Professor Utonium from creating more Powerpuff girls. Mojo Jojo is coming prepared with ammunition and Him is leading other villains like Princess, Amoeba Boys, Sedusa, Gangreen Gang etc.
Professor does not have much time as villains will reach the laboratory soon. He is starting the process but does not know the number of Powerpuff Girls which will be created. He needs your help in determining the maximum number of Powerpuff Girls which will be created with the current quantity of ingredients.
Example:
Professor Utonium requires 3 ingredients to make Powerpuff Girls. The 3 ingredients are present in the laboratory in the given quantity:
To make a Powerpuff Girl, Professor Utonium requires:
3 units of Ingredient A
6 units of Ingredient B
10 units of Ingredient C
The maximum number of Powerpuff Girls that can be created is 3 as, after 3, Professor will run out of Ingredient C.
Can you determine the maximum number?
Input Format
The first line of input consists of the number of ingredients, N
The second line of input consists of the N space-separated integers representing the quantity of each ingredient required to create a Powerpuff Girl.
The third line of input consists of the N space-separated integers representing the quantity of each ingredient present in the laboratory.
Constraints
1<= N <=10000000 (1e7)
0<= Quantity_of_ingredient <= LLONG_MAX
Output Format
Print the required output in a separate line.
Sample TestCase 1
Input
4
2 5 6 3
20 40 90 50
Output
8
SOLUTION CODE
package com.mzk.poi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class PowerPuffGirls {
private static final String SPACE = " ";
private static final Integer INITAL_IDX = 0;
private static final Integer LOWER_IDX = 1;
private static final Integer SECOND_IDX = 2;
private static final Integer MAX_LINES = 3;
private static final Integer UPPER_IDX = 1000000;
private static String[] UnitsArr = null;
private static String[] totIngrdientsArr = null;
private static int size = 0;
public static void main(String[] args) {
List<Integer> maxPowerPuffGirlsCreationList = new ArrayList<Integer>();
Scanner stdin = new Scanner(System.in);
String[] input = new String[MAX_LINES];
try {
for (int i = 0; i < input.length; i++) {
input[i] = stdin.nextLine();
if (validateIngredienInput(input[INITAL_IDX])) {
System.exit(INITAL_IDX);
}
}
} finally {
stdin.close();
}
int numOfIngredients = Integer.parseInt(input[INITAL_IDX]);
String units = input[LOWER_IDX];
UnitsArr = units.split(SPACE);
String ingredients = input[SECOND_IDX];
totIngrdientsArr = ingredients.split(SPACE);
size = UnitsArr.length;
int[] specifiedArrayOfUnits = convertToIntegerArray(UnitsArr);
int[] totIngredientInLabArray = convertToIntegerArray(totIngrdientsArr);
for (int i = 0; i < size; i++) {
totIngredientInLabArray[i] = Integer.parseInt(totIngrdientsArr[i]);
}
for (int i = 0; i < numOfIngredients; i++) {
maxPowerPuffGirlsCreationList.add(totIngredientInLabArray[i] / specifiedArrayOfUnits[i]);
}
System.out.println(Collections.min(maxPowerPuffGirlsCreationList));
}
/**
* This method validates the first input
* #param noOfIngredients
* #return boolean
*/
private static boolean validateIngredienInput(String noOfIngredients) {
int numOfIngredients = Integer.parseInt(noOfIngredients);
boolean result = false;
if (numOfIngredients <= LOWER_IDX && numOfIngredients <= UPPER_IDX) {
result = true;
return result;
}
return result;
}
/**
* This utility method convert the String array to Integer array
* #param size
* #param specifiedArrayOfUnits
* #return int[]
*/
private static int[] convertToIntegerArray(String[] arrayToBeParsed) {
int array[] = new int[size];
for (int i = INITAL_IDX; i < size; i++) {
array[i] = Integer.parseInt(arrayToBeParsed[i]);
}
return array;
}
}
The above solution has passed 3 test cases, remaining 7 are un identfied,Please help me to rectify or improve this code.
There are several issues with your code:
try {
for (int i = 0; i < input.length; i++) {
input[i] = stdin.nextLine();
if (validateIngredienInput(input[INITAL_IDX])) {
System.exit(INITAL_IDX);
}
}
} finally {
stdin.close();
}
You don't need to check the first row each time you read one line from the input. Instead you run the test only once. You can run it once you read the first line or after you read the whole input. The code can be look like this:
for (int i = 0; i < input.length; i++) {
input[i] = stdin.nextLine();
}
if (!validateIngredienInput(input[INITAL_IDX])) {
System.exit(...);
}
Also, it is not clear what the return value of validateIngredienInput() means. Is true a correct input or is false? Your if() statements checks for the return value being true and quits if it is.
private static boolean validateIngredienInput(String noOfIngredients)
{
int numOfIngredients = Integer.parseInt(noOfIngredients);
boolean result = false;
if (numOfIngredients <= LOWER_IDX && numOfIngredients <= UPPER_IDX) {
result = true;
return result;
}
return result;
}
Your if() condition doesn't make any sense. You are checking if the number of different ingredients is <= 0 and <= 1. This also means that you could rewrite is as just if (numOfIngredients <= 0). But with the description above it is unclear if the validation should return true or false. Depending on what this method should do it can be written as:
private static boolean validateIngredienInput(String noOfIngredients)
{
int numOfIngredients = Integer.parseInt(noOfIngredients);
return numOfIngredients > 0;
}
This will return true if the value is greater than 0.
UnitsArr = units.split(SPACE);
Variable and field names should begin in lowercase, so they don't get confused with class names, which start in uppercase. It looks like UnitsArr is a class, but it is actually a field. So you should rename your field to unitsArr:
unitsArr = units.split(SPACE);
Also check the requirement/format of the input and the limits:
Constraints
1<= N <=10000000 (1e7)
0<= Quantity_of_ingredient <= LLONG_MAX
As you see the quantity of ingredient can be a long value, but you are using Integer.parseInt() and int[] arrays for storing the quantity. You must change this to long to read long values from the input.
int[] totIngredientInLabArray = convertToIntegerArray(totIngrdientsArr);
for (int i = 0; i < size; i++) {
totIngredientInLabArray[i] = Integer.parseInt(totIngrdientsArr[i]);
}
You are converting the String array to an int array with your helper method convertToIntegerArray(), but then you are doing it again with the for loop. You can skip one of the two.
You might also want to check at: What is a debugger and how can it help me diagnose problems?
I am writing a program which part is presented below:
public class Portal {
private String name;
private int[] positions; // positions of "ship"
private static int moves = 0; // moves made by player to sink a ship
public static int shot; // the value of position given by player
private int hits = 0; // number of hits
private int maxSize = 4; // max size of ship (the size will be randomized)
int first; // position of 1st ship block
int size; // real size of ship (randomized in setPortal method)
public void checkIfHit(){
for (int i : positions){
if (i == shot){
System.out.println("Hit confirmed");
hits++;
} else if (hits == positions.length){
System.out.println("Sunk");
} else {
System.out.println("Missed it");
}
}
moves++;
}
public void setPortal(){
size = 1 + (int)Math.random()*maxSize;
for (int i = 0; i < size - 1; i++){
if (i == 0){
positions[i]= 1 + (int)Math.random()*positions.length;
first = positions[i];
System.out.println(positions[i]);
continue;
}
positions[i]= first + 1;
System.out.println(positions[i]);
}
}
}
public class Main{
public static void main(String[] args){
// write your code here
Portal p1 = new Portal();
p1.setPortal();
}
}
code is split in two Java .class files.
The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0.
I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file).
What may be the cause of such issue?
It should properly throw an exception, because you forgot to initialize the integer array.
Have a look at this thread: Do we need to initialize an array in Java?
The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..
I am struggling with Arrays (java)
Since this is the first time to learn about java in my life, I have no idea how to start it. I have just learned how to declare arrays and so on. However, this is too complicated for me. I think I can get guidelines if I see this answer. Can anybody help me out?
the prog
Read the java.util.Scanner (API). Your code works. You can do what you want with the scores, just read them from the file and cast them to the appropriate data types (integers) for calculating average scores etc.
The variables are strings, so you must cast them to numbers to make your calculation.
You can use arraylist ArrayList<TeamMember> as an instance variable of TeamMembers for your Teams or a collection with primitive types for the team but I think best is if you make classes for Team, TeamMember and Score that you instanciate in your Bowling class. You can find this information anywhere.
import java.util.Scanner;
//...
Team usa = new Team();
Team mexico = new Team();
TeamMember person = new TeamMember(usa); //Harry plays for the US
...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
If you know that every third input is a score then you can check modulo 3 (% 3) to know which iteration is divisible by 3. .
I have done about 40% of your request, i think that's enough for you to go on. You should be able to finish it on your own.
If you have further question,just leave a comment.
( There are some hidden bugs for you,to handle it you should have an understanding of scope first, just for your learning. )
import java.io.*;
import java.util.*;
// declaration of the class
public class Bowling2 {
// declare arrays below
String Team, Member;
int Score, Scorew, Scoreb;
int[][] teamw = new int[10][3];
int[][] teamb = new int[10][3];
// declaration of main program
public static void main(String[] args) throws FileNotFoundException {
// 1. connect to input file
Scanner fin = new Scanner(new FileReader("bowling.txt"));
// 2) initialize array accumulators to zero
int i, j, Scoreb, Scorew = 0 ;
// 3) display a descriptive message
System.out.println(
"This program reads the lines from the file bowling.txt to determine\n"
+ "the winner of a bowling match. The winning team, members and scores\n"
+ "are displayed on the monitor.\n");
// 4) test Scanner.eof() condition
while (fin.hasNext()) {
// 5) attempt to input next line from file
Member = fin.next();
Team = fin.next();
Score = fin.nextInt();
// 6) test team color is blue
if (Team.toString() == "blue" ){
// 7) then store blue member and score
teamb[i][0] = Member;
teamb[i][1] = Team;
teamb[i][2] = Score;
// 8) increase blue array accumulator
sumArray("blue");
i++;
}
// 9) else store white member and score
else {
teamw[j][0] = Member;
teamw[j][1] = Team;
teamw[j][2] = Score;
// 10) increase white array accumulator
sumArray("white");
j++;
}
}
// 11) if blue team score is larger
// 12) then display blue team as winner
// 13) else display white team as winner
// 14 disconnect from the input file
fin.close();
}
// implement method `sumArray()` below
/* 1. initialize accumulator to 0
2. loop over initialized array indices
3. increase accumulator by indexed array element
4. return accumulator
*/
public double sumArray(string color) {
if (color == "blue") {
for (int k = 0;k < teamb.length(); k++) {
//do the calculation here, and return it
}
}else {
for (int h = 0;h < teamw.length(); h++) {
//do the calculation here, and return it
}
}
}
// implement method `printArray()` below
/* 1. display the team name as the winner
2. loop over initialized array indices
3. display member and score for that array index
*/
}
I need to set each TextField in my JFrame to the corresponding number in a pre-generated array of numbers but I do not know how.
This is what I need it to look like:
Here is the ActionListener Class that I am working with:
public class RandListener implements ActionListener
{
private final JTextField[] tF;
public RandListener(JTextField[] tF)
{
this.tF = tF;
}
#Override
public void actionPerformed(ActionEvent e)
{
int [] rArray = new int[10];
Random rNum = new Random();
for(int k = 0; k < rArray.length; k++)
{
rArray[k] = rNum.nextInt(100);
}
if(e.getActionCommand().equals("bRand"))
{
for(int k = 0; k < tF.length; k++)
{
tF[k].setText(/*I need to set the text of my TextFields to the numbers in the array*/);
}
}
if(e.getActionCommand().equals("bMaxMin"))
{
//I need to find the maximum and minimum of the Array here
}
}
}
Read up on how Strings in Java work. Basically, if you would want to turn the number into a string:
tF[k].setText(/*I need to set the text of my TextFields to the numbers in the array*/);
turns into:
tF[k].setText("" + rArray[k]);
I believe this is done automatically by Java; number boxing turns the primitive type into its respective wrapper (int -> Integer) and then then toString() is called on the Integer object which represents the primitive type.
Now, to find the minimum and maximum, you're going to have to think a little bit. This is an elementary problem companies will give to weed out bad candidates. Figure it out once on your own and you'll never forget it. Think of how you would do it as a human; you take the current biggest/smallest and compare it to whatever you're looking at currently.
assignment:
A school that your little cousin attends is selling cookies. If your cousin's class sells more cookies than any other class, the teacher has promised to take the whole class on a picnic. Of course, your cousin volunteered you to keep track of all the sales and determine the winner.
Each class is identified by the teacher's name. Each sales slip has the teacher's name and the number of boxes sold. You decide to create two parallel arrays: one to hold the teacher's names and one to record the number of boxes sold. Here is a sample of the data:
The first number gives the number of classes, and then a teacher's Name is followed by the number of boxes sold
15
Smith
3
Courtney
... so on so forth
My main issue (because i can just duplicate it for the "to-be" parrallel array)
is getting every other line to save into an array for the boxes sold
so array "boxSold"
would look like
[1] 15
[2] 3
package assignment5Package;
import java.util.Scanner;
import java.io.*;
public class assignment5Demo
{
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//create arrays, variables
Scanner keyboard = new Scanner(System.in);
BufferedReader input = new BufferedReader
(new FileReader ("/Users/lee/Desktop/class/cs 113/Assignment5/cookies.txt"));
System.out.println("How many sale slips are there");
int numSaleSlips = keyboard.nextInt();
int[] soldBox = new int[numSaleSlips];
//______String[] teacherName = new String[numSaleSlips];
int soldBoxIndex;
int teacherNameIndex;
//String soldBoxString; (line 50)
//initializing both strings to 0 and "_"
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
soldBox[soldBoxIndex] = 0;
}
//**for (teacherNameIndex = 0; teacherNameIndex < numSaleSlips; teacherNameIndex++)
//**{
//** teacherName[teacherNameIndex] = "_";
//**}
//reading from the cookies.txt file
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
System.out.println("Error at " + soldBoxIndex +".");
}
}
}
The following may be a quick-and-dirty solution, but will get the job done:
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
input.readLine(); //read the following line, but ignore its content, effectivly skipping the line
}
}
You might also need to work the numbers of the for-loop a bit, to accomodate the skipped line.