Whitespace Location Finding - java

So the instructions I have are as follows:
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. Sample output for the given program:
Space at 1
The code I currently have written is:
import java.util.Scanner;
public class FindSpaces {
public static void main (String [] args) {
String passCode = "";
passCode = "A ";
if (Character.isWhitespace(passCode.charAt(0))){
System.out.println("Space at " +passCode.indexOf(" "));
}
else if (Character.isWhitespace(passCode.charAt(1))){
System.out.println("Space at " +passCode.indexOf(" ", 1));
}
else{
}
return;
}
}
Now this works sometimes but if I have more than one space in my input, it only ever prints one line. If it helps anyone, it is from zyBooks and I have no idea how to make it bring a second line showing a second whitespace.

When you do
if ( condition1 ) {
doSomething();
}
else if ( condition2 ) {
doSomethingElse();
}
the else means that you will only test condition2 (and so only have a chance of calling doSomethingElse()) if condition1 is false. You just need to remove that else from your code.

While the length might be limited to two, I still guess a for loop would fit better:
String passCode = "";
passCode = " ";
for (int i = 0; i < passCode.length(); i++) {
if (passCode.charAt(i) == ' ') {
System.out.println("Whitespace at index " + (i + 1));
}
}
To look at your solution: Your code can't enter any output for more than one time. You have if() else() - simply remove the else, and you should be fine:
String passCode = "";
passCode = " ";
if (Character.isWhitespace(passCode.charAt(0))) {
System.out.println("Space at " + passCode.indexOf(" "));
}
if (Character.isWhitespace(passCode.charAt(1))) {
System.out.println("Space at " + passCode.indexOf(" ", 1));
}

