I have a table on a mySQL server that has data stored like this
Name Goal New Used Total Pace
Jill 5 6 1 7 0
Bob 5 2 3 5 0
Ann 5 1 2 3 0
It can have many more than that in it. What I need to do is read in the data from the mySQL server and load it into a 2D String array. I already know how to load sql data...the issue is I can not, for the life of me, figure out how to load it into the array.
After the data is loaded into the array, it will be sent off to a table to be loaded for viewing.
So basically the output of the array would need to be:
Jill 5 6 1 7 0
Bob 5 2 3 5 0
Ann 5 1 2 3 0
here is the code I have:
public String[][] fillInTableForStoreFromArchive(String Person, String DateTable) throws SQLException{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT * FROM `" +DateTable+ "` WHERE name = '" +Person+"'");
int rows = 0; //column number
int columns = 6; //row number
rows = getAmountOfSalesPeople(DateTable).length;
String[][] data = new String[rows][columns];
String name = null;
int goal = 0, New = 0, used = 0,total = 0,pace = 0;
while(rs.next()){
name = rs.getString("Name");
goal = rs.getInt("Goal");
New = rs.getInt("New");
used = rs.getInt("Used");
// total = rs.getInt("total");
// pace = rs.getInt("pace");
String[] mData = { name, new Integer(goal).toString(),
new Integer(New).toString(), new Integer(used).toString(),
new Integer(New + used).toString(),new Integer(pace).toString() };
for(int row = 0; row >data.length; row ++){
data[row] = mData;
}
}
for(int row = 0; row < data.length; row++){
for(int col = 0; col <data[row].length; col++){
System.out.print(data[row][col] + " ");
}
System.out.println();
}
return data;
}
Looking at your example I'll make the assumption that name is unique. Since you've got mixed types, Strings and ints, you can't put them all into one array unless you store the ints as Strings. One solution would be to make an Object that holds a name and its associated data...that is, after all, something one does in object oriented programming.
Barring that I would store the data in a Map, where name is the key and an int array is the value:
HashMap<String, int[]> myMap = new HashMap<String, int[]>();
String name;
int[] myData;
while(rs.next())
{
myData = new int[5];
name = rs.getString("Name");
myData[0] = rs.getInt("Goal");
myData[1] = rs.getInt("New");
myData[2] = rs.getInt("Used");
myData[3] = rs.getInt("total");
myData[4] = rs.getInt("pace");
myMap.put(name, myData);
}
It is then trivial to iterate over the map when needed (hint: use a Map.Entry<String, int[]>), such as in toString(). Arrays don't have "output" so you'll either need to use an object or a separate method to get the data formatted as needed.
Also, avoid variable names like New...no good can come of names that are the same as keywords yet capitalized differently.
Your problem is that youre trying to deal with array rows as independent entities, by setting a row ton other array...
... 2D arrays cannot be set at the "row" level - because they are not managed using row level pointers --- in order to set an 2D array row, you have to explicitly set and define the row and column 'for' each column in the row, in a proper "for" loop.
Once you have the mdata array you want to use it as one of the rows in data. Instead you are using a cycle and assigning to several positions.
You should use a counter to keep track of how many rows have you added and then use that counter to put mdata in the right position.
As a corolary to #Paul's solution you can describe your table in a class and access it through normal OO principle. That would completely eliminate the need for arrays.
Say for example :
public class Player {
private String name;
private int goal;
private int _new; //As #Paul pointed out you should not use reserved keywords
private int used;
private int total;
private int pace;
public Player(String name, int goal, int _new, int used, int total, int pace) {
this.name = name;
this.goal = goal;
this._new = _new;
this.used = used;
this.total = total;
this.pace = pace;
}
public String getName() {
return name;
}
public int getGoal() {
return goal;
}
public int get_new() {
return _new;
}
public int getUsed() {
return used;
}
public int getTotal() {
return total;
}
public int getPace() {
return pace;
}
}
your initialization loop then becomes a much more readable :
List<Player> players = new ArrayList<Player>();
while (rs.next()) {
players.add(new Player(rs.getString("Name"),
rs.getInt("Goal"),
rs.getInt("New"),
rs.getInt("Used"),
rs.getInt("total"),
rs.getInt("pace")));
}
If you want to print information from your data good approach here would be to overload the toString of Player or to add a new method, say dumpToString().
public String dumpTostring() {
StringBuilder sb = new StringBuilder();
sb.append("Player ");
sb.append(name);
sb.append(" Goal=");
sb.append(goal);
sb.append(" New=");
sb.append(_new);
sb.append(" Used=");
sb.append(used);
sb.append(" Total=");
sb.append(total);
sb.append(" Pace=");
sb.append(pace);
return sb.toString();
}
and then just call in as part of a for each loop iterating through the list.
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?
Ok this might seem easy but its been bugging my mind for days and I honestly don't know why it the index wont increase and get the other data. I dont know where to but the return. I placed it in 2 lines and the first one only gives the first row of data from the database and the second one only gives the last one from the database. (See commented out lines below). How to get each row that fits the if-statements?
Here's my code:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
for(int i = 0; i<outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection)){
if(outletList.get(i).getStatus().equals("ACTIVE")){
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
//return data ->gives the first one in the database
}
}
}
}
//return data -> gives the last one in the database
}
You need to save all your results in another array and return that instead.
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
List<object> result = new List<object>();
for(int i = 0; i<outletList.size(); i++)
{
if(outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if(outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
result.Add(data);
}
}
}
return result.ToArray();
}
try this:
public List<Outlet> populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
List<Outlet> data = new ArrayList<Outlet>();
for(int i = 0; i < outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection) &&
outletList.get(i).getStatus().equals("ACTIVE")){
data.add(outletList.get(i));
}
}
return data;
}
Your problem here is as follow:
Your first return statement, will exit the for loop, and return
the first object, as your results have shown.
Your second return statement, will, as you have explained, only
return the last record that was iterated over in the for loop.
Your third problem is on this line data = new Object[]{bar, name,
code};. After every loop, you instantiate the data object to a new
array of objects, instead of adding the values to the array, so essentially, you are always creating an array of objects with 1 item in it, the last one that was iterated.
If you want to return all objects in the array, you should try the following:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
Object[] result = new Object[outletList.size()];
for (int i = 0; i < outletList.size(); i++)
{
if (outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if (outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
var data = new { bar, name, code };
result[i] = data;
}
}
}
return result;
}
I currently have this program read the contents of a text file and calculate the averages and amount of test scores taken and print them out neatly in a small data table. These are the names, amount of quizes taken and average of each student:
James Tiberius Kirk 8 91.63
Buffy Summers 7 83.14
Tom Baker 15 100.00
Malcolm Reynolds 9 84.22
Elizabeth Bennet 9 93.33
John Blutarsky 9 0.00
Dorthy Gale 6 85.83
All of these Students are stored within the Array named Anames[]. I was wondering if it was at all possible to sort these students alphabetically by last name using the code that I have now. When I run the program it gives me the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1927)
at text.reader.TextReader.compareLastNames(TextReader.java:117)
at text.reader.TextReader.main(TextReader.java:94)
Here is the code of my main class:
public static void main(String[] args)throws IOException{
Double score=0.0;
int b,j;
String tempfirst = "";
String templast = "";
Student Anames[] = new Student[30];
Student Temp[] = new Student [1];
int Stucount = 0;
Scanner reader = new Scanner(new File("quizScores.txt"));
boolean runProgram = true;
PrintWriter writer = new PrintWriter(new File("scoreReport.txt"));
//prints header for report
System.out.println("Name Number Quizes Quiz Socres");
writer.println("Name Number Quizes Quiz Socres");
//check to see if end of file string
while (!reader.hasNext("-10")){
String name="", first="", last="";
//gets the name from file
while(!reader.hasNextDouble()){
last = reader.next();
while (!reader.hasNextDouble()){
first = first+reader.next()+" ";
}
name=first+last;
}
//creates new student with given name
Student newStudent = new Student(first, last);
Anames[Stucount] = newStudent;
Stucount++;
//gets the quiz scores and makes sure does not averge in the end of file string.
while (reader.hasNextDouble()&& !reader.hasNext("-10")){
newStudent.addQuiz(reader.nextDouble());
}
//Prints out the formated data
System.out.printf("%-30s%4.0f%30.2f \n",newStudent.getName(), newStudent.getQuizNumber(), newStudent.getAverage());
writer.printf("%-30s%4.0f%30.2f",newStudent.getName(), newStudent.getQuizNumber(), newStudent.getAverage());
writer.println();
}
System.out.println("\n");
for (b = 0; b < Stucount; b++){
int INTEGERTEMP = b;
for (j= b+1; j < Stucount; j++){
int INTEGERTEMP2 = j;
if ((compareLastNames(Anames[INTEGERTEMP].getLAST(), Anames[INTEGERTEMP2].getLAST()))>0){
Temp[0] = Anames[b];
Anames[b] = Anames[j];
Anames[j] = Temp[0];
}
}
}
System.out.println("Name Number Quizes Quiz Socres");
for (int i = 0; i < Stucount; i++) {
System.out.printf("%-30s%4.0f%30.2f \n", Anames[i].getName(), Anames[i].getQuizNumber(), Anames[i].getAverage());
}
writer.close();
}
private static int compareLastNames(String a, String b){
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
Here is the Student.java which contains most of the methods used:
public Student (String inName, String inLast){
studentName=inName;
studentLast = inLast;
quizAverage = 0;
quizScore=0;
numberQuizes=0;
}
public void addQuiz(double inQuiz){
quizScore += inQuiz;
numberQuizes++;
}
public double getAverage(){
quizAverage = quizScore/numberQuizes;
return quizAverage;
}
public String getName(){
return studentName+studentLast;
}
public double getQuizNumber(){
return numberQuizes;
}
public String getLAST(){
return studentLast;
}
You can use java.util.Arrays.sort(Student [] arr, Comparator<Student> comp) instead of your own compare code. In single line you can achieve it like this:
Student arr[];//considering this array you will populate
Arrays.sort(arr,new java.util.Comparator<Student>(){
public int compare(Student o1, Student o2) {
return o1.studentLast.compareTo(o2.studentLast);
}
});
//then the arr will be sorted with studentLast name
Let's work our way back from your exception to figure out where the problem is. First, it tells us we've got a StringIndexOutOfBoundsException on line 117; that is, the line (it might actually be the surname_b line, you've removed code from the class that means I can't match up the lines properly)
String surname_a = a.substring(index_a);
You'll notice the message from the exception helpfully tells us that the index used was -1. Let's take a look at why a.lastIndexOf(" "); would return -1. We see in the documentation for String that it returns -1 when the character does not occur in the String.
Now, let's work another step back in the Exception's stack trace to figure out why there's no space in that String. The Exception tells us to check line 94, where we see
if ((compareLastNames(Anames[INTEGERTEMP].getLAST(), Anames[INTEGERTEMP2].getLAST()))>0){
So, what's going on here? We're passing in the last names (and just the last names) from each of the students into our comparison function. The last names, for the most part, have no spaces in them.
So, how do we fix this? Well, you'll have to change your function to only take substrings of the surname if there actually is a space in them, i.e. if the index returned isn't -1.
Once you've got the comparison function done, I recommend looking at how to write an Object that implements the Comparable interface. This will allow you to use library sorting functions, which will be faster and less buggy than your own sorting functions (most likely!).
I have an array of arrays with color variable
Color [] [] bin = new Color [64] [];
afterwards I want to insert colors into this array
Im looping through a list of colors and tmpColor is the particular color in the loop. I need to insert it into the specific loop it belongs.
int idx = 16* (tmpColor.getRed()/64) + 4*(tmpColor.getGreen()/64) + (tmpColor.getBlue()/64);
bin[idx].push(tmpColor);
However this doesn't seem to work. How do I add a color into the array in the specific index?
How I solve it is the following: instead of creating an array of arrays I created and array of ArrayLists
int size = 64;
ArrayList<Color>[] lists = new ArrayList[size];
for( int i = 0; i < size; i++) {
lists[i] = new ArrayList<Color>();
}
After that I pushed the elements to their particular bin ( in this case in lists)
lists[idx].add(tmpColor);
Afterwards getting the lenght and the first color in the array is s follows:
for (ArrayList<Color> p : lists){
System.out.println("size of bin" + p.size());
if (p.isEmpty())
continue;
else {
System.out.println("list" + p.get(0));
}
}
If you need a List of colors for your index you can use a Map:
private Map<Integer, List<Color>> bin = new HashMap<Integer, List<Color>>();
int idx = 16* (tmpColor.getRed()/64) + 4*(tmpColor.getGreen()/64) + (tmpColor.getBlue()/64);
if(bin.get(idx)==null) bin.put(idx, new ArrayList<Color>());
bin.get(idx).add(tmpColor); //This should be exactly what you need
You can use also different structures like List<List<Color>> or List<Color>[]. Every structure relays on a List since List can be updated and created without knowing the initial length.
What I would do is create a separate class for color bin and some useful methods within:
public class Bin{
private List<Color> colors = new ArrayList<Color>();
public void addColor(Color col){
this.colors.add(col);
}
public List<Color> getColors(){
return this.colors;
}
public boolean hasColor(Color col){
return colors.contains(col);
}
//and so on...
}
And the best structure for your goal now is a map with lazy initialization:
private Map<Integer, Bin> myBinsOfColors = new HashMap<Integer, Bin>();
int idx = 16* (tmpColor.getRed()/64) + 4*(tmpColor.getGreen()/64) + (tmpColor.getBlue()/64);
if(myBinsOfColors.get(idx)==null) myBinsOfColors.put(idx, new Bin()); //Lazy
myBinsOfColors.get(idx).addColor(tmpColor); //This should be exactly what you need
To get the avarage and the number of colors you can implement two methods in the Bin class:
public class Bin{
private List<Color> colors = new ArrayList<Color>();
//As above.
public Color calculateAverage() {
Integer red = 0;
Integer blue = 0;
Integer green = 0;
if(!colors.isEmpty()) {
for (Color col : colors) {
red+= col.getRed();
green+= col.getGreen();
blue+= col.getBlue();
}
return new Color(red/colors.size(), green/colors.size(), blue/colors.size());
}
return null;
}
public int getColorCount(){
return this.colors.size();
}
//and so on...
}
Can someone could be kind and help me out here. Thanks in advance...
My code below outputs the string as duplicates. I don't want to use Sets or ArrayList. I am using java.util.Random. I am trying to write a code that checks if string has already been randomly outputted and if it does, then it won't display. Where I am going wrong and how do I fix this.
public class Worldcountries
{
private static Random nums = new Random();
private static String[] countries =
{
"America", "Candada", "Chile", "Argentina"
};
public static int Dice()
{
return (generator.nums.nextInt(6) + 1);
}
public String randomCounties()
{
String aTemp = " ";
int numOfTimes = Dice();
int dup = 0;
for(int i=0 ; i<numOfTimes; i++)
{
// I think it's in the if statement where I am going wrong.
if (!countries[i].equals(countries[i]))
{
i = i + 1;
}
else
{
dup--;
}
// and maybe here
aTemp = aTemp + countries[nums.nextInt(countries.length)];
aTemp = aTemp + ",";
}
return aTemp;
}
}
So the output I am getting (randomly) is, "America, America, Chile" when it should be "America, Chile".
When do you expect this to be false?
countries[i].equals(countries[i])
Edit:
Here's a skeleton solution. I'll leave filling in the helper methods to you.
public String[] countries;
public boolean contains(String[] arr, String value) {
//return true if value is already in arr, false otherwise
}
public String chooseRandomCountry() {
//chooses a random country from countries
}
//...
int diceRoll = rollDice();
String[] selection = new String[diceRoll];
for ( int i = 0; i < selection.length; i++ ) {
while (true) {
String randomCountry = chooseRandomCountry();
if ( !contains(selection, randomCountry ) {
selection[i] = randomCountry;
break;
}
}
}
//...then build the string here
This doesn't check important things like the number of unique countries.
You need a data structure which allows you to answer the question "does it already contain item X?"
Try the collection API, for example. In your case, a good candidate is either HashSet() or LinkedHashSet() (the latter preserves the insert order).
You'd probably be better of using another structure where you save the strings you have printed. Since you don't want to use a set you could use an array instead. Something like
/*
...
*/
bool[] printed = new bool[countries.length];
for(int i=0 ; i<numOfTimes ; /*noop*/ )
{
int r = nums.nextInt(countries.length);
if (printed[r] == false)
{
i = i + 1;
printed[r] = true;
aTemp = aTemp + countries[r];
aTemp = aTemp + ",";
}
}
return aTemp;
Consider what you're comparing it to:
if (!countries[i].equals(countries[i]))
are you comparing c[i] to c[i]? or c[i] to c[i-1]? Or do you need to check the whole array for a particular string? Perhaps you need a list of countries that get output.
make list uniqueCountries
for each string called country in countries
if country is not in uniqueCountries
add country to uniqueCountries
print each country in uniqueCountries
When you do this, watch out for index out of bounds, and adjust accordingly
Much faster way to do it then using HashSets and other creepy stuff. Takes less code too:
public String randomCounties() {
List<String> results = Arrays.asList(countries);
Collections.shuffle(results);
int numOfTimes = Dice();
String result = " ";
for(int i=0 ; i<numOfTimes; i++) {
result = result + countries[i] + ", ";
}
return result;
}
If you want to avoid outputting duplicate values, you need to record what values have already been listed or remove values from the pool of possibilities when they get selected.
You mention that you do not want to use Sets or ArrayList (I assume you mean Lists in general), I assume that is a requirement of the assignment. If so, you can accomplish this by building arrays and copying data between them the same way that an ArrayList would.
one note, your current implementation chooses between 1 and 6 entries from and array of 4 entries. If you force the selections to be unique you need to decide how to handle the case when you have no more unique selections.