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

"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");
}

Related

A logic error is causing a statement to be printed twice in a While Loop

So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.
What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.
import java.util.Scanner;
public class StringChangerenter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
// While loop
while (!command.equalsIgnoreCase("quit")) {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
// Bracket for while loop
}
}
}
The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.
Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.
Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.
To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.
what is happening is, the condition for you while loop is
while (!command.equalsIgnoreCase("quit"))
which in english mean, as long as command is not equal to "quit" then run this loop.
Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1.
Then your logic sets command to "remove" here
command = keyboard.nextLine();
and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.
A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input
this is what you code would be if you explicitly took user consent if you want to run any more commands:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}

how can i count index of constants in word and sum its in java?

I cannot fix below mentioned issue. i want to see in console correct index of string which insert from scanner. but this code show index of first char which find and dont show correct sum of index of string:
public class task8 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Insert word:");
String str;
str = sc.nextLine();
char [] consonants = {'b', 'c', 'd', 'f','g','j','h','q','x','z','l','m','p','s','r' , 'n', 't'};
int conlenth = consonants.length;
int sum_ind =0;
for (int s=0; s < str.length(); s++){
for ( int i = 0; i < conlenth ; i++){
char ch_cons = consonants[i];
char ch_str = str.charAt(s);
int con_ind = str.indexOf(ch_str);
sum_ind = sum_ind + con_ind;
if (ch_str == ch_cons){
System.out.println( "cons. = " + ch_cons + " index = " + con_ind );
}
}
}
System.out.println("summ index = " + sum_ind);
}
}
For me, you should simply move the increment in the if test to increment only when we have a match, something like this:
...
int con_ind = str.indexOf(ch_str);
if (ch_str == ch_cons) {
sum_ind += con_ind;
System.out.println( "cons. = " + ch_cons + " index = " + con_ind );
}
Response Update:
You have 1 more issue in your program, you should not use str.indexOf(ch_str) to get the index of the current character as it will give you the index of the first character that matches in the complete String which is not correct if you have several times the same character in the input String, you should use simply s instead as you iterate already over the characters of the String.
The correct code is this:
main: for (int s=0; s < str.length(); s++){
char ch_str = str.charAt(s);
for ( int i = 0; i < conlenth ; i++){
char ch_cons = consonants[i];
if (ch_str == ch_cons){
sum_ind += s;
System.out.println( "cons. = " + ch_cons + " index = " + s );
continue main;
}
}
}
NB: To brake in the inner loop when we have a match, I use a label to go directly to the next iteration of the main loop.
Output:
Insert word:
hello
cons. = h index = 0
cons. = l index = 2
cons. = l index = 3
summ index = 5
A faster approach could be to use a switch statement instead of an inner loop, something like this:
for (int s=0; s < str.length(); s++){
char ch_str = str.charAt(s);
switch (ch_str){
case 'b':
case 'c':
...
case 'z':
sum_ind += s;
System.out.println( "cons. = " + ch_cons + " index = " + s );
break;
}
}

Split Numbers within parenthesis in Java

