Hello, I am working on a program that requires the splitting of a string (the string in question is "BSHDDBDSBSHHSBH") so that it can count the occurrences of each separate letter. The code I currently have is:

public static void countPercent(Scanner input)	{
	String nucl = input.next();
		int[] count = new int[4];
		for (int i = 0; i < nucl.length(); i++)	{
			char single = nucl.charAt(i);
			if (single == 'B')	{
			} else if (single == 'D')	{
			} else if (single == 'H')	{
			} else	{

The expected output should be in an array like this: [3, 3, 5, 7] for example. Currently, I get one number in the final cell, but all the rest read zero. I have spent so long trying to figure this one out!

Thanks in advance!

I don't know what was going wrong, because it worked for me, try this though.

import java.util.Scanner;

public class one 
	public static void countPercent(Scanner input)
		String nucl = input.next();
		int[] count = new int[4];
		for (char single : nucl.toCharArray())
			switch (single)
			case 'B': count[0]++; break;
			case 'D': count[1]++; break;
			case 'H': count[2]++; break;
			default: count[3]++; break;
			for(int j : count)
	public static void main(String[] args)
		Scanner s = new Scanner(System.in);

I added a print statement, and changed your initial for loop to a for each loop, which reads a little more cleanly and also changed your if else loops to a switch.

Hope it helps.

That sort of got it working, I'll just play around with it for a bit. Thanks for your help! Now I have a similar question about my same program.

public static void codons(Scanner input)	{
		String firstLine = input.nextLine();
		String codon = input.next();
		String group = codon.toUpperCase();
		String trio = group.substring(0, 3);
		char each[] = group.toCharArray();
		for (int i = 0; i < codon.length(); i++) {
		System.out.println("Codons: " + Arrays.toString(each));

That code is supposed to break apart the same initial string I posted into groups of three characters. However, it just prints out each individual character in the array. Do you have any hints as to what may be the issue?

Thanks for your help again.

Also, if this next question would be best in its own thread, I can also do that.

Try this instead, it might need a little fixing:

public static void codons(Scanner input)
		//String firstLine = input.nextLine();
		String DNA = input.next();
		DNA = DNA.toUpperCase();
		while(DNA.length() >= 3)
			String codon = DNA.substring(0,3);
			DNA = DNA.substring(3);

(I assume you are working on DNA).

Every time the while loop is run the DNA string is shortened after the first part (the first codon) is striped.

I figured out my issues! Your solutions were definitely a lot cleaner in my program, but it turns out I was passing the nextLine() and next() all over the place and wasn't really keeping track of them.

Thanks for your help!