To find and print the location of each whitespaces in a string, you simply iterate through the string and check if the current character is a whitespace:
String str = "Find the space location";
for(int i = 0; i < str.length(); i++) {
if(Character.isWhitespace(str.charAt(i)) {
System.out.println("Space at " + i);
}
}

Related

Will Not Compare 2 strings that are equal that were read in from PrintWriter

I am writing a program that takes a document created by one program by PrinterWriter and then hashes the lines in that document to an array in the new program. The hash is done by using the ASCII code for the letter and adding them up. I am able to get the correct hash for each line and save it in the hash table. By the way, it is a list of countries that is hashed. My problem is that it does not seem to be able to compare the countries entered by the user, even though it is copy and paste, to the ones in the hash table to display them. It is not only supposed to display the country in the hash table, but all the ones leading up to the hash table. So if one was supposed to go to spot 23 but went to spot 26, display 23-26 to show clustering. I have tired everything to get it to work, but nothing seems to work, please help. I have included some of the code:
import java.io.PrintWriter;
import java.io.File;
import java.util.*;
import java.text.*;
public class Hashing
{
String[] line = new String[238];
String[] HashTable = new String[300];
public Hash() {
for (int i = 0; i< HashTable.length; i++) {
HashTable[i]=null;
}
}
public void readIn()throws Exception {
Scanner ln = new Scanner(new File(System.getProperty("user.home"), "user.home.CountryUnSortedFormat.txt"));
int i = 0;
while (ln.hasNextLine()) {
line[i] = ln.nextLine();
i++;
}
}
public int toASCII(String input) {
int total = 0;
char character;
String str = input.replaceAll(",","").trim();
if (str.length() > 50) {
for (int i = 0; i<50; i++) {
int ascii = str.charAt(i);
if (ascii > 32) {
total = total + ascii;
}
}
} else if (str.length()<50) {
for (int i = 0; i<str.length(); i++) {
int ascii = str.charAt(i);
if (ascii > 32) {
total = total + ascii;
}
}
}
return total % 300;
}
public void hashIt(String input, int where){
int counter = where;
if (where==299 && HashTable[where]!=null){
counter = 0;
}
while (HashTable[counter]!=null){
counter++;
}
System.out.println("Country = " + input + " HashValue = " + where + " actual HashSpot = " + counter);
HashTable[counter]=input;
}
public boolean showCountries(String paramCountry, int where){
int location = where;
int length = paramCountry.length();
while (!(HashTable[location].substring(0,length).contains(paramCountry))){
System.out.println("Input = " + paramCountry + " and HashTableCOunty = " + HashTable[location].substring(0,length));
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
if (!(HashTable[location].substring(0,length).contains(paramCountry))){
location++;
}
else if (HashTable[location].substring(0,length).contains(paramCountry)){
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
System.out.println("Eguals");
return true;
}
if (location==300||HashTable[location]==null){
System.out.println("End");
return false;
}
}
return false;
}
public void displayHashTable() {
for (int i = 0; i<HashTable.length; i++) {
System.out.println("i = " + i + " " + HashTable[i]);
}
}
public static void main(String[]args)throws Exception {
Scanner kb = new Scanner(System.in);
Hash H = new Hash();
H.readIn();
for (int i = 0; i< 238; i++) {
int where = H.toASCII(H.line[i]);
H.hashIt(H.line[i], where);
}
H.displayHashTable();
String UserChoice;
System.out.println("Enter the Name of the Country you wish to locate in the Hash Table or Enter -1 to quit: ");
UserChoice = kb.nextLine();
while (!(UserChoice.equalsIgnoreCase("-1"))) {
int index = H.toASCII(UserChoice);
boolean error = H.showCountries(UserChoice, index);
while (error == false) {
System.out.println("The country you searched for is not in the hash table. Try again.");
UserChoice = kb.nextLine();
index = H.toASCII(UserChoice);
error = H.showCountries(UserChoice, index);
}
System.out.println("Enter the Name of the Country you wish to locate in the Hash Table or Enter -1 to quit: ");
UserChoice = kb.nextLine();
}
}
}
Let us look at showCountries method:
public boolean showCountries(String paramCountry, int where) {
//....
return false;
}
I removed every line, that does not contain a return statement. As you can see, you always return false no matter if the searched element was found or not.
Therefore this loop:
while (error == false) {
//...
}
is like an infinite loop.
Change the code in your showCountries method to return true, it the country was found.
And consider changing the variable name error to something else. error == false sounds like "everything was ok", but this is not the case here.
If I understand your code correctly, you can change this:
else if (paramCountry.equals(HashTable[location].substring(0,length))) {
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
break;
}
to:
else if (paramCountry.equals(HashTable[location].substring(0,length))) {
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
return true;
}
Edit:
Another error-prone point is right here:
int length = paramCountry.length()-1;
while (!(paramCountry.equals(HashTable[location].substring(0,length)))) {
//...
You're cutting off the last character due to the usage of -1.
A small example:
paramCountry = "Eng";
HashTable[0] = "England";
int length = paramCountry.length()-1; // 2 (paramCountry.length() is 3)
And this are the results with the above values:
HashTable[0].substring(0,length)) // "En"
paramCountry.equals(HashTable[0].substring(0, length)) // "Eng".equals("En") -> false
So, you can remove that -1 or get rid of that substring and use contains instead.
Edit 2:
So, after your edit use contains instead of substring you only have one error left (the last one I cuurently see ):
while (!(HashTable[location].substring(0, length).contains(paramCountry))) {
// ...
}
return false;
Before you're calling the method showCountries you're calculating the possible position by calling H.toASCII(UserChoice);. This position is given to the method as location there it is used in the above while loop. This loop will be skipped, because the search country is already found. The bad thing is: you will return false in this case.
Now I suggest to change this return to return true; because this line will only be reached if the searched country was already found (and the while loop was skipped). If the country could not be found, you will return false in this if body: if (location==300||HashTable[location]==null).

Dot Counter issue

I have a homework assignment that requires me to write a program that counts the dots in an input line. So far this is what I have came up with it works (sort of)except that it is counting everything instead of only the dots. I am stuck with how to make the program to only count the dots.
import javax.swing.*;
import java.lang.Character;
public class Assign5_Polk {
public static void main(String[] args) {
String string = JOptionPane.showInputDialog("Give me dots and i will count them : ");
int count = 0;
for (int i = 0; i< string.length(); i++) {
char c = string.charAt(i);
if (string.contains(".")) {
count++;
}
}
System.out.println("There are" + " "+ count + " " + "dots" +" " + "in this string. " + string);
}
}
if (string.contains("."))
This line is checking the whole string and returning true if there is a . anywhere in it.
Instead, you want to test if c is a .
Change the if condition as below :
if (string.contains(".")) { // Check whole String contain dot
count++;
}
to
if (c == '.') { //Check single char of String contain dot
count++;
}
In your for loop, you repeatedly test if the entire string has dots, and increment the counter each time. You need something like if (c == '.') instead, to determine if the character you are looking at is a dot.
Solution without loop ;-)
count = string.replaceAll("[^.]","").length();
This makes your program pretty short:
public static void main(String[] args) {
String string = JOptionPane.showInputDialog("Give me dots and i will count them : ");
int count = string.replaceAll("[^.]","").length();
System.out.println("There are "+ count + " dots in this string: " + string);
}

