Entering an If statement with a hashmap conditions - java

for (int i = 0; i < pac.length; i++)
{
for (int j=0;j<mem.length;j++)
{
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++)
{
if (words[k].equals(pac[i])
{ //done system.out.println here and it's right
if (!members.containsKey(pac[i])) //won't enter this if correctly
{
members.put(pac[i], " " + words[0]);
}
else
{
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
}
}
else
{
members.put(pac[i], "");
}
}
}
}
I need the code to take an array pac which contains a list of organizations and then a list of people's names with their organizations after. I have to put them into a hashmap of members. I cant seem to get it to enter the if statement correctly though. It reaches there correctly. I've used the printing to see what should go into it and that part is correct. Members is an empty hashmap yet all but only one iteration of the loops will go into the first if statement when most should go into it.

use label you can solve your problem. because any one iteration of 2nd loop can empty your member. try this
for (int i = 0; i < pac.length; i++) {
action:
for (int j = 0; j < mem.length; j++) {
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++) {
//System.out.println(words[0] + "ttt");
if (words[k].equals(pac[i])) {
System.out.println(words[k]);
if (!members.containsKey(pac[i]))
{
members.put(pac[i], " " + words[0]);
break action;
} else {
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
break action;
}
} else {
members.put(pac[i], "");
}
}
}
}
and use persons as a key for members instead of organization. because a org have more number of persons.

Related

Printing out values of different rows and column in 2d array using for loops