I would like to split this input: 12132002(177) 012(207.5) 014(184) into two arrays, like this:
num[500] = 12132002,012,014, etc.
and
mark[500] = 177,207.5,184, etc.
The Fact is that I'm accepting values from user like this, where i don't know the total number which he/she will input.
How can I code in Java that kind of splitting? Is it like this?
int number[500];
for(int i=0;i<500;i++) {
number=num.split("//(");
}
To code "that kind of splitting", you will have to:
Declare your variables: String[] number, String[] mark, String num, and String[] numSplit.
Split num by " " (spaces). Assign this to numSplit.
Loop through numSplit from 0 to numSplit.length with i.
Set number[i] to numSplit[i] from the beginning to the first occurrence of a "(".
Set mark[i] to numSplit[i] from one character after the first occurrence of "(" to one character before the end.
Output number and mark
The full code:
String[] number = new String[500]; //1
String[] mark = new String[500];
String num = "12132002(177) 012(207.5) 014(184)";
String[] numSplit = num.split(" "); //2
for(int i = 0; i < numSplit.length; i++) { //3
number[i] = numSplit[i].substring(0, numSplit[i].indexOf("(")); //4
mark[i] = numSplit[i].substring(numSplit[i].indexOf("(") + 1, numSplit[i].length() - 1); //5
}
for(int i = 0; i < number.length; i++) System.out.println(number[i]); //6
for(int i = 0; i < mark.length; i++) System.out.println(mark[i]);
Which outputs:
12132002
012
014
null (x497)
177
207.5
184
null (x497)
Notice that number, mark, and numSplit are String arrays because the leading zeros would be cut off in not otherwise. If you don't mind the leading zeros being cut off then you can change num to an int array and mark to a double array (Because of the decimal in 207.5).
Ok buddy, this could be a solution for your problem. I chose to use the methods I have already created for some other project, but I think those can fit for this purpose as well, instead of using some complex REGEX expression. The output is good, though you have to figure out the way you want to store num and mark variables (I suggest arrays). Hope I helped.
public class Example {
public static void main(String[] args) {
String s = "12132002(177)012(207.5)014(184)";
// output 12132002,012,014 && 177,207.5,184
// it works good with this string as well -> s = "12132002(177)012(207.5)014(184)111(024)";
int numOfParanthesis = numOfParanthesis(s, '(');
String num = "";
String mark = "";
// array which contains positions of (
int[] indexesOpening = indexes(s, '(');
// array which contains positions of )
int[] indexesClosing = indexes(s, ')');
// logic
for(int i = 0; i < numOfParanthesis; i++){
if(i == 0){
num = s.substring(i, indexesOpening[i])+",";
mark = s.substring(indexesOpening[i]+1,indexesClosing[i])+",";
}else if(i!=numOfParanthesis-1){
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i])+",";
mark += s.substring(indexesOpening[i]+1, indexesClosing[i])+",";
}else{
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i]);
mark += s.substring(indexesOpening[i]+1, indexesClosing[i]);
}
}
System.out.println(num);
System.out.println(mark);
}
// returns array of positions for the given character
public static int[] indexes(String s, char c){
int numOfParanthesis = numOfParanthesis(s, c);
int[] indexes = new int[numOfParanthesis];
int delimetar = s.indexOf(c);
for(int i = 0; i < numOfParanthesis; i++){
if(i != -1){
indexes[i] = delimetar;
}
delimetar = s.indexOf(c, delimetar+1);
}
return indexes;
}
// returns how many times a character repeats in a string
public static int numOfParanthesis(String s, char c){
int number = s.indexOf(c);
int i = 0;
while (number >= 0){
number = s.indexOf(c, number+1);
i++;
}
return i;
}
}
Try this:
public class Test {
public static void main(String[] args) {
// Guess this is a string since it is a mix of integers
// and non-integers, characters like '(', ')' and space.
String str = "12132002(177) 012(207.5) 014(184)";
System.out.println("Your string:");
System.out.println("str=\"" + str + "\"");
System.out.println();
// remove all ')' since they will not be used
// using space as a delimiter is enough
String str2 = str.replaceAll("\\)", "");
System.out.println("Your string after removing ')' character:");
System.out.println("str2=\"" + str2 + "\"");
System.out.println();
// Since your input has spaces, we split on spaces
String[] strings = str2.split("\\s+");
System.out.println("Result after splitting str2 by spaces:");
for (String s : strings) {
System.out.println(s);
}
System.out.println();
// Lets make two array
String[] num = new String[500];
String[] mark= new String[500];
// loop strings
int cnt = 0;
for (String s : strings) {
String[] a = s.split("\\("); // a[0]="012", a[1]="207.5"
num[cnt] = a[0];
mark[cnt] = a[1];
cnt++;
}
System.out.println("Result num: ");
System.out.print("num[500] = ");
for(String s : num) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
System.out.println("Result mark: ");
System.out.print("mark[500] = ");
for(String s : mark) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
}
}
Output:
Your string:
str="12132002(177) 012(207.5) 014(184)"
Your string after removing ')' character:
str2="12132002(177 012(207.5 014(184"
Result after splitting str2 by spaces:
12132002(177
012(207.5
014(184
Result num:
num[500] = 12132002,012,014, etc.
Result mark:
mark[500] = 177,207.5,184, etc.

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);
}

Insert a comma after each item but not the last item

I have a program in java that when you enter a sentence and the program tells you how many palindrome words there are and outputs the words. However, when I output the words I can't seem to get a comma after each output. For example if I input "Abba is running to the radar" It outputs that there's 2 palindromes and that the palindromes are "Abba radar". I however want it to output the palindromes as "Abba, Radar". No matter how I do it I can either get "Abba Radar" or "Abba, Radar". Any help would be appreciated.
The code
package strings;
import javax.swing.*;
public class Palindrome2 {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Words that are the same forwards and backwards are called palindromes.\nThis program determines if the words are palindromes.\n\nEnter a sentence(do not include a punctuation mark):");
String newWord[] = word.split(" ");
String palindromeWords = "";
int count = 0;
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
palindromeWords = palindromeWords + " " + newWord[i];
}
}
JOptionPane.showMessageDialog(null, "There are " + count + " palindromes in this sentence");
if (count != 0) {
JOptionPane.showMessageDialog(null, "The palindromes are:\n" + palindromeWords);
} else {
JOptionPane.showMessageDialog(null, "There isn't any palindromes.");
}
}
}
Just modify your code to:
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
palindromeWords = palindromeWords + newWord[i] + ",";
}
}
After the for loop, substring it to remove the last comma:
palindromeWords = palindromeWords.substring(0,palindromeWords.length()-1);
The code could also be
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
if (count > 1)
{
palindromeWords += ", ";
}
palindromeWords += newWord[i];
}
The comma goes before the new word after the first was found...
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Words that are the same forwards and backwards are called palindromes.\nThis program determines if the words are palindromes.\n\nEnter a sentence(do not include a punctuation mark):");
String newWord[] = word.split(" ");
StringBuffer palindromeWords = new StringBuffer();
int count = 0;
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
if (count > 0) {
palindromeWords.append(",");
}
palindromeWords.append(newWord[i]);
count++;
}
}
JOptionPane.showMessageDialog(null, "There are " + count + " palindromes in this sentence");
if (count != 0) {
JOptionPane.showMessageDialog(null, "The palindromes are:\n" + palindromeWords.toString());
} else {
JOptionPane.showMessageDialog(null, "There isn't any palindromes.");
}
}
So I altered palindromewords to be a StringBuffer and moved the count++ after the append operation. Hope this helps!

Categories