Slicing a string

I'm trying to slice a string for the first time.
With this code, if I input, for example 'one two three' it works fine until the last word.
This is the last few lines of the output:
Current word is thr
Sentence is now e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(String.java:1907)
at TestCurr.main(testCurrentWord.java:18)
Has anyone any idea why it does that to the last word?
class TestCurr
{
public static void main (String []args)
{
String s;
int i;
String currentWord;
int length;
int spacePos;
System.out.println("Enter a sentence ");
s = EasyIn.getString();
spacePos = s.indexOf(" ");
length = s.length();
for (i = length -1; i >= 0; i--)
{
currentWord = s.substring(0,spacePos);
s = s.substring(spacePos +1);
System.out.println("Current word is " + currentWord);
System.out.println("Sentence is now " + s);
}
}
}
First of all, you call
spacePos = s.indexOf(" ");
length = s.length();
only once, but these values should change with each iteration of the loop. Furthermore,
s.substring(spacePos +1);
with
spacePos == s.length()-1
means you are passing an index beyond the end of the string as the start index for substring(). Once you fix the first error, this will be your next exception.
Your problem is that you only get the index of the space once. This causes the program to cut the string every three characters, as the first word is three letters long. You need to update spacePos after each iteration.
I believe your problem is in your usage of your spacePos variable.
Outside the loop, you initialize the variable like so:
spacePos = s.indexOf(" ");
Which in your example string of "one two three", yields 3.
But then inside your loop, you never set the variable again, based on what whatever is left that you haven't processed.
Try re-calculating spacePos's value inside the loop and your problem should go away.
Your current approach is too error prone.
And you have too many variables.
Try this just as an idea.
class TestCurr {
public static void main(String[] args) {
String s = null;
System.out.println("Enter a sentence: ");
s = " one two three ";
System.out.println("|" + s + "|");
int i = 0;
int j = 0;
while (true){
while (i<s.length() && s.charAt(i)==' ') i++;
j = i;
if (i>=s.length()) break;
while (i<s.length() && s.charAt(i)!=' ') i++;
System.out.println("Current word is: [" + s.substring(j, i)+ "]");
System.out.println("Sentence is now: [" + s.substring(i) + "]");
if (i>=s.length()) break;
}
}
}
As others have stated, you only get the index once. But I'm curious, why re-invent the wheel?
String s = "one two three";
String[] split = s.split(" ");
for (String out : split) {
System.out.println("Word: " + out);
}

How to equals a single character in string and then calculate it

