I am trying to write a program that counts the occurrence of letters in a string. For example, if the user inputs "Java", it will display "j: 1 a: 2 v:1". However, there seems to be something wrong with my program, and when I input the word java this is what it shows "j: 0 a: 1 v: 0"
Scanner myScanner = new Scanner(System.in);
String s = myScanner.nextLine();
int i = 0;
int j = 0;
int cnt = 0;
int length = s.length();
char ch;
for (i = 0; i < length; i++) {
ch = s.charAt(i);
if (s.indexOf(ch) < i)
continue;
for (j = (i + 1); j < length; j++) {
if (s.charAt(j) == ch)
cnt++;
}
System.out.println(ch + ": " + cnt);
cnt = 0;
}
Your desired output:
Enter your String: Mascarena
M: 1
a: 3
s: 1
c: 1
r: 1
e: 1
n: 1
Error in your code:
for (j = (i + 1); j < length; j++) { //It is omitting the first letter and searches the remaining
if (s.charAt(j) == ch)
cnt++;
}
Rectified:
for (j = 0; j < length; j++) { //For a specific letter searches the whole string.
if (s.charAt(j) == ch)
cnt++;
}
Your 2nd for-loop is not searching the entire word for each letter.
For example, when searching for j it is only looking at ava because it starts at i + 1 which is
(0 + 1) = 1
this a in the string java as j would be index at 0. Change
for (j = (i + 1)..)
to
(j = 0..)
public static String numberOfOccurence(String data) {
String result = "";
while (!data.isEmpty()) {
result += String.valueOf(data.charAt(0))+ StringUtils.countOccurrencesOf(data, String.valueOf(data.charAt(0)));
data = data.replaceAll(String.valueOf(data.charAt(0)), "");
}
return result;
}
input: aabacbd
output: a3b2c1d1
Related
In java, I am suppose to examine each character in the sentence, from left to right and count the number of identical characters to its right and print the count.
Scanner K = new Scanner(System.in);
String s = K.nextLine();
for (int i = 0; i < s.length(); i++) {
int count = 0;
while (i+1 < s.length() && s.charAt(i)== s.charAt(i + 1))
{
i++;
count++;
}
System.out.print(s.charAt(i)+ ":");
System.out.println(count);
}
System.out.println();
}
}
Example output should be like:(when i input "I love u")
I:0
: 1
l:0
o:0
v:0
e:0
:0
u:1
Given a string representing the starting number and a maximum number of changes allowed, create the largest palindromic string of digits possible or the string -1 if it's impossible to create a palindrome under the contstraints.
I wrote a code who answer on the questions, but i have an error that i dont know where it is, or if even the code work.
static String highestValuePalindrome(String s, int n, int k) {
for(int i =0 ; i < n ; i++){
char[] ch =s.toCharArray();
if(n==1)
return s ;
else if ((ch[i] != ch[n-i-1]) && (k != 0) ){
ch[i] = ch[n-i-1] = 9 ;
k--;
}
}
String str = new String(ch);
return str ;
}
Output Format
Print a single line with the largest number that can be made by changing no more than digits. If this is not possible, print -1.
Sample Input
n=4, k=1
3943
Sample Output
3993
Sample Input
n=6, k=3
092282
Sample Output
992299
Sample Input
n=4, k=1
0011
Sample Output
-1
First of all there is no need to pass n as a parameter because it's just the length of the string. Secondly, this is not the complete program. I have made many changes to the given code.
public class largestPalindorme {
public static void main(String[] args) {
System.out.println(highestValuePalindrome("0011", 1));
}
static String highestValuePalindrome(String s, int k) {
char[] ch = s.toCharArray();
int n = s.length(); // which is same as n which you passed as parameter
int minChangesRequired = MinumumChangesNeeded(s);
//if the changes required to make the given string a palindrome is less then k then only it will go inside or it will return -1
if (k >= minChangesRequired) {
int diff = 0;
if (k > minChangesRequired) {
diff = k - minChangesRequired;
for (int l = 0; l < diff; l++) {
ch[l] = '9';
ch[n - l - 1] = '9';
}
}
for (int i = diff; i < n - diff / 2; i++) {
if (ch[i] != ch[n - i - 1]) {
//if checks which number is greater
int greater = Integer.parseInt(String.valueOf(ch[i])) > Integer.parseInt(String.valueOf(ch[n - i - 1])) ? Integer.parseInt(String.valueOf(ch[i])) : Integer.parseInt(String.valueOf(ch[n - i - 1]));
//replaces the smaller number from the greater number.
if (Integer.parseInt(String.valueOf(ch[i])) != greater) {
ch[i] = ch[n - i - 1];
} else {
ch[n - i - 1] = ch[i];
}
}
}
String str = new String(ch);
return str;
}
return "-1";
}
//this function returns the minimum changes we need to do to make it a palindrome.
public static int MinumumChangesNeeded(String s) {
int count = 0;
char[] ch = s.toCharArray();
int n = s.length();
for (int i = 0; i < n / 2; i++) {
if (ch[i] != ch[n - i - 1]) {
count++;
}
}
return count;}}
I would like to write a function that will be reverse a number and then sum it up.
For example, the input string is
We have 55 guests in room 38
So the expected output should be
83 + 55 = 138
I have face a question is that I can't read the last number
example:
input string is '8 people'
output is 0
Here's the code I've written :
int total = 0;
String num = "";
String a = input.nextLine();
for (int i = a.length() - 1; i > 0; i--) {
if (Character.isDigit(a.charAt(i))) {
num += a.charAt(i);
if (!Character.isDigit(a.charAt(i - 1))) {
total += Integer.valueOf(num);
num = "";
}
}
}
All you really need to do is :
String input = "We have 55 guests in room 38";
int sum = 0;
String[] split = input.split(" "); // split based on space
for (int i = 0; i < split.length; i++) {
if (split[i].matches("[0-9]+")) {
sum = sum + Integer.parseInt(new StringBuffer(split[i]).reverse().toString());
}
}
System.out.println(sum);
Explanation:
Here we use regex to check if the String split contains only
digits.
Now we reverse the String and then parse it to an int before
summing.
Try this and works for any input in the form "We have x guests in room y". For your program however, instead if the for loop > 0 do > -1 I think:
Scanner scan = new Scanner(System.in);
scan.next(); scan.next();
String numberOne = "" + scan.nextInt();
scan.next(); scan.next(); scan.next();
String numberTwo = "" + scan.nextInt();
// String numberOne = "" + scan.nextInt(), numberTwo = "" + scan.nextInt();
String numberOneReversed = "", numberTwoReversed = "";
for(int k = numberOne.length() - 1; k > -1; k--)
numberOneReversed += numberOne.charAt(k);
for(int k = numberTwo.length() - 1; k > -1; k--)
numberTwoReversed += numberTwo.charAt(k);
int sum = Integer.parseInt(numberOneReversed) + Integer.parseInt(numberTwoReversed);
System.out.println("" + numberOneReversed + " + " + numberTwoReversed + " = " + sum);
scan.close();
Note for your program as defined in your question:
for (int i = a.length() - 1; i > -1; i--) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
and
if (i != 0 && !Character.isDigit(a.charAt(i - 1))) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
Will return the sum correctly.
Okay here is what I created using BigIntegers instead of ints:
public static BigInteger nameOfFunctionGoesHere(String input) {
BigInteger total = new BigInteger(new byte[] {0});
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total.add(new BigInteger(new String(flipped)));
i = j;
} else {
i++;
}
}
return total;
}
You can of course use ints as well like this:
public static int nameOfFunctionGoesHere(String input) {
int total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Integer.parseInt(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}
With longs too:
public static long nameOfFunctionGoesHere(String input) {
long total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Long.parseLong(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}
I'm trying to count each char in string for example:
Sample input: abababx
Sample output :
a appears 3 times
b appears 3 times
x appears 1 time
Here is what I've done :
String s = input.nextLine();
//Invoke the count method to count each letter
int[] counts = countLetters(s.toLowerCase());
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
System.out.println((char)('a' - i) + " appears " +
counts[i] + ((counts[i] == 1 ? " time" : " times")));
}
private static int[] countLetters(String s) {
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
}
return counts;
}
I'm getting:
a appears 3 times
` appears 3 times
J appears 1 time
Here is my code. I have to count the frequency of letters in my text.
I got as output:
a 21
b 28(should be 7)
c 34(should be 6)
I think my problem is it makes the sum and i dont want it.
int[] alphabetArray = new int[26];
// char varA = 'a';
alphabetArray[0] = A;``
int count = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == A) {
count++;
}
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");
alphabetArray[1] = B;
for (int i = 0; i < text.length; i++) {
if (text[i] == B) {
count++;
}
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
for (int i = 0; i < text.length; i++) {
if (text[i] == C) {
count++;
}
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");
return null;
Although you could fix your problem by zeroing out the count after printing, your program would not be ideal with the loop itself repeated three times. When you see a pattern like this, it's an indication that you need another loop.
Make a loop outside your current loop going through the letters from 'A' to 'Z'. Since letters' code points in UNICODE are consecutive, you can find the index of a letter by subtracting 'A' from it:
for (char letter = 'A' ; letter <= 'Z' ; letter++) {
int letterIndex = letter - 'A';
for (int i = 0; i < text.length; i++) {
if (text[i] == letter) {
alphabetArray[letterIndex]++;
}
}
}
Note that since you are accumulating counts for all letters, you do not need a separate count variable, because alphabetArray[letterIndex] replaces it. If you want to print letter frequency as you go, print alphabetArray[letterIndex] after the nested loop.
You initialized count=0 once and you are increasing it without re-initalizing it to 0.
int[] alphabetArray = new int[26];
// char varA = 'a';
alphabetArray[0] = A;``
int count = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == A) {
count++;
}
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");
alphabetArray[1] = B;
count=0;
for (int i = 0; i < text.length; i++) {
if (text[i] == B) {
count++;
}
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
count=0;
for (int i = 0; i < text.length; i++) {
if (text[i] == C) {
count++;
}
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");
return null;