I'm working on a code in which an input String is taken and an input character is taken. the code will calculate the percentage occurrence of that character in that String. the code is given below:
import java.util.Scanner;
class apple{
public static void main(String args[]){
int i,j,l=0;
float m;
char k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String");
String str = in.nextLine();
j=str.length();
System.out.println("Enter the character to be found");
char s = in.next(".").charAt(0);
for(i=0;i<=j;i++){
k = str.charAt(i);
if(k == s){
l++;
}
}
m= l/j;
m=m*100;
System.out.println("percent character in String is "+m);
}
}
Change your loop to
for(i = 0 ;i < j ; i++)
Otherwise, if your String has a length of 4 (so the last index is 3), it will try to reach index 4 and throw an Exception.
You are doing this:
for (i = 0; i <= j; i++) {
and this is throwing an java.lang.StringIndexOutOfBoundsException:
because you are not considering that the element goes from 0 to lengt-1
instead you should do:
for (i = 0; i < j; i++) {
Edit your for-loop to for (i=0;i<j;i++). We can not access the element at array size position because Java array uses 0-based index
The first character of a String is '0', the last is yourString.length()-1, so change your loop to
for( i = 0 ; i < j ; i++ ){
k = str.charAt(i);
if(k == s){
l++;
}
}
It'll work ;)
Related
Can anyone please explain the process of this for loop which comes first in the code. If you print these two lines in the console, you get output [0 0 0 1 2]. I don't know "how it works behind the scene to increment the character count every time".
for (int i=0; i<len; i++)
count[str.charAt(i)]++;
//Code
public class GFG
{
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str)
{
// Create array to keep the count of individual
// characters and initialize the array as 0
int count[] = new int[ASCII_SIZE];
// Construct character count array from the input
// string.
int len = str.length();
for (int i=0; i<len; i++) //bit confused lines
count[str.charAt(i)]++;
int max = -1; // Initialize max count
char result = ' '; // Initialize result
// Traversing through the string and maintaining
// the count of each character
for (int i = 0; i < len; i++) {
if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}
return result;
}
// Driver Method
public static void main(String[] args)
{
String str = "abcaa";
System.out.println("Max occurring character is " +
getMaxOccuringChar(str));
}
}
The for loop iterates over the string, the value of str.charAt(i) is the character of str at the index i.
Since every char corresponds to an int value (see more about that here) count[str.charAt(i)]++; increases the value of the count array at the index of the given char's corresponding int (see the ascii table to see which one that is).
So after the for loop count contains the number of occurences of every ascii character in str.
str.charAt(i) return char from str at the i position. Char can be used as index in array for example myarray['c'] because 'c' can be represented as number (see ASCII table).
So basically
for(int i=0; i<len; i++)
count[str.charAt(i)]++;
is counting how many times the same letter appears in string.
so for input string "aabc"
count['a'] = 2
count['b'] = 1
count['c'] = 1
Maximum occurring character in a single input string
public static char getMaxOccuringChar(String str) {
char result = ' ';
int len = str.length();
HashMap<Character, Integer> StrArray = new HashMap<Character, Integer>();
int val = 1;
for(int i =0; i<len; i++) {
char temp = str.charAt(i);
if(!StrArray.containsKey(temp)) {
StrArray.put(temp, val);
}else {
StrArray.put(temp, StrArray.get(temp)+1);
}
}
int MaxVal = 0;
for(char i : StrArray.keySet()) {
if(StrArray.get(i) > MaxVal) {
result = i;
MaxVal = StrArray.get(i);
}
}
return result;
}
I have string in java "naveen" i want output as "eennav". Please help me out in this. The idea is that the characters are to be ordered in order of frequency, and, where frequencies are the same, alphabetically.
Thanks
I have tried to find duplicates in the string , but am not able to get the required output .
String str="naveen";
int count =0;
char[] charr=str.toCharArray();
for(int i=0;i<charr.length;i++) {
//System.out.println(s[i]);
for(int j=i+1;j<charr.length;j++) {
if(charr[i]==(charr[j])) {
System.out.println(charr[i]);
}
Assuming the question is asking us to take a string containing only lower case letters and organize them by frequency of letters (high to low) and within that by alphabetical order, we can do it as below.
The strategy is first to make a pass through the characters of the input string and count the number of occurrences of each. Then we look through the counts for letters and find the largest. Working from the largest down to 1, we run through the alphabet for characters that occur that many times, and append that many of them to the result string.
There is a little bit of work involved here to convert back and forth from 'a' to 0 and 0 to 'a' and so on to 25 and 'z'.
This approach could be extended, but since the question didn't specify, I chose to make simplifying assumptions. I also did not work on optimizing, just getting it to work.
public class MyClass {
public static void main(String args[]) {
String str = "naveen"; //this string may change, but it is assumed to be all lower case letters by this implementation
int[] counts = new int[26]; //frequency count of letters a to z
for (int i = 0; i < 26; i++) {
counts[i] = 0; // intially 0 of any letter
}
char[] charr = str.toCharArray();
for (int i = 0; i < charr.length; i++) {
counts[(int)(charr[i]) - (int)('a')]++; // increment corresponding spot in counts array, spot 0 for 'a' through 25 for 'z'
}
int maxCount = counts[0]; // now find the most occurrences of any letter
for (int i = 1; i < counts.length; i++) {
if (counts[i] > maxCount) {
maxCount = counts[i];
}
}
String result = ""; // string to return
for (int j = maxCount; j > 0; j--) { // work down from most frequently occuring, within that alphabetically
for (int i = 0; i < 26; i++) {
if (counts[i] == j) {
//System.out.println("there are "+j+" of the letter "+(char)((int)('a'+i)));
for (int k = 0; k < j; k++) {
result = result + (char)((int)('a' + i));
}
};
}
}
System.out.println(result);
}
}
Write a program that uses a Scanner object to first read in a number that represents the size (n) of an array of Strings. Create an array of Strings that uses the first number as the size. You will then read in (n) cities all on the same line and store them in the array. Finally, you will read in a char (same line as the cities). Then program will then go through the array of cities and print the screen the number of times the char is in the city. Make sure you deal with case (A != a).
import java.util.Arrays;
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
String myarray[] = new String[length];
char ch;
for (int i = 0; i < myarray.length; i++) {
myarray[i]=scanner.next();
}
ch= scanner.next().charAt(0);
char ch1= Character.toUpperCase(ch);
char ch2= Character.toLowerCase(ch);
for(int y=0; y<myarray.length; y++){
int counter=0;
for(int z=0; z<myarray.length; z++){
if(myarray[y].charAt(z)==ch1){
counter++;
}else if(myarray[y].charAt(z)==ch2){
counter++;
}
}
System.out.print(counter+" ");
}
}
}
Example Input:
4
Toronto Halifax Truro Ottawa t
Example Output:
2 0 1 2
My Output:
1 0 1 2
To count amount of required character ignore case, you could use Character.toLowerCase() for character from string and required character. It is the same, when you do str.toLowerCase(), but without new string creation.
For this counting task, you do not need to modify string (like str.replaceAll()). In general you approach is fine, but you have some mistake in your for loops.
public class Problem {
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
int[] count = count(readCities(scan), readChar(scan));
System.out.println(Arrays.stream(count)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" ")));
}
}
private static String[] readCities(Scanner scan) {
String[] cities = new String[scan.nextInt()];
for (int i = 0; i < cities.length; i++)
cities[i] = scan.next();
return cities;
}
private static char readChar(Scanner scan) {
return scan.next().charAt(0);
}
private static int[] count(String[] cities, char ch) {
int[] count = new int[cities.length];
for (int i = 0; i < cities.length; i++)
for (int j = 0; j < cities[i].length(); j++)
if (Character.toLowerCase(cities[i].charAt(j)) == Character.toLowerCase(ch))
count[i]++;
return count;
}
}
for(int z=0; z<myarray.length; z++){
change the above mentioned for loop as below
for(int z=0; z<myarray[y].length(); z++){
myarray.length will represent total number of input string(4) i.e the loop will iterate until 4th character or a string , so the 1st string is "Toronto" and loop will iterate untill second occurence of 'o' remainings will not iterate.
myarray[y].length() will represent the total number of charactors in a string. So now the loop will iterate all the characters of a string.
First, it is often best to comment using // and /* text */
Second, your counter is isn’t working because you only count to the length of the array and not the String, but by using 'String.replaceAll(String, String);' and 'String.length()' you can count it.
This will give your char counter an error.
Input: 2 A B t
Using the variables
• length (int)
• myarray (String[])
• ch (char)
int[] countChar(int length, String[] myarray, char ch){
int[] result = new int [length]; // Method returns int[] result
for(int i=0; i<length; i++){
result[i] = myarray[i].length -
myarray[i].replaceAll(ch+"", "").length;
}
return result;
}
The code counts the char in the String like this. Worried about uppercase and lowercase? Use String.toLowerCase() and .toUpperCase() in your input.
[String length] - [String length after replacing char]
It is sometimes helpful to look at the comments. Look at Dave's and you'll find the error.
So , I am trying to create a program which calculates the score of an exam . What we have to do is give a pattern as a string consisting X's and 0's i.e 000XXX000XXX, where the value of 'X' is 0 and the value of each zero is 1 and for every consecutive '0' the value increases by 1 . If suppose there are 2 or more consecutive 0's and then an 'X' the value of '0' is reset to 1.if the program seems common to you , then , yes this is a problem from an OJ and it was given to me by a senior from my university to solve.Now the thing is I have figured out how the code works and solved the problem.But there seems to be an issue in the code.
package javaapplication4;
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T, score = 0, f = 0, g = 0;
String str;
int len;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
str = sc.nextLine();
len = str.length();
for (int j = 0; j < len; j++) {
if (str.charAt(j) == '0') {
f++;
score = score + f;
}
else if(str.charAt(j) == 'X')
{
f = 0;
score = score + g;
}
}
System.out.println(score);
}
}
}
As you can see from the code , I first give an Input for the number of test cases and as soon as I press enter , the code displays the value of score (which is 0) automatically without doing any think inside the for loop.
I have rechecked all the curly braces, but I cannot find the bug in the code. I would be happy if I could get some help.
Output:
4
0
The sc.nextInt() causes the sc.nextLine() to be triggered so you get the output of a empty string that's why it's zero, by using sc.nextLine() for input of your test case number you can prevent this:
int score = 0;
System.out.println("Enter test case:");
int testCase= Integer.parseInt(sc.nextLine());
for (int i = 1; i <= testCase; ++i)
{
System.out.println("Enter pattern:");
String str = sc.nextLine();
for (int j = 0; j < str.length(); j++)
{
if (str.charAt(j) == '0')
{
score += 1;
}
else if (str.charAt(j) == 'X')
{
score += 0;
}
}
System.out.println(score);
score = 0; // reset score to zero for the next test case
}
See this link regarding the sc.nextInt() issue : Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I am trying to create a program that will tell me how many times a letter appears in the array, so if the array contains {'a','c','b','a','b','a'} it will output:
a: 3
c: 1
b: 2.
I am building this program so I can learn how to think, so I want to do it with the basics only. No Hashmap and other more advanced things.
Edit: here is my answer, I succeeded create the program without Hashmap:
public class arrays5 {
public static void main(String[] args) {
char [] arr = {'a', 'b', 'a', 'c', 'b','a'};
char [] letters = new char[arr.length];
int count = 0;
char ch = '_';
boolean isInArray;
for (int i=0; i < arr.length; i++) {
isInArray = false;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == letters[j])
isInArray = true;
}
if (!isInArray)
letters[i] = arr[i];
}
int amountOfLetters = 0;
for (int i = 0; i < letters.length; i++) {
if (letters[i] != '\0')
amountOfLetters++;
}
int index = 0;
char [] newLetters = new char[amountOfLetters];
for (int i = 0; i < letters.length; i++) {
if (letters[i] != '\0') {
newLetters[index] = letters[i];
index++;
}
}
for (int k = 0; k < newLetters.length; k++) {
for(int i=0;i<arr.length;i++){
ch = arr[i];
count = 0;
for(int j=i;j<arr.length;j++){
if(arr[i] == arr[j])
count++;
}
if (ch == newLetters[k])
System.out.println(ch + ": " + count);
}
}
}
}
I created the temporary arrays so I can know when a char has already output and it will not show the same char more than once, but it didn't help, the output of this program is:
I would suggest using a HashMap.
Quick demo:
import java.util.HashMap;
public class Demo {
public static void main(String[] args){
char[] inputs = {'a','b','a','b','c','a'};
HashMap<Character, Integer> map = new HashMap<>();
for(Character c : inputs){
if(map.containsKey(c)){
Integer i = map.get(c);
i++;
map.put(c, i);
}
else{
map.put(c, 1);
}
}
System.out.println(map);
}
}
will output:
{b=2, c=1, a=3}
Where they key is your char and the number indicates how often it was in your array.
You can simply do this by using an array index for each element. This way you don't have to know the input but assumed all are small caps.
public class Demo {
public static void main(String[] args){
int[] count= new int[26]; // 26 elements for 26 letters
char[] inputs = {'a','b','a','b','c','a'}; // example input
for(Character c : inputs){
count[c-'a'] ++;
// if c='b', then c-'a' returns 1, thus increments the count[1].
}
for (int i=0; i<26; i++){
// using if condition I only print the previously encountered letters
if(count[i]>0)
System.out.println((char)(i+'a')+":"+count[i]);
}
}
}
This way time complexity is really low (Only O(number_of_inputs)).
I won't give you a full solution, however I'll try to guide you.
You can make a HashMap<Character, Integer>.
If the char already appears in the map, increment it's key by one, otherwise, add it to the map.
For example:
put('C', 1);
Then, assume it's 'C' again, you can do:
put('C', get('C') + 1);
Since the key of 'C' is 1, now when you put it, the key will be 2.
you can read the character using the scanner.next()
char c = scan.next().charAt(0);
you can change your code like below
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of array : ");
int n = scan.nextInt();
char[] arr = new char[n];
//Read inputs to array
for(int i = 0; i < n; i++)
{
arr[i] = scan.next().charAt(0);
}
//Main Logic
to optimize your code (Main Logic ) you can use hash table visit [http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html]
In java 8 it's one line:
return Arrays.stream(arr).collect(Collectors.groupingBy(String::valueOf, Collectors.counting()).get(input);