asinine
asinine

Reputation: 1

Alternate Printing 2 Strings with multiple variables with Java

I am trying to have the output alternate between string institution and string prefix. Example

1.Institution: UCF

1.Prefix: CGS

2.Institution: USF

2.Prefix: COP

so on and so forth...

I want to print The first variable from each String together (print the 1's together and print the 2's together.

package catalog; public class Course {

private String[] institution = {"UCF", "USF", "UM", "FSU", "FS"};
private String[] prefix = {"CGS", "COP", "COP", "CGS", "CIS"};
public Course() {
    for(String i: institution) {
        System.out.println("Institution: "+i);
        for (String p: prefix)
        System.out.println("Prefix: "+p);}
    }

public static void main(String[] args) {
    System.out.println("Transcripts for BN");
    new Course();
}

}

Upvotes: 0

Views: 135

Answers (2)

Shubham
Shubham

Reputation: 189

First of all, this is possible only if both the array is of the same size. If that's the case then you just have to loop based on the index. The solution will be the same as above.

for better understanding of for loop and forEach loop read this. What is the difference between for and foreach?

Also, I would like to add your program can crash if the sizes of the arrays are different so I suggest putting a check for that.

Upvotes: 0

Jason
Jason

Reputation: 5246

Instead of using an advanced for-loop just use a for-loop. In doing so, we retain the index in the array we're iterating over. All we have to do is print the value at the index in the Course#instituion array and Course#prefix array.

How to improve this (for you to do)

  1. Think of each Course as containing a single institution and prefix.
  2. Do not use the constructor to print information, create a method to do this.
  3. Check for edge cases such as what if institution array is not the same size as the prefix array.
    public static void main(String[] args) {
        System.out.println("Transcripts for BN");

        new Course();
    }

    public static final class Course {

        private String[] institution = {"UCF", "UCF", "UCF", "UCF", "UCF"};

        private String[] prefix = {"CGS", "COP", "COP", "CGS", "CIS"};

        public Course() {
            for (int institutionIndex = 0; institutionIndex < institution.length; institutionIndex++) {
                System.out.println(String.format("Institution: %s", institution[institutionIndex]));
                System.out.println(String.format("Prefix: %s", prefix[institutionIndex]));
            }
        }

    }

Output

Transcripts for BN
Institution: UCF
Prefix: CGS
Institution: UCF
Prefix: COP
Institution: UCF
Prefix: COP
Institution: UCF
Prefix: CGS
Institution: UCF
Prefix: CIS

Upvotes: 1

Related Questions