I have this 2d array of the first row being first names and the second being last names.
String[][] ladrones2 = {
{"Phil", "Kim", "Phil", "Perry"},
{"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
the prefered out come of this would be to have them printend out like e.g
Phill Garcia
Kim Gimena
etc...
Now I was able to do this by catching the ArrayIndexOutOfBoundsException exception and it works and the output is:
name Phil Garcia
name Kim Gimena
name Phil Basinger
name Perry Ornitorrinco
Which is great but I wondered if there was a way to do this without having to catch the exception? I've been searching to make this cleaner but wasn't able to do so.
Code at the moment:
public static void robo2() {
String[][] ladrones2 = {
{"Phil", "Kim", "Phil", "Perry"},
{"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
try {
for (int i = 0; i < ladrones2.length; i++) {
for (int j = 0; j < ladrones2[i].length; j++) {
System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("");
}
}
as you can see I used in the inner for loop a +1 on the i variable which in turn throws the exception.
Any ideas? I would like just to keep this way of working at the moment with 2 forloops due to being new to Java.
If you are sure that ladrones2 array always has 2 rows, then below code would be simpler:
public static void main(String[] args) {
String[][] ladrones2 = {
{"Phil", "Kim", "Phil", "Perry"},
{"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
for (int i = 0; i < ladrones2[0].length; i++) {
System.out.println("name: " + ladrones2[0][i] + " " + ladrones2[1][i]);
}
}
On this line :
System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
You are taking an element from the first and second array at the same time but you are looping over all the elements in the sequence on this line :
for (int i = 0; i < ladrones2.length; i++)
To correct this problem, you simply have to reduce the range of i to ladrones.length-1, otherwise you will reach the end of the array and try to access the next element which doesn't exist here.
You'll end up with this line instead :
for (int i = 0; i < ladrones2.length-1; i++) {

My Substitution Cipher is not combining the encrypted message in the StringBuilder

//Fill Each Alphabet
System.out.println();
for(int i = 0; i<alphabet.length; i++)
System.out.print(i + " ");
System.out.println();
for(int i = 0; i <alphabet.length; i++)
{
alphabetOriginal[i] = i;
alphabet[i] = i;
char letter = (char)(alphabetOriginal[i] + 65);
if(alphabet[i] > 9)
System.out.print(letter+ " ");
else
System.out.print(letter+ " ");
}
//Switch each character!
int position, temporary;
Random rn = new Random();
for(int i = 0; i <alphabet.length; i++)
{
int j = rn.nextInt(26);
temporary = alphabet[25-i];
alphabet[25-i] = alphabet[j];
alphabet[j] = temporary;
}
//Display the Scrambled Alphabet if they Are Interested
if(validateAffirm(decision))
{
System.out.println("\n\n\tYou can see the (randomly generated) new alphabet below!\n");
for(int i = 0; i <alphabet.length; i++)
System.out.print(alphabet[i] + " ");
System.out.println();
for(int i = 0; i<alphabet.length; i++)
{
char ScrambleLetter = (char)(alphabet[i] + 65);
if(alphabet[i] > 9)
System.out.print(ScrambleLetter + " ");
else
System.out.print(ScrambleLetter + " ");
}
}
//Use a Binary Search to Determine the Length of Each
StringBuilder sb4 = new StringBuilder(initMessage.length());
int temporaryCharValue;
for(int i = 0; i<initMessage.length(); i++)
{
temporaryCharValue = (int)(initMessage.charAt(i));
temporaryCharValue-=65;
for(int j = 0; alphabet[j] != temporaryCharValue; j++)
{
if(alphabet[j] == temporaryCharValue)
{
temporaryCharValue+=65;
char tempChar = (char)(temporaryCharValue);
sb4.append(tempChar);
System.out.println(tempChar);
sb4.toString();
}
}
}
System.out.println("\n" +sb4);
Can you help find out why my String isn't compiling to determine the final encrypted message? The arrays are defined just fine, but in my nested for loop, I cannot seem to access the proper method for combining each translated character into the final String. I am not even sure if the method translates the characters properly... (This is my first year programming, I apologize for any obvious mistakes. I am a junior in high school).
You code is hard to understand, there are constants that I don't know where they came from... however, It seems to me that the loop you mention had a definition problem... I explain:
According to your algorithm, your invariant (or looping condition) is alphabet[j] != temporaryCharValue however, the inner sentence (the IF sentence) expects that alphabet[j] == temporaryCharValue, so when lphabet[j] == temporaryCharValue is TRUE, the loop returns (or stops) and the IF Sentence is never evaluated...

Java How to get start and end of an element in an ArrayList

I have some dynamic values in an ArrayList
ClassnameOne <!----Begin---->
Classnametwo <!----Begin---->
Classnamethree <!----Begin---->
Classnamethree <!----End---->
Classnametwo <!----End--->
ClassnameOne <!----End---->
What I want to do is to get the beginning occurrence of an element and when it ends. So for example ClassnameOne would be 5, Classnametwo would be 3.
This is what I have done so far:
ArrayList<String> one = new ArrayList<String>();
for (int i = 0; i < one.size(); i++) {
if(one.get(i).contains("<!----End---->") && one.get(i).equals(one.get(i+1))) {
break;
} else {
count++;
System.out.println(one.get(i));
}
System.out.println(count);
}
This doesn't give the right answer. Can you please help?
ArrayList<String> one = new ArrayList<String>();
for (int starti = 0; starti < one.size(); ++starti) {
String[] words = one.get(starti).split(" ", 2);
if (words[1].equals("<!----Begin---->")) {
int n = 0;
String sought = words[0] + " " + "<!----End---->";
for (int endi = starti + 1; endi < one.size(); ++endi) {
if (one.get(endi).equals(sought) {
n = endi - starti;
break;
}
}
System.out.printf("%s at %d covers %d lines.%n", words[0], starti, n);
}
}
Assuming that the names do not repeat, otherwise a stack (or such) would to be needed.

Method to do compare and change single characters in a string

I need to do a method to check two string for example bod and bot or crab and rab. The method needs to print out what the user must do in order to make them equal. For example in bod and bot it will print "replace,2,d in the string". I used this code which seems to work.
if(a.length()==b.length()){
int i;
for(i=0; i<=a.length(); i++){
if(a.charAt(i)!=b.charAt(i)){
return "replace,"+ i + "," + b.charAt(i);
}
}
}
But I am having troubles if the two string are not equal in size. I use this but it doesn't work because one of the strings is bigger.
int aS = a.length();
int bS = b.length();
if(bS - aS == 1){
int i;
for(i=0; i<=b.length(); i++){
if(b.charAt(i)!=a.charAt(i)){
return "remove," + i;
}
}
}
Can you guys give me a suggestion what method I can use to check which is the extra letter or vice versa a letter I can add and then return a string saying either to remove a character or add an extra one. Thank you
Maybe something like this?
public ArrayList<String> createConversionList(String primary, String secondary){
//Determine which string is shorter.
String shorter;
String longer;
boolean primaryIsShorter = false;
if (primary.length() >= secondary.length()){
longer = primary;
shorter = secondary;
} else{
longer = secondary;
shorter = primary;
primaryIsShorter = true;
}
//Fills an array with all the character positions that differ between the
//two strings, using the shorter string as the base.
int[] posOfCharsToChange = new int[shorter.length()];
for(int i = 0; i < shorter.length(); i++){
if(shorter.charAt(i) != longer.charAt(i)){
posOfCharsToChange[i] = i;
} else{
posOfCharsToChange[i] = -1;
}
}
//Adds to an ArrayList all of the "Replace" strings.
ArrayList<String> conversionList = new ArrayList();
for(int pos: posOfCharsToChange){
if(pos != -1){
String s = "Replace " + secondary.charAt(pos) + " with " + primary.charAt(pos) + ". \n";
conversionList.add(s);
}
}
//Depending on which string was bigger, either adds "Add" or "Remove"
//strings to the ArrayList. If the strings were the same size, does
//nothing.
if(primary.length() != secondary.length()){
if(primaryIsShorter){
for(int i = primary.length(); i < secondary.length(); i++){
String s = "Remove " + secondary.charAt(i) + ". \n";
conversionList.add(s);
}
}
else{
for(int i = secondary.length(); i < primary.length(); i++){
String s = "Add " + primary.charAt(i) + ". \n";
conversionList.add(s);
}
}
}
return conversionList;
}
My Approach works as follows
1) We take the smaller string and put all its contents in an arraylist
2) We take the bigger string and put its contents in the arraylist only if its not present in the arraylist
3) The last character in the arraylist must be removed from the bigger string to make them equal
Ex 1:
a = rab
b = crab
1) arraylist = rab -> contents of a added
2) arraylist = rabc -> only unique content of b is added
Ex 2:
a = crab
b = rab
1) arraylist = rab
2) arraylist = rabc
similarly if the positions are in the middle or not at start ,
ex : a = racb
b = rab
1) arraylist = rab
2) arraylist = rabc
public class Replace {
public static void main(String args[]) {
int p = 0, j = 0;
String a = "rab";
String b = "crab";
if (b.length() < a.length()) {
ArrayList al = new ArrayList();
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String a");
} else {
ArrayList al = new ArrayList();
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String b");
}
}
}
Note - The program only works under your given contraints that strings only differ in one character and the ordering of both the strings is not different if we remove or add that charcter.

else statement printing multiple times - array loop

I want my code to loop through an array and only give the user an option to delete a student only if there are values in the array. If all the array values are null then I want it to print out a message. The problem is that my message is printing out multiple times for each null element in the array.
My code:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (i = studentChoice + 1;i < studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(i = studentChoice + 1;i < 9;i++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[i-1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for(int y = 0;y < 3;y++) {
studentMarksArray[9][y] = 0;
}
} else {
System.out.println("There are no students stored");
}
}
}
The else block runs in each loop iteration. If you want to run it only once at the end, do something like this:
boolean studentFound = false;
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
...
Then after the for:
if (!studentFound) {
System.out.println("There are no students stored");
}
Here is how I would determine if all the elements are null. The reason yours prints it out for each null element is that the print statement is inside the for loop.
boolean allNull = true; // default is that everything is null
for(int i = 0; i < studentNamesArray.length; i++) { // iterate through entire array
if(studentNamesArray[i] != null) { // if even 1 of them is not null
allNull = false; // set allNull to false
break; // and break out of the for loop
}
}
if(allNull) System.out.println("There are no students stored!");
I suggest to use 'boolean' variable, lets name it 'flag'. Initialize it as 'false'. If you found not null element in array, when set 'flag = true'. After 'for' loop check 'if (!flag) System.out.println ("There are no students.");'.
In your for loops, you use the same variable i, in which it overrides the original variable used in the for loop.
Try something like this:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (int j = studentChoice + 1;j < studentNamesArray.length; j++) {
studentNamesArray[j-1] = studentNamesArray[j];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(int k = studentChoice + 1;k < 9;k++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[k-1][y] = studentMarksArray[k][y];
}
}
markArrayCount = markArrayCount - 1;
for(int z = 0;z < 3;z++) {
studentMarksArray[9][z] = 0;
}
} else {
System.out.println("hi");
}
}
}
Although, I am not sure what you are trying to print out, I made adjustments to the other variable names based on my intuition; the result might not be exactly as resulted, but I am sure you can make further adjustments with the variable names so that you are not over-riding each other and causing excessive loops.

Categories