-3

I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.

There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.

Here is the code I have so far

import java.util.Scanner;

public class GimmeAW {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter the Line\nEntering -1 exits the program")           
    String aLine;

    aLine = input.nextLine();
    char one = aLine.charAt(0);
    char two = aLine.charAt(1);

    if (one == '-' && two == '1') {
        System.out.println("System Exit");
        System.exit(1);
    }

    for (int i = 0; i < aLine.length(); i++) {

        if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
            int location = i;
            System.out.print(" " + i);
        }
    }
}
SeanD
  • 1
  • 2
  • *"I am also struggling with allowing the user to enter a new string and running the loop again."* Hint: how do you do something repeatedly in Java? – Stephen C Jun 01 '17 at 13:49
  • 1
    You can check "-1" condition, in this way: if (!("-1").equals(aLine)) – Yuri H Jun 01 '17 at 13:52

1 Answers1

0

To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...

char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();

for(int i = 0; i < ch.length; i++) {

    System.out.print("The character " + ch[i] + " is at locations ");
    // searching
    for(int j = 0; j < l; j++) {
        if(aLine.charAt(j) == ch[i]) {
            System.out.print(j + " ");
        }
    }
    System.out.println();
}

And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.

String choice = "yes";
do {
    // code

    // want to repeat ??
    choice  = in.nextLine();

} while(choice.equals("yes"));
Rajeev Singh
  • 3,292
  • 2
  • 19
  • 30
  • Does this utilize arrays? If so, I can't use that yet. Could I still use that logic with just charAt() and length() functions? – SeanD Jun 01 '17 at 14:00
  • the array is just for storing the chars... you can remove it and put the char directly in place of `ch[i]` for comparison. – Rajeev Singh Jun 01 '17 at 14:02