"This is my code"
public static void main(String[] args) {
int letter_count = 0;
String check_word = new String ("How to equals a single character in string and then calculate it ");
String single_letter = " ";
int i = 0;
for ( i = 0; i < check_word.length(); i++ ) {
single_letter = check_word.substring(0);
if (single_letter.equals("a") ); {
letter_count ++;
}
}
System.out.println ( " - \"a\"" + " was found " + letter_count + " times");
}
You seem to be confused about what the substring function does. This line:
single_letter = check_word.substring(0);
essentially returns the whole of check_word and stores it inside of single_letter. I suspect what you actually wanted was this:
single_letter = check_word.substring(i, i + 1);
to get the single letter at that position.
You could also change it to:
if(check_word.charAt(i) == 'a') {
letter_count++;
}
One of your problems is that there is ; after your if (single_letter.equals("a") ) condition so your code
if (single_letter.equals("a") ); {
letter_count ++;
}
effectively is the same as
if (single_letter.equals("a") ){
//empty block "executed" conditionally
}
//block executed regardless of result in `if` condition
{
letter_count ++;
}
Other problem is that
single_letter = check_word.substring(0);
will get substring of check_word from index 0 which means that it will store same string as check_word. Consider using charAt method with i instead of 0. This will return simple char so you will need to compare it with == like check_word.charAt(i)=='a'.
Other (and probably better) approach would be just iterating over all characters of string with
for (char ch : check_word.toCharArray()){
//test value of ch
}
try...
public static void main(String[] args) {
int letter_count = 0;
char[] check_word = "How to equals a single character in string and then calculate it "
.toCharArray();
char single_letter = 'a';
for (int i = 0; i < check_word.length; i++) {
if (single_letter == check_word[i]) {
letter_count++;
}
}
System.out.println(" - \"a\"" + " was found " + letter_count + " times");
}
Why don't you use a character, like this:
public static void main(String[] args) {
int letter_count = 0;
String check_word = new String ("How to equals a single character in string and then calculate it ");
char toCheck = 'a';
for (int i = 0; i < check_word.length(); i++) {
char cursor = check_word.charAt(i);
if (cursor == toCheck) {
letter_count++;
}
}
System.out.println ( " - \"a\"" + " was found " + letter_count + " times");
}

For loop only loop 1 time JAVA?

I have a trouble with the for loop method that only loop 1 times whats is the problem? In the array was no problem at all, it able to print the value I want to.
here is my code:
public static void main(String[] args){
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++){
if(word[y].toString().equals("Apple2") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple3") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple4") ){
total++;
//str.append(word[y].toString());
}
else if(word[y].toString().equals("Apple1") ){
total++;
//str.append(word[y].toString());
}
}
System.out.println( word[0] + word[1] + word[2] + word[3] + word[4] + word.length);
System.out.println(str + "hihi" + total);
}
The others have nailed the cause of your problem. However, the fix they suggest is rather too specific ... and fragile. (Splitting with split("\\s*,\\s*") is better but it won't cope with whitespace at the start / end of the entire string.)
I suggest that you continue to use split(","), but trim the words before testing; e.g.
for (int y = 0; y < word.length; y++) {
String trimmed = word[y].trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
or better still:
String[] words = s.split(",");
for (String word : words) {
String trimmed = word.trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
That will make your code work irrespective of the whitespace characters around the commas and at the start and end of the string. Robustness is good, especially if it costs next to nothing to implement.
Finally, you could even replace the if / else if / ... stuff with a Java 7 String switch statement.
Try splitting on ", " (with space)
String[] word = s.split(", ");
without that space in split word[1] would look like " Apple1" instead "Apple1"
Other option would be calling word[y].trim().equals("Apple2") to get rid of that additional space, but I would say including it in split is better. If you aren't sure how many white-spaces can be near comma you can split this way split("\\s*,\\s*") to include all white-spaces around comma.
Also as Matt Ball pointed in his comment you don't need to call toString() on word[y] since it is already String.
you ignore the space during split. String[] word = s.split(", ");
You'are split by "," but your String contains ", ".
You can change the s.split(","); to s.split(", ");
Or trim the split's result like this :
public static void main(String[] args) {
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++) {
if (word[y].trim().equals("Apple2")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple3")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple4")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple1")) {
total++;
// str.append(word[y].toString());
}
}
System.out.println(word[0] + word[1] + word[2] + word[3] + word[4]
+ word.length);
System.out.println(str + "hihi" + total);
}
There is nothing wrong with your code but the problem lies in the String that you are giving to the variable.
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
Here the string contains spaces between them after the comma. So that when you split your string it splits like
word[0]= "Apple0"
word[1]= " Apple1"
word[2]= " Apple2"
word[3]= " Apple3"
and so on.
So that when you compare like
word[y].equals("Apple1") it returns false because " Apple1" and "Apple1" are two different strings. So that initialize your string like this
String s = "Apple0,Apple1,Apple2,Apple3,Apple4"; // without white spaces
It will work fine. Or you can use trim method in your existing code without changing String like
word[y].trim().equals("Apple1") //It will trim all the leading and trailing white spaces.
Hope this helps.

Categories