This is the Main.java
Scanner input = new Scanner(System.in);
String in="t";
String [] t=new String[15];
int c=0;
int p=0;
String n="p";
for(int i=0;i<15;i++){
System.out.print("Enter a topping (or type quit):");
n=input.nextLine();
if(n.equals("quit")){
i=16;
p=1;
}else
t[i]=n;
c++;
}
String [] q=new String[c];
if(t[c-1]==null){
q=new String[c-1];
for(int u=0;u<c-1;u++){
q[u]=t[u];
}
Arrays.sort(q);
if(p==0){
System.out.println("No more toppings allowed.");
}
for(int o=0;o<c-1;o++){
System.out.println((o+1)+". "+q[o]);
}
}
else{
q=new String[c];
for(int u=0;u<c;u++){
q[u]=t[u];
}
Arrays.sort(q);
if(p==0){
System.out.println("No more toppings allowed.");
}
for(int o=0;o<c;o++){
System.out.println((o+1)+". "+q[o]);
}
}
BinarySearch bs = new BinarySearch();
System.out.println("\nWhat do you want to search for?");
String search = input.nextLine();
System.out.println("BinarySearch: "+bs.binarySearch(q, search));
This is the BinarySearch.java class
public void printTopping() {
}
public boolean addTopping(String top) {
}
public int binarySearch(String[] words, String key) {
int left = 0;
int right = words.length - 1;
int mid = 0;
while (left <= right) {
mid = (left + right) / 2;
if ((words[mid] + "").trim().compareTo(key.trim()) < 0) {
left = mid + 1;
} else if ((words[mid] + "").trim().compareTo(key.trim()) > 0) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
How do I use the addTopping method to add an topping into the q array in main without there being a String array parameter in the addTopping method? Can I get help writing this method? Then How would i do printTopping() method?
This is the direction :
In main:
String[] toppingStringArray = Arrays.copyOf(q, q.length + 1);
In addTopping:
toppingStringArray[toppingStringArray.length - 1] = top;
Related
I'm doing a project for school and I have to test the speeds of binary vs linear searches for a spellcheck implementation. We have to use this certain SpellCheck. The examples given by my professor for binary search using recursion were a few separate snippets of code designed for ints and he wants us to make it work for this implementation with strings. Any help would be appreciated, I am very stuck at the moment. SortedWordList is the class i need help on.
import java.util.Scanner;
public class Spellcheck {
private static WordList listOfWords;// The list of correctly spelled words.
public static void main(String[] args) {
long start = System.nanoTime();
listOfWords = new SortedWordList();
//listOfWords = new WordList();
long end = System.nanoTime();
long WL = (end-start);
//end = 0;
//start = 0;
long SW = 0;
Scanner in = new Scanner(System.in);
while (true) { // Get and process one word from the user.
System.out.println();
System.out.print("Enter a word to be cheched (press return to end): ");
String word = in.nextLine().trim().toLowerCase();
start = System.nanoTime();
if (word.length() == 0)
break;
if (listOfWords.contains(word)) {
System.out.println("'" + word + "' is a legal word.");
}
else {
System.out.println("'" + word + "' is not a legal word.");
System.out.println("If there are similar words, they are shown here:");
trySubstitute(word);
tryInsert(word);
tryDelete(word);
trySwap(word);
tryBreak(word);
end = System.nanoTime();
SW = (end-start);
}
System.out.println();
System.out.printf("Time to create word list: %,d nanoseconds.%n",(WL));
System.out.println();
System.out.printf("Time to test for similar words: %,d nanoseconds.%n",(SW));
System.out.println();
System.out.printf("Time to test total: %,d nanoseconds.%n",(SW + WL));
}
}
private static void trySubstitute(String word) {
for (int i = 0; i < word.length(); i++) {
String before = word.substring(0, i);
String after = word.substring(i+1);
for (char ch = 'a'; ch < 'z'; ch++) {
String newword = before + ch + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
}
private static void tryInsert(String word) {
for (int i = 0; i <= word.length(); i++) {
String before = word.substring(0,i);
String after = word.substring(i);
for (char ch = 'a'; ch < 'z'; ch++) {
String newword = before + ch + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
}
private static void tryDelete(String word) {
for (int i = 0; i < word.length(); i++) {
String before = word.substring(0, i);
String after = word.substring(i+1);
String newword = before + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
private static void trySwap(String word) {
for (int i = 0; i < word.length() - 1; i++) {
String before = word.substring(0, i);
char a = word.charAt(i);
char b = word.charAt(i+1);
String after = word.substring(i+2);
String newword = before + b + a + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
private static void tryBreak(String word) {
for (int i = 1; i < word.length() - 1; i++) {
String before = word.substring(0, i);
String after = word.substring(i);
if (listOfWords.contains(before) && listOfWords.contains(after))
System.out.println(" " + before + " " + after);
}
}
} // end class Spellcheck
`
import java.util.ArrayList;
import java.util.Scanner;
import java.net.URL;
public class WordList {
protected final String[] words; // the list of words
public WordList() {
try {
URL listLocation = WordList.class.getClassLoader().getResource("unsorted_words.txt");
Scanner in = new Scanner( listLocation.openStream() );
ArrayList<String> wordList = new ArrayList<String>();
while (in.hasNextLine())
wordList.add(in.nextLine());
words = wordList.toArray(new String[] {});
in.close();
}
catch (Exception e) {
throw new IllegalStateException("Can't load list of words from file 'unsorted_words.txt'");
}
}
public boolean contains(String lowerCaseWord) {
for (String s : words) {
if (s.equals(lowerCaseWord))
return true;
}
return false;
}
public int size() {
return words.length;
}
public String get(int index) {
return words[index];
}
}
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class SortedWordList extends WordList {
public String [] words;
public SortedWordList() {
URL listLocation = SortedWordList.class.getClassLoader().getResource("unsorted_words.txt");
Scanner in = null;
try {
in = new Scanner( listLocation.openStream() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> wordList = new ArrayList<String>();
while (in.hasNextLine())
wordList.add(in.nextLine());
words = wordList.toArray(new String[] {});
in.close();
}
//public boolean contains(String lowerCaseWord) {
//}
static int binarySearch(String[] A, int loIndex, int hiIndex, String value) {
if (loIndex > hiIndex) {
return -1;
}
else {
int middle = (loIndex + hiIndex) / 2;
if (value == A[middle])
return middle;
else if ((A[middle].compareTo(value)) > 0)
return binarySearch(A, loIndex, middle - 1, value);
else // value must be > A[middle]
return binarySearch(A, middle + 1, hiIndex, value);
}
} // end binarySearch()
static int quicksortStep(String[] A, int lo, int hi) {
String pivot = A[lo]; // Get the pivot value.
while (hi > lo) {
while (hi > lo && ((pivot.compareTo(A[hi])) <= 0)) {
hi--;
}
if (hi == lo)
break;
A[lo] = A[hi];
lo++;
while (hi > lo && ((pivot.compareTo(A[lo])) >= 0)) {
lo++;
}
if (hi == lo)
break;
A[hi] = A[lo];
hi--;
} // end while
A[lo] = pivot;
return lo;
} // end QuicksortStep
static void quicksort(String[] A, int lo, int hi) {
if (hi <= lo) {
return;
}
else {
int pivotPosition = quicksortStep(A, lo, hi);
quicksort(A, lo, pivotPosition - 1);
quicksort(A, pivotPosition + 1, hi);
}
}
}
First, where do you need to call quicksort? Just guessing by the class's name of SortedWordList, it would seem to me that you would need to call this quicksort method inside the SortedWordList's constructor. Right now, the constructor appears to load an unsorted list of words.
If that doesn't solve the problem, I would then also look at your quicksortStep method inside the SortedWordList class again. This quicksortStep method is basically the partition method. (See https://www.programcreek.com/2012/11/quicksort-array-in-java/ for an example). I would try to follow the same code structure in the quicksortStep method as the partition method in the link above, and then modify it for strings, until it is something like:
public static int partition(String[] arr, int start, int end){
String pivot = arr[end];
for(int i=start; i<end; i++){
if((arr[i].compareTo(pivot)) < 0){
String temp= arr[start];
arr[start]=arr[i];
arr[i]=temp;
start++;
}
}
String temp = arr[start];
arr[start] = pivot;
arr[end] = temp;
return start;
}
Feel free to rename methods / variables.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to read names from a file into an String array and use binary search to find the name based on what the user types in but I keep getting a null pointer exception? I feel like it has something to do with the comparators when seeing if anything returns a null but i am not 100% sure if its that.
import java.util.*;
import java.io.*;
public class nameSearch{
static String names[];
int length;
public static void main(String[] args)throws IOException{
nameSearch sorter = new nameSearch();
File f = new File("names.txt");
Scanner scan = new Scanner(f);
Scanner input = new Scanner(System.in);
names = new String[65];
int counter = 0;
while(scan.hasNext()){
counter = counter + 1;
scan.next();
for(int i=0; i < counter; i=i+1){
names[i] = scan.next();
System.out.println(names[i].toString());
}
}
sorter.sort(names);
System.out.println(names.toString());
scan.close();
System.out.println("Enter a name you want to search: ");
String s = input.nextLine();
sorter.binarySearch(s, names);
}
public String toString(){
return "Name: "+ names;
}
void sort(String[] array) {
if (array == null || array.length == 0) {
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
String pivot = this.names[lowerIndex + (higherIndex - lowerIndex) / 2];
while (i <= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names[j].compareToIgnoreCase(pivot) > 0) {
j--;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j) {
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}
void binarySearch(String s, String[] ar){
String stringToFind = s;
int lowestIndex = 0;
int highestIndex = ar.length-1;
int middleIndex = 0;
while(lowestIndex<=highestIndex){
middleIndex = (lowestIndex+highestIndex)/2;
if(stringToFind.compareTo(ar[middleIndex]) > 0){
lowestIndex = middleIndex+1;
}else if(stringToFind.compareTo(ar[middleIndex]) < 0){
highestIndex = middleIndex - 1;
}else{
break;
}
}
if(lowestIndex > highestIndex){
System.out.println("not found");
}else{
System.out.println("found at " + middleIndex);
}
}
}
The compiler is telling me that there is a null pointer exception on: sorter.sort(names) , quicksort(0, length-1), and starting at:
while (this.names[i].compareToIgnoreCase(pivot) < 0) {
In line 16 you have defined names as String[65] and probably there is no 65 names in your file. so some of names elements are null.
try using arrayList.
public class NameSearch{
static ArrayList<String> names;
int length;
public static void main(String[] args)throws IOException{
NameSearch sorter = new NameSearch();
File f = new File("src/names.txt");
Scanner scan = new Scanner(f);
Scanner input = new Scanner(System.in);
names = new ArrayList<>();
int counter = 0;
while(scan.hasNext()){
names.add(scan.next());
}
sorter.sort(names);
System.out.println(names.toString());
scan.close();
System.out.println("Enter a name you want to search: ");
String s = input.nextLine();
sorter.binarySearch(s, names);
}
public String toString(){
return "Name: "+ names;
}
void sort(ArrayList<String> array) {
if (array == null || array.size() == 0) {
return;
}
this.names = array;
this.length = array.size();
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
String pivot = this.names.get(lowerIndex + (higherIndex - lowerIndex) / 2);
while (i <= j) {
while (this.names.get(i).compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names.get(j).compareToIgnoreCase(pivot) > 0) {
j--;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j) {
Collections.swap(this.names, i, j);
}
void binarySearch(String s, ArrayList<String> ar){
String stringToFind = s;
int lowestIndex = 0;
int highestIndex = ar.size()-1;
int middleIndex = 0;
while(lowestIndex<=highestIndex){
middleIndex = (lowestIndex+highestIndex)/2;
if(stringToFind.compareTo(ar.get(middleIndex)) > 0){
lowestIndex = middleIndex+1;
}else if(stringToFind.compareTo(ar.get(middleIndex)) < 0){
highestIndex = middleIndex - 1;
}else{
break;
}
}
if(lowestIndex > highestIndex){
System.out.println("not found");
}else{
System.out.println("found at " + middleIndex);
}
}
}
Note: This question is asked for a school assignment. I fell I'm getting close to the true code, there are only a few points left to be taken care of.
I am asked to write a method that receives two strings(s1 and s2) and
checks whether s2 is in s1 case sensitively. If s2 is in s1 it returns the index of the last occurrence of s2, otherwise it returns -1.
So, here is my code:
import java.util.*;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.println("Enter firts string: ");
String s1 = input.next();
System.out.println("Enter second string: ");
String s2 = input.next();
System.out.print(contains(s1,s2));
}
else {
//Call other methods...
}
public static int contains (String s1, String s2) {
for(int i = 0; i<s1.length(); i++) {
for(int j = 0; j<s2.length(); j++) {
char ch = s2.charAt(j);
if(s1.charAt(i) == ch) {
return i;
}
}
}
return -1;
}
But this method returns first index of s2 or it is just a copy of IndexOf method.
Output for s1 = aabbccbbe and s2 = bb is 2.
EDIT : #eli's code
import java.util.*;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.println("Enter firts string: ");
String s1 = input.next();
System.out.println("Enter second string: ");
String s2 = input.next();
System.out.print(contains(s1,s2));
}
else {
//Call other methods...
}
public static int contains(String s1, String s2) {
int i = s2.length()-1, j = s1.length()-1;
if(i > j)
return -1;
for(; i > -1; i--) {
for(; j >= 0; j--) {
if(s1.charAt(j) == s2.charAt(i)) {
if(i == 0)
return j;
if(j != 0)
j--;
break;
} else if(i != s2.length()) {
i = s2.length()-1;
}
}
}
return -1;
}
First of all, close any resource you open when you're done with it.
input.close();
If it is allowed you can just use regex:
public static int contains (String s1, String s2) {
Pattern p = Pattern.compile(s2+"(?!.*"+s2+")");
Matcher m = p.matcher(s1);
if(m.find())
return m.start();
return -1;
}
The regex pattern is explained here.
With find() you make sure that at least one occurrence is present.
As the pattern can result in 1 and only 1 result, you can just ask for the "first index of first occurrence" in the matcher, achieved with start().
EDIT
Okay, I can see you can't use anything but charAt and length.
Here's a different solution without regex, substring, indexOf or what-so-ever:
public static int contains(String s1, String s2) {
int i = s2.length()-1, j = s1.length()-1;
if(i > j)
return -1;
for(; i > -1; i--) {
for(; j >= 0; j--) {
if(s1.charAt(j) == s2.charAt(i)) {
if(i == 0)
return j;
if(j != 0)
j--;
break;
} else if(i != s2.length()) {
i = s2.length()-1;
}
}
}
return -1;
}
I must admit I didn't thoroughly test this.
FINAL
I've done some minor fixes for you. I don't know how you were capable of compiling what you edited in your post. Here's a working sample:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter choice: ");
switch (input.nextInt()) {
// If 1 is given as input...
case 1:
// As we press "enter" after inputting 1, the newline is read by the
// scanner. We skip this newline by doing this.
input.nextLine();
System.out.println("Enter first string: ");
String s1 = input.nextLine();
System.out.println("Enter second string: ");
String s2 = input.nextLine();
System.out.println("Result: " + contains(s1, s2));
break;
// If 2 is given as input (just for the sake of the example)
case 2:
System.out.println("You chose an unimplemented choice.");
break;
// If something else is given as input...
default:
System.out.println("Nothing to do...");
break;
}
// As Scanner is considered a resource, we have to close it, now that
// we're done using it.
input.close();
}
// This is the RegEx implementation
public static int containsRegx(String s1, String s2) {
Pattern p = Pattern.compile(s2 + "(?!.*" + s2 + ")");
Matcher m = p.matcher(s1);
if (m.find())
return m.start();
return -1;
}
// This is the charAt and length only
public static int contains(String s1, String s2) {
int i = s2.length() - 1, j = s1.length() - 1;
if(i > j || i * j == 0)
return -1;
for (; i > -1; i--) {
for (; j >= 0; j--) {
if (s1.charAt(j) == s2.charAt(i)) {
if (i == 0)
return j;
if (j != 0)
j--;
break;
} else if (i != s2.length()) {
i = s2.length() - 1;
}
}
}
return -1;
}
}
I think it will boil down to looping through string characters and storing the last index of occurred match.
Here is not perfect, but simple example without use of indexOf:
public static int contains(String s1, String s2) {
if(s1.length() < s2.length())
return -1;
int lastOccurrence = -1;
for (int i = 0; i < s1.length(); ) {
if (s1.startsWith(s2, i)) {
lastOccurrence = i + s2.length() - 1;
i = lastOccurrence + 1;
}
else {
++i;
}
}
return lastOccurrence;
}
Say you have the string called sentence: The quick brown fox jumps over the lazy dog. and you want to find the last occurrence of "the", called token.
sentence.length = 44 and token.length = 3
Consider this somewhat java pseudo code:
public static int lastIndexOf(String sentence, String token) {
//The starting index is the first possible location your token could fit
int startingIndex = sentence.length() - token.length();
//move backwards one character at a time until you reach 0
//checking for string fragment that equals your token at each iteration
for (int i = startingIndex; i >= 0; i--) {
String fragment = sentence.substring(i, i + token.length());
if (fragment.equals(token)) return i;
}
return -1;
}
EDIT
Here is the full application using only length and charAt():
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
int indexOf = lastIndexOf("The quick brown fox jumps over the lazy dog.", "the");
System.out.print(indexOf);
}
public static int lastIndexOf(String sentence, String token) {
int startingIndex = sentence.length() - token.length();
for (int i = startingIndex; i >= 0; i--) {
String fragment = substring(sentence, i, i + token.length());
if (strEquals(token, fragment)) return i;
}
return -1;
}
public static String substring(String str, int startingIndex, int endingIndex) {
int size = endingIndex - startingIndex;
char[] arr = new char[size];
for (int i = 0; i < size; i++) {
arr[i] = str.charAt(startingIndex+i);
}
return new String(arr);
}
public static boolean strEquals(String s1, String s2) {
if (s1.length() != s2.length()) return false;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) continue;
return false;
}
return true;
}
}
EDIT 2
You also have a bug in the way you are reading your input. You need to use input.readLine() to get the full line. input.read breaks on spaces. Along those lines, you also need a new scanner for each line you want to read.
EDIT 3
Here is the whole source:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args)
{
Scanner input1 = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
String s1="";
String s2="";
int choice = input1.nextInt();
if(choice == 1) {
Scanner input2 = new Scanner(System.in);
System.out.println("Enter first string: ");
s1 = input2.nextLine();
Scanner input3 = new Scanner(System.in);
System.out.println("Enter second string: ");
s2 = input3.nextLine();
}
int indexOf = lastIndexOf(s1, s2);
System.out.println(indexOf);
}
public static int lastIndexOf(String sentence, String token) {
int startingIndex = sentence.length() - token.length();
for (int i = startingIndex; i >= 0; i--) {
String fragment = substring(sentence, i, i + token.length());
if (strEquals(token, fragment)) return i;
}
return -1;
}
public static String substring(String str, int startingIndex, int endingIndex) {
int size = endingIndex - startingIndex;
char[] arr = new char[size];
for (int i = 0; i < size; i++) {
arr[i] = str.charAt(startingIndex+i);
}
return new String(arr);
}
public static boolean strEquals(String s1, String s2) {
if (s1.length() != s2.length()) return false;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) continue;
return false;
}
return true;
}
}
import java.io.File;
import java.util.Scanner;
public class TestDriver {
public static void main(String[] args) {
Scanner x = null;
try {
x = new Scanner(new File("pokemon"));
} catch (Exception e) {
System.out.println("could not find file");
}
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Type in the number of Pokemons (1-15)!");
int userNumber = 0;
boolean userFalse = false;
while (!userFalse) { // Validates user inputs for years
if (input.hasNextInt()) {
int temp = input.nextInt();
if (temp < 1 || temp > 15) { // Years cannot be below 0
System.out.println("Invalid input.");
userFalse = false;
} else {
userFalse = true;
userNumber = temp;
}
} else {
System.out.println("Try Again!");
input.next();
}
}
String[] a = new String[userNumber];
for (int i = 0; i < userNumber; i++) {
a[i] = x.next();
System.out.print(a[i] + " ");
}
sort(a, userNumber);
}
In the pokemon.txt, it reads
Gyarados
Lapras
Eevee
Vaporeon
Snorlax
Abra
Slowbro
Rhyson
Kyogre
Blastoise
Jigglypuff
Miltank
Lugia
Steelix
Arbok
I am trying to sort the Pokemon NAMES from smallest to largest. I don't know the best way to do this. My teacher wants me to do it using recursion. Is that the same thing as quicksort or mergesort? Thanks in advance.
edit: Here's my attempt to sort using mergesort:
public static void sort(String[] pokemon, int userNumber) {
String[] a = new String[pokemon.length / 2]; // Split array into two
String[] b = new String[pokemon.length - a.length]; // halves, a and b
for (int i = 0; i < pokemon.length; i++) {
if (i < a.length)
a[i] = a[i];
else
b[i - a.length] = pokemon[i];
}
sort(a, userNumber); // Recursively sort first
sort(b, userNumber); // and second half.
int ai = 0; // Merge halves: ai, bi
int bi = 0; // track position in
while (ai + bi < pokemon.length) { // in each half.
if (bi >= b.length || (ai < a.length && a[ai].length() < b[bi].length())) {
pokemon[ai + bi] = a[ai]; // (copy element of first array over)
ai++;
} else {
pokemon[ai + bi] = b[bi]; // (copy element of second array over)
bi++;
}
}
}
Quicksort and Mergesort can both be implemented recursively. Since this is homework I will not be providing actual code but I will link you to a few places you can look:
Merge Sort
Quick Sort
I would like to have this code be able to locate more than one X and output it as Location1, location2,.......
i.e input: xuyx
i would have it output 0,3
import java.util.Scanner;
public class findinline {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str;
str = input.nextLine();
int pos = str.indexOf("x");
if (pos < 0){
System.out.println("No X Detected");
}
else{
System.out.println(pos);
}
}
}
String has the method indexOf(String str, int fromIndex) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
So just increment the starting index to where you found the last one.
String xStr = "xuyx";
int index = xStr.indexOf("x", 0);
while(index >= 0)
{
System.out.println(index);
index = xStr.indexOf("x", index + 1);
}
or better yet...
public List<Integer> getIndexesOfStr(String fullStr, String strToFind){
ArrayList<Integer> listOfIndexes = new ArrayList<>();
int index = fullStr.indexOf(strToFind, 0);
while(index >= 0)
{
listOfIndexes.add(index);
index = fullStr.indexOf(strToFind, index + strToFind.length());
}
return listOfIndexes;
}
You could do it like this. Iterate through the characters and print out the indexes where you hit an x.
boolean any = false;
for (int pos = 0; pos < str.length(); ++pos) {
if (str.charAt(pos)=='x') {
if (any) {
System.out.print(',');
}
any = true;
System.out.print(pos);
}
}
if (!any) {
System.out.println("No x found");
} else {
System.out.println();
}
Bear in mind you'd have to fix the case if you want to detect capital X as well.
Or, as kingdamian42 says, you could use indexOf(txt, fromindex)