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
*/
}
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?
This is a program I'm writing for school, its a 2D array adventure game. I need help with the blank if statement. It needed to know if a valid direction was entered. I'm just not sure where to go from here. I also want to make it so there is an amount of keys to access the locked rooms. I'm not very talented at coding so this may seem messy, but I'ts the best I have. How can i do this?
package hauntedhouse;
import java.util.Scanner;
public class HauntedHouse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner c = new Scanner(System.in);
String room[][] = new String[2][2]; // allocate 2 dimensional array of strings
//This section of code fills the 2D array with room names
room[0][0] = "Entry Hall";
//code to fill the rest of the rooms here
room[1][0] = "Dining Room";
room[2][0] = "Master Bedroom";
room[0][1] = "Storage [locked]";
room[1][1] = "Grand Hall";
room[2][1] = "Bedroom";
room[0][2] = "Garage [locked]";
room[1][2] = "Back Door";
room[2][2] = "";
int x = 0; // the coordinates of the room to start
int y = 0;
String di = ""; // variable used to hold the direction they entered
System.out.println("Theres a secret in this house,");
System.out.println("go into the locked rooms to find");
System.out.println("out what it is, have these two keys!");
do {
System.out.println("You are now in the " + room[x][y]);
//this next loop will repeat until a valid direction is entered
while (true) //this loop continues until the "break" statement is executed
{
System.out.println("Enter your direction");
if () //figure this out!!
{
break; //exits while loop
}
} // end while (true)
if (di.equals("W"))
{
y = y+1;
} else if (di.equals("A")) {
x = x-1;
} else if (di.equals("S")) {
y = y-1;
} else if (di.equals("D")) {
x = x+1;
} else {
//an illegal direction has been entered
}
}
while (x>=2); }// end when you make it to the locked room SOMEHOW
} // TODO code application logic here
To validate a 2D array you can simply use .equals() function
String room [][] = new String [2][2];
room[0][0] = "Entry Hall";
if(room[0][0].equals("Entry Hall")){
System.out.println("Inside Entry Hall");
}
I have a project that is to create an array aRoad with a distinct length. I need to shift elements through this array and delete the object in the end, when it reaches the element just behind aRoad[N].
Let's suppose:
I have a number of objects ("cars") N and an array ("road") with the length L (=4).
i = 0: car1 is at road[0].
i = 1: car1 is at road[1].
i = 2: car1 is at road[2], car2 spawns at road[0].
i = 3: car1 is at road[3], car2 is at road[1].
i = 4: car1 vanishes from the road, car2 is at road[2], car3 spawns at road[0].
My Car-class:
package traffic;
public class Vehicle {
private int bornTime;
private char destination;
public Vehicle(int bornTime, char destination){
this.bornTime = bornTime;
this.destination = destination;
}
public int returnTime() {
return bornTime;
}
public char returnDest() {
return destination;
}
public String toString() {
System.out.print(destination);
return null;
}
}
My problem is: as soon as an object is leaving the array I get an error because the Index is out of Range. I tried to cover this with an IF-condition and thanks to the first answer I was able to create the code update.
How do I get a system, like that to run in Java? My updated approach:
public static void main(String[] args) {
int time = 1;
char[] aRoad = new char[6]; // lane length
Vehicle[] carList = {new Vehicle(1, 'X'), new Vehicle(4, 'Y')};
while(time < 15){
for(Vehicle car : carList){
if (car != null ){
int pos = time - car.returnTime();
if (pos >= 0){
if (pos >= 1){
aRoad[pos-1] = 0;
}
if (pos == (aRoad.length)){
aRoad[pos-1] = 0;
car = null;
}
if (car != null){
aRoad[pos] = car.returnDest();
}
}
}
}
//PRINT ARRAY EACH ITERATION, SET time = time + 1
}
The output looks like:
[...]
time = 6: [ , , Y, , , X]
time = 7: [ , , , Y, , ]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at traffic.Test1.main(Test1.java:19)
So my specific question is:
How do I prevent this exception without setting the X-object (-car) to null?
EDIT
Since the question was too unspecified I threw out all the useless information and tidied it up.
I will answer your most clear question, the answer to which should hopefully set you in the right direction.
but how do I actually create a lot of cars going down the road?
You may be getting stuck here because you haven't utilised your Vehicle object's borntime field. For each iteration of your while loop, a car's new position in the road should be be given by
current time - borntime
So if you have multiple cars and a while loop iterating over your time dimension
Vehicle car1 = new Vehicle(2, "X");
Vehicle car2 = new Vehicle(4, "Y");
...
int time = 2;
while(time < 10){
// calculate road positions
int car1Pos = time - car1.returnTime();
int car2Pos = time - car2.returnTime();
aRoad[car1Pos - 1] = 0;
aRoad[car1Pos] = car1.returnDest();
aRoad[car2Pos - 1] = 0;
aRoad[car2Pos] = car1.returnDest();
...
}
But whenever your code starts looking this repetitive its best to think in terms of more arrays and loops. Put the vehicles in a "Vehicle array" and loop over it to update each car's position in the array
Vehicle[] carList = {new Vehicle(2, "X"), new Vehicle(4, "Y")};
...
int time = 2;
while(time < 10){
for(Vehicle car : carList){
int pos = time - car.returnTime();
aRoad[pos-1] = 0;
aRoad[pos] = car.returnDest();
}
...
}
Once you have that working, the next step would be to dynamically add Vehicles to carList, perhaps every two seconds, and remove them from carList when they get to the end of the road. Using an ArrayList for your carList would be much easier for this part.
Note that I have not tested this code so their might be syntactic mistakes.
This is a modified example from the book, Head First Java. It's a kind of Battleship game where a 3 element array is being used as the battleship. The user has to guess these 3 locations. Currently, I've hard-coded the values of the ship location to 2,3,4. When the user guesses the correct location "Hit" is printed. If not then "Miss" is printed. If a user guesses all 3 locations then "Kill" is printed. But I have a problem. Currently if the user enters the same location multiple times, it still gives a hit. I tried to fix this by changing the value of a variable that has already been hit (int cell) to "-1". But for some reason this didn't fix it too. Please tell me what I am doing wrong.
public class Game {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] location = {2,3,4};
SimpleDotCom firstGame = new SimpleDotCom();
firstGame.setLocation(location);
firstGame.checkYourself("2");
firstGame.checkYourself("2");
//firstGame.checkYourself("2");
}
}
public class SimpleDotCom {
int [] loc = null;
int numOfHits = 0;
void setLocation (int [] cellLocation){
loc = cellLocation;
}
void checkYourself(String userGuess){
int guess = Integer.parseInt(userGuess);
String result = "Miss";
for(int cell:loc){
if (guess == cell){
result = "Hit";
numOfHits++;
cell = -1;
break;
}
if (numOfHits==loc.length){
result = "Kill";
}
}
System.out.print("Result: " + result);
System.out.println(" ** Num of Hits: " + numOfHits);
}
}
When you loop over loc, you get an int cell for each location. The problem is that that variable doesn't have any connection to the array, it's only a copy. If you change it, nothing's going to happen to the original array. I suggest looping over loc with a traditional for(;;) and using the current array index within the loop's logic to set the right "cells" to -1.
because you are assigning -1 to local variable. not updating in array actually
for(int cell:loc){ // cell is local copy of element in array is you have array of primitive int
if (guess == cell){
result = "Hit";
numOfHits++;
cell = -1;
break;
}
if (numOfHits==loc.length){
result = "Kill";
}
}
You can use traditional for loop for this or use List which has methods for adding removing elements.
You need to update the array at the correct index, not simply change the value of the cell variable, which only references the array element at the current iteration state.
You should probably use a traditionnal for loop for that, since you cannot get the index for free from an enhanced for loop.
for (int i = 0; i < loc.length; i++) {
//code...
loc[i] = -1; //instead of cell = -1;
}
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.