I'm creating an array that will sort arrayString[10][2] and then display the results to the user using JOptionPane. The length of the 2D array is irrelevant, just note that it will not be completely populated resulting in nulls. When I display the information to the user I want to exclude the nulls. Currently I have used a variable "isNull" to make this work but I know it is inefficient and am looking for the proper way to accomplish this.
The Array with two rows of data
String arrayString[][] = new String[10][2];
arrayString[0][0] = "Doe";
arrayString[0][1] = "John";
arrayString[1][0] = "Doe";
arrayString[1][1] = "Jane";
The actual program logic
String output = "";
int isNull = 0;
for (int i = 0; i < arrayString.length; i++)
{
for (int j = 0; j < arrayString[i].length; j++)
{
if ( arrayString[i][j] == null )
{
isNull = 1;
break;
}
else
output += arrayString[i][j] + " ";
isNull = 0;
}
if(isNull == 1)
break;
else
output += " \n";
}
JOptionPane.showMessageDialog(null,output,"Results",JOptionPane.INFORMATION_MESSAGE);
Thanks for all the help guys, I wen't back through my code and reevaluated it and got an answered I'm satisfied with on my own. Thanks for the responses though.
Solved
for (int i = 0; i < arrayString.length; i++)
{
for (int j = 0; j < arrayString[i].length; j++)
{
if ( arrayString[i][0] == null)
break;
else
output += arrayString[i][j] + " ";
}
if ( arrayString[i][0] == null)
break;
else
output += " \n";
}
// Make a List of all anagram groups above size threshold.
List<List<String>> winners = new ArrayList<List<String>>();
for (List<String> l : m.values())
if (l.size() >= minGroupSize)
winners.add(l);
// Sort anagram groups according to size
Collections.sort(winners, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
return o2.size() - o1.size();
}});
// Print anagram groups.
for (List<String> l : winners)
System.out.println(l.size() + ": " + l);
Look at this post more accurate:
http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html#sorting
Related
I have two ArrayLists: phNumbers and pinNumbers. Both with the same amount of elements. I am trying to check if a given value is in the first phNumbers, and if it is, at what index of the phNumbers ArrayList was that value found. I then wish to check if a second value is in the pinNums ArrayList at the index previously identified.
Here is my code so at the moment:
for(int i = 0; i < phNumbers.size() && i < pinNums.size(); i++){
index1 = phNumbers.indexOf(i);
index2 = phNumbers.indexOf(i);
index3 = pinNums.indexOf(i);
if(phNumbers.get(i).equals(details[1].trim()) && pinNums.get(index1+1).equals(details[2].trim())){
//send response1
}
else if(phNumbers.get(i).equals(details[1].trim()) && !pinNums.get(index2+1).equals(details[2].trim())){
//send response2
}
else if(pinNums.get(i).equals(details[2].trim()) && !phNumbers.get(index3+1).equals(details[1].trim())){
//Send response3
}
else{
//send response4
}
}
The issue I am having is that it is not working for any elements beyond the first, so I'm assuming it's an issue with my for loop. Could anyone offer some assistance?
So, First if you have a phNumber arraylist and one string of phnumber then try this
ArrayList<String> phNumbers = new ArrayList<>();
phNumbers.add("aaa");
phNumbers.add("bbb");
phNumbers.add("ccc");
phNumbers.add("ddd");
ArrayList<String> pinNums = new ArrayList<>();
pinNums.add("ddd");
pinNums.add("bbb");
pinNums.add("ccc");
pinNums.add("aaa");
for (int i = 0; i < phNumbers.size(); i++) {
for (int j = i; j < pinNums.size(); j++) {
if (phNumbers.get(i).equalsIgnoreCase(pinNums.get(j))) {
Log.e("mye", "phone number and pin number match on this index" + i + "for phnumber and index " + j + "for pin number");
}
}
}
if you want to break after some point then you need to break for loop.
its ok or you want anything else?
I have two lists which contains some values,I have to make String from them so that i will take the 1st value of first list and 1 st value of 2 nd list and also 2nd value of first list and 2 nd value of 2nd list and so on..Lets says those two lists contains the interview timings.So i am giving my code here
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
for(String a :interviewTimingToFrom1){
System.out.println("Timing 1:"+a);
}
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
for(String a :interviewTimingToFrom2){
}
The values contain in the 1 st and 2nd list are
Timing 1:12:00am
Timing 1:2:00am
Timing 2:1:00am
Timing 2:3:00am
So now i need to make a string like from 12.00am to 1.00 am ,from 2.00 am to 3.00am how i can do that .Please help
int maxSize = Math.max(interviewTimingToFrom1.size(),interviewTimingToFrom2.size());
StringBuilder result = new StringBuilder();
for (int i=0; i<maxSize; i++)
{
if (i < interviewTimingToFrom1.size())
result.append(interviewTimingToFrom1.get(i));
if (i < interviewTimingToFrom2.size())
result.append(interviewTimingToFrom2.get(i));
}
System.out.println(result.toString());
Try this;
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
if (interviewTimingToFrom1.size() == interviewTimingToFrom2.size()) {
int noOfSlots = interviewTimingToFrom1.size();
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom1.get(i));
}
} else {
System.out.println("No match");
int noOfSlots = (interviewTimingToFrom1.size() > interviewTimingToFrom2
.size() ? interviewTimingToFrom2.size()
: interviewTimingToFrom1.size());
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom2.get(i));
}
}
I am using this code, and for some reason, I'm getting a No Such Element Exception...
numCompanies is being imported from the keyboard and is showing up right and portfolio is an array with [numCompanies][4].
Can anyone figure out why?
for(int i = 0; i < numCompanies; i++)
{
System.out.print("Stock #" + (i+1) + ": ");
String stockData = kbReader.nextLine();
System.out.print("\n\n hi" + stockData);
Scanner stockLine = new Scanner(stockData);
for(int j = 0; j < 4; j++)
{
portfolio[i][j] = stockLine.next();
}
}
I have not tested this but probably stockLine.next(); is called even though there is no element left. So maybe this could help:
for(int j = 0; j < 4; j++)
{
if( stockLine.hasNext() ) {
portfolio[i][j] = stockLine.next();
}
else
{
portfolio[i][j] = 0; // or whatever you want it to be by default
}
}
This will solve the error message but not the fault.
You're passing a single string to a Scanner object, but I would say there's a better way of doing this.
If you want to simply read in the input for each value in the string, separated by spaces, then use split():
String stockData = kbReader.nextLine();
String[] data = stockData.split(" ");
if (data.length != 4) {
System.err.println("Bad data value found!");
} else {
//run your loop
}
For those who aren't familiar, the game is a number guessing game, where a number is chosen (non repeating; e.g 1223 is NOT chosen) and the user makes a guess and obtains information whether the number AND digit is correct, number is correct but in a wrong digit, or the number is not contained. http://en.wikipedia.org/wiki/Bulls_and_cows
(e.g number chosen => 1234, guessing 3789 will give 1 cow)
Instead of the computer choosing the number and telling the properties and player guesses, I would like to do the reverse; I type in a number and the properties - the computer gives a list of possible numbers.
Anyways, my method is:
Add all numbers that do not repeat itself to the arraylist
Delete numbers that do not satisfy the conditions.
Here is how the cow cases are done :
//Case 5: property is 4 cows;
if (property.equals("040")) {
//delete if numbers don't appear EXACTLY 4 times
if (contains != 4) { numbers.remove(i); }
//removes if the digits of the number tried corresponds with the actual number (Cow!)
else if (n.charAt(0) == first.charAt(0)) { numbers.remove(i); }
else if (n.charAt(1) == second.charAt(0)) { numbers.remove(i); }
else if (n.charAt(2) == third.charAt(0)) { numbers.remove(i); }
else if (n.charAt(3) == fourth.charAt(0)) { numbers.remove(i); }
}
It has worked for cows. Upon trying to implement bulls, it seems like using this sort of approach won't be possible. How can I do a method for bulls!? Would I need to create four more arraylists and calculate for each case? Or is ArrayList not the way to go?
For example, 1234 with 1bull would mean the number to guess is 1XXX, X2XX, XX3X or XXX4 but
I can't use this approach as it will delete all number except the input.
Thanks.
You can try this algorithm for solving -
String userAnswer = // ... getUserAnswer();
if(userAnswer == null || userAnswer.equals("")
|| !userAnswer.matches("^-?\\d+$")
|| userAnswer.split("(?<=\\G.{1})").length < 4) {
// error
}
int[] secret = (int[])// ... getSecret(request);
int[] seq = {1,2,3,4};
for(int i = 0; i < userAnswer.split("(?<=\\G.{1})").length; i++) {
seq[i] = Integer.parseInt(s[i]);
}
int bullCount = 0;
int cowCount = 0;
for(int i = -1; ++i < secret.length;) {
if(secret[i] == seq[i]) {
bullCount++;
}
}
for(int i = -1; ++i < secret.length;) {
for(int j = -1; ++j < secret.length;) {
if(secret[i] == seq[j] && i != j) {
cowCount++;
}
}
}
String snswer = bullCount + "b" + cowCount + "c";
if(Arrays.equals(secret, seq))
// win!
else
// fail!
It's wrong as if the code is 1634 and the user enters 6113, the program returns 4 cows when there is in fact 3.
Try this:
private static String findNumberOfCowsAndBulls(String firstString, String secondString) {
if(firstString.equals(secondString))
return "All Bulls:" + firstString.length();
char[] fSArr = firstString.toCharArray();
char[] sSArr = secondString.toCharArray();
int countCow = 0;
int countBull = 0;
Map<String, Integer> fSMap = new HashMap<>();
Map<String, Integer> sSMap = new HashMap<>();
for (int i = 0; i < fSArr.length; i++) {
if(i < sSArr.length){
if(fSArr[i] == sSArr[i]){
countBull++;
}
else{
updateMapOfCharsCount(fSMap, fSArr[i]);
updateMapOfCharsCount(sSMap, sSArr[i]);
}
}
else{ //fSArr is bigger than sSArr
updateMapOfCharsCount(fSMap, fSArr[i]);
}
}
if(fSArr.length < sSArr.length){ //fSArr is shorter than sSArr
for(int i = fSArr.length; i < sSArr.length - fSArr.length; i++){
updateMapOfCharsCount(sSMap, sSArr[i]);
}
}
for (Map.Entry<String, Integer> entry : fSMap.entrySet()) {
String key = entry.getKey();
if(sSMap.containsKey(key)){
if(sSMap.get(key) <= fSMap.get(key))
countCow = countCow + sSMap.get(key);
else
countCow = countCow + fSMap.get(key);
}
}
return "countCow = " + countCow + " countBull = " + countBull;
}
private static void updateMapOfCharsCount(Map<String, Integer> fsMap, char c) {
String key1 = String.valueOf(c);
if (fsMap.containsKey(key1)) {
fsMap.put(key1, fsMap.get(key1) + 1);
} else
fsMap.put(key1, 1);
}
long temp;
for ( int i = 0; i < size; i++ )
{
temp = ls.get(i);
System.out.println("temp is:" + temp);
for ( int j = 0; j < size; j++)
{
if ( i == j )
{
}
else if ( ls.get(i) == ls.get(j) )
{
// If Duplicate, do stuff... Dunno what yet.
System.out.println(ls.get(i)+" is the same as: " + ls.get(j) );
//System.out.println("Duplicate");
}
}
}
I have a List of type Long, it is filled with several 9 digit numbers like 900876012, I am checking for duplicates so that I can generate new numbers and replace the duplicate before exporting to a file.
First, I check to see if the position in the array is the same, since obviously something at position 1 is going to be the same in the same list at position 1, if so, ignore.
Then, I check to see if the contents are the same, but it doesn't evaluate as true for some reason, it did before as a plain "if" on its own.
For reference here's the numbers, just ignore the "temp is":
temp is:900876512
temp is:765867999
temp is:465979798
temp is:760098908
temp is:529086890
temp is:765867999
temp is:529086890
temp is:800003243
temp is:200900210
temp is:200900210
temp is:542087665
temp is:900876512
temp is:900876512
temp is:900876512
temp is:900876512
Here's the full method for reference:
public static void CheckContents(BufferedReader inFileStreamName, File aFile, Scanner s ) throws DuplicateSerialNumberException
{
System.out.println();
List<Long> ls = new ArrayList<Long>();
List<String> ls2 = new ArrayList<String>();
long SerialNum = 0;
int counter = 0;
int size = 0;
String StringBuffer;
while (s.hasNextLine())
{
ls.add(s.nextLong());
//System.out.println();
StringBuffer = s.nextLine();
ls2.add(StringBuffer);
size = ls.size();
//System.out.println(ls.size());
SerialNum = ls.get(size-1);
//System.out.println(ls.get(size-1));
System.out.println("Serial # is: " + SerialNum);
//System.out.println(SerialNum + ": " + StringBuffer);
counter++;
}
long temp;
for ( int i = 0; i < size; i++ )
{
temp = ls.get(i);
System.out.println("temp is:" + temp);
for ( int j = 0; j < size; j++)
{
if ( i == j )
{
}
else if ( ls.get(i) == ls.get(j) )
{
// If Duplicate, do stuff... Dunno what yet.
System.out.println(ls.get(i)+" is the same as: " + ls.get(j) );
//System.out.println("Duplicate");
}
}
}
}
A nice one.
In the list you don't store float (primitive) but Float objects. Autoboxing makes you transparent to you.
And the == comparator does not work with objects (it tells if both objects are the same, but if you have two object holding the same value it returns false).
You can use
if ( ls.get(j).equals(ls.get(i))
or (since it is List<Long>)
if ( ls.get(j).longValue() == ls.get(i).longValue())
or even (thanks to autoboxing)
if ( ls.get(j).longValue() == ls.get(i))
Please try
else if ( ls.get(i) != null && ls.get(i).equals(ls.get(j)) )
instead