Reputation: 43
So I'm trying to write code to print the location of any space in the 2-character string passCode. Each space detected should print a separate statement followed by a newline.
i wrote this code and it would work until passcode = " ";
public class space{
public static void main(String args[]) {
String passCode = "";
passCode = "A ";
int p = passCode.length();
/*
for(int i = 0; i < p; i++) {
int b = passCode.charAt(i);
if(Character.isWhitespace(b)){
System.out.println("Space at " + passCode.indexOf(b));
}
}
}
}
however i found a way of doing it where it will evaluate correctly if passcode = " "; posted below
int indexOfSpace = passCode.indexOf(" ");
while(indexOfSpace >= 0){
System.out.println("Space at " + indexOfSpace);
indexOfSpace = passCode.indexOf(" ", indexOfSpace + 1);
}
could someone please explain to me why it works when both indexes are blank for the while loop and not the for loop ?
Thank you
Upvotes: 1
Views: 7084
Reputation: 11
This works but is very rudimentary:
import java.util.Scanner;
public class FindSpaces {
public static void main (String [] args) {
String passCode = "";
passCode = "A ";
boolean whitespaceAtZero = false;
boolean whitespaceAtOne = false;
whitespaceAtZero = Character.isWhitespace(passCode.charAt(0));
whitespaceAtOne = Character.isWhitespace(passCode.charAt(1));
if (whitespaceAtZero) {
System.out.println("Space at 0");
}
if (whitespaceAtOne) {
System.out.println("Space at 1");
}
return;
}
}
Upvotes: 1
Reputation: 592
Both of your solutions are correct, the problem is your print statements. Namely:
int b = passCode.charAt(i);
System.out.println("Space at " + passCode.indexOf(b));
Here you are retrieving the character at the given index, but your problem comes when you look up using the character. indexOf(char) returns the first index containing that character. Because the string has two of the same characters, it will always return the first index in this instance. You should print out your index instead:
System.out.println("Space at " + i);
Upvotes: 0