Comparing character and String - java

I am writing a program to check wether the given sentence is a panagram or not, but I am not able to compare each character with the characters in a string.
Can anyone suggest me a method to get the desired output?
Scanner scan = new Scanner(System.in);
String panagram = scan.nextLine();
String word = panagram.toLowerCase();
System.out.println(word);
String a[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z" };
int count = 1;
System.out.println("a=" + a.length);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < word.length(); j++) {
if ((a[i]).equals(word.charAt(j)))// problem occurs here {
count++;
break;
}
}
}
if (count == 26) {
System.out.println("pangram");
} else {
System.out.println("not pangram");
}

You can use:
(a[i]).equals(String.valueOf(word.charAt(j)))
or change your a array from String[] to char[] and compare the character using the == operator.

You can convert it to a String and then compare it.
String s = Character.toString('c');
if(s.equals(s2)){..}
Or you could make it a String by adding it to an empty string.
String s = 'c' + "";
if(s.equals(s2)){..}
Or you could compare it's ascii value.
As there are only single characters, why don't you use a character array.
char []a = {'a', 'b', 'c'....};
if(a[i] == 'a')//you could use == in this case.
{..}
Also you don't need to check it that way.
You could create a boolean array of 26 size, as there are only 26 characters and check if every character is present atleast once or not
boolean []arr = new boolean[26];
for(int i = 0; i < word.length(); ++i)
{
arr[word.charAt(i) - 'a'] = true;
}
isPan(arr);
public boolean isPan(boolean[] arr)
{
for(int i = 0; i < arr.length; ++i)
if(!arr[i])
return false;
return true;
}
A simple O(n) solution.
Or you could use a Set and check it's size.
HashSet<Character> set = new HashSet();
for(int i = 0; i < word.length(); ++i)
set.add(word.charAt(i));
System.out.println(set.size() == 26 ? "Pangram" : "Not Pangram");
//A 2 liner would be
HashSet<Character> set = new HashSet<Character>(Arrays.asList(word.toCharArray()));
System.out.println(set.size() == 26 ? "Pangram" : "Not Pangram");
A point added by spookieCookie. These approaches apply only when the string has only lower case alphabets.
String s = "sdgosdgoih3208ABDDu23pouqwpofjew##$%^&".repalceAll("[^A-Za-z]+", "");
String s = s.toLowerCase();
//do the computation then

Convert the array into an arraylist
List<Character> alphabet = Arrays.asList(a);
Make a list to hold the characters that are read:
Set<Character> chars = new HashSet<>();
Then check whether every character in the sentence is part of the alphabet. Duplicates are not added due to the characteristics of Set
for (Character c : word.toCharArray()) {
chars.add(c);
}
Then check whether the size of the Set is equal to the given alphabet:
return (chars.size() == alphabet.size());

Try this instead:
public void checkPanagram() {
boolean isPanagram = false;
String word = "The quick brown fox jumps over the lazy dog";
String a[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z" };
for (int i = 0; i < a.length; i++) {
if (word.toLowerCase().contains(a[i])) {
isPanagram = true;
} else {
isPanagram = false;
break;
}
}
if (isPanagram) System.out.println("Yes, panagram");
else System.out.println("No, not panagram");
}

You can use String.contains(String) as every letter in a already is a String.
for (int i = 0; i < a.length; i++) {
if (word.contains(a[i])) {
count++;
// } else { break;
}
}
A remark: better use String[] a which is a more regular syntax instead of String a[] whose Syntax was added for C/C++ compatibility.

To check equality of a string with a char you could change your code minimally
if ((a[i]).equals(word.charAt(j)) to if ((a[i]).equals("" + word.charAt(j))
This gives you an equality check between two strings.
Alternatively you can change the line if ((a[i]).equals(word.charAt(j))
to if ((a[i]).equals(word.substring(j,j+1))

Related

How would you print a list (not java lingo, a literal list) more easily? [duplicate]

This question already has answers here:
How to join Array to String (Java)?
(6 answers)
Closed 3 months ago.
I was working on a project, and thought, Couldn't there be an easier way to write a list without having to waste 3 minutes and one line of code? I'm probably wasting even more time here, but suppose I want to spell out "Hello, world!":
class Main {
public static void main(String[] args) {
String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"};
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + "-"); // prints "H-E-L-L-O-, -W-O-R-L-D-!-"
}
}
}
As you can see there's a nagging dash hanging over the edge at the end of the line. One idea I had was doing this:
class Main {
public static void main(String[] args) {
String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"};
System.out.print(array[0]); // enter "H" early
for (int i = 1; i < array.length; i++) { // int i = 0 -> int i = 1
System.out.print("-" + array[i]); // switched order, prints "H-E-L-L-O-, -W-O-R-L-D-!"
}
}
}
Yes, this does complete the job, but I feel like the extra line is clunky and awkward in my code. Also, I don't feel it's exactly flexible?
If there's something inside the documentary junk or a trick I need, please let me know. :)
You can print the dash before the list element and if the list element is the first one, you don't print anything.
class Main {
public static void main(String[] args) {
String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"};
for (int i = 0; i < array.length; i++) {
System.out.print((i == 0 ? "" : "-") + array[i]); // prints "H-E-L-L-O-, -W-O-R-L-D-!"
}
}
}
You can use the iterator i in a ternary expression (i == array.length - 1 ? "" : "-") as a substitute for the constant "-". This way, whether or not there is a dash is dynamic, based on whatever you want. This is adaptable to lots of different scenarios.

Replace element in a String java

I am trying to remove some special char from my string and replace it with other string, i write this method but it not work fine :
private String nameNormalizer(String nameString) {
char[] LETTERS_TO_REPLACE = new char[]{
'À', 'Á', 'Â', 'Ã', 'Ä', 'Æ',
'È', 'É', 'Ê', 'Ë', '&',
'Ì', 'Í', 'Î', 'Ï',
'Ò', 'Ó', 'Ô', 'Ö', 'Œ',
'Ù', 'Ú', 'Û', 'Ü',
'Ç', 'Č',
'Ñ',
'Š', 'ß',
'Ž'
};
String[] LETTERS_REPLACEMENT = new String[]{ //
"A", "A", "A", "A", "AE", "AE",
"E", "E", "E", "E", "E",
"I", "I", "I", "I",
"O", "O", "O", "OE", "OE",
"U", "U", "U", "UE",
"C", "C",
"N",
"S", "SS",
"Z"
};
char[] surnameArray = nameString.toUpperCase().toCharArray();
int i_s = 0;
int k =0;
int len_s = LETTERS_TO_REPLACE.length;
int len_name = nameString.length();
StringBuilder sb_s = new StringBuilder();
while(k < len_name) {
String b_s = ;
while (i_s < len_s){
if((surnameArray[k] == LETTERS_TO_REPLACE[i_s])) {
b_s =(LETTERS_REPLACEMENT[i_s]);
break;
}
else{
b_s = "" + surnameArray[k];
i_s++;
}
}
sb_s.append(b_s);
k++;
}
String newName = sb_s.toString();
return newName;
}
My method replace only the first occurence and after append the original char element on newName ...
How i can match all char on string and edit it?

method/function to generate the column names for a spreadsheet application similar to Excel

I'm trying to achieve the below output, e.g if I pass 5 to the function columnNames, it should print A, B, C, D, E and if pass 27 it should print A, B, C, D, E...AA, AB, AC etc.
I need to work with the below code snippet and I only need to work on the columnNames method.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Tester {
static List<String> columnNames(int n) {
List<String> result = new ArrayList<String>();
return result;
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int _columns = Integer.parseInt(in.nextLine().trim());
List<String> result = columnNames(_columns);
System.out.println(String.join(", ", result));
}
}
when I added this snippet to the columnNames method and passed 5 to the parameter, it only prints the column letter equivalent to the number I entered. However, I expected to see A,B,C,D,E.
StringBuilder sb = new StringBuilder();
while (n > 0) {
for (int i = 0; i < n; i++) {
n--;
char ch = (char) (n % 26 + 'A');
n /= 26;
sb.append(ch);
result.add(sb.toString());
}
}
sb.reverse();
Thanks for the help.
I manage to figure it out with the code below. Thanks to those who have helped in a way.
static List<String> columnNames(int n) {
List<String> result = new ArrayList<String>();
String alphabets[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
StringBuilder sb = new StringBuilder();
for(int j = 0; j < n; j++){
int index = j/26;
char ch = (char) (j % 26 + 'A');
sb.append(ch);
String item = "";
if(index > 0) {
item += alphabets[index-1];
}
item += alphabets[j % 26];
result.add(item);
}
sb.reverse();
return result;
}
This is exactly what you want.
static List<String> columnNames(int n)
{
List<String> result = new ArrayList<String>();
String[] alphs = new String[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"};
if(n>-1 && n<27)
{
for(int i=0; i<n;i++)
{
result.add(alphs[i]);
}
}
else
{
for(int i=0;i<26;i++)
{
result.add(alphs[i]);
n--;
}
for(int i=0;i<result.size();i++)
{
for(int j=0; j<26; j++)
{
if(n!=0)
{
result.add(result.get(i).concat(alphs[j]));
n--;
}
else
{
return result;
}
}
}
}
return result;
}
This code produces what you want:
StringBuilder sb;
char current = 'A';
for (int i = 0; i < n; i++) {
// new StringBuilder for every String
sb = new StringBuilder();
// If 'i' exceeds letters, use the ones you have already added to your List
if (i > 25)
sb.append(result.get(i - 26));
// Append current character
sb.append(current);
// Add it to your List
result.add(sb.toString());
// Get the next letter while making sure it will not surpass 'Z'
if (current == 'Z')
current = 'A';
else
current = (char) (current + 1);
}
the code fails to exit and run for n > 702
Java Doodle link Work upto 'ZZ' sequence

Comparing charAt(x) to String array = letter [y]

I am trying to write a piece of code that produces a letter frequency using arrays. I am getting a bit stuck on how to compare a letter in a string to a letter in an array. my basic pseudo code is as follows.
import java.util.Scanner;
public class test {
public static void main (String[]args){
Scanner sc = new Scanner (System.in);
System.out.print ("Please enter a sentence: ");
String str = sc.nextLine();
String [] let = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
Float [] freq = new Float [25];
int x,a = 0,b = 0, strCount = 0;
String str1;
str1 = str.replaceAll(" ", "");
for (x = 0; x < str1.length(); x++)
{
strCount++;
}
System.out.println("The number of Characters in the string is :" + strCount);
System.out.println();
And now I'm stuck on how to compare the str1 to the let array. I have tried the following but it has a problem with the comparing.
while (b < strCount)
{
while (a < let.length)
{
if (let[a] == str1.charAt(b))
{
freq[a] = freq[a]++ ;
}
if(let[a] != str1.charAt(b))
{
a = a++;
}
}
b = b++;
}
Any help would be much appreciated.
Thank you.
Well, I see a number of other issues but the one you're asking about is simple enough.
if (let[a].charAt(0) == str1.charAt(b)) // <-- one letter
{
freq[a]++ ;
}
else
{
a++;
}
Also, strCount = str1.length(); with no need for a loop.
You might want to get rid of the risk of eternal loops by replacing your while loops with
for
loops.
Also,
a = a++;
is incorrect, while
a++;
or
a = a+1;
is correct.
Fix those two, and you will have fixed your problem.
Let me address some of the problems that seem to stand out. First of all, you might want to enlarge your Float[] since it has a size of 25 and there are 26 letters in the alphabet, meaning you would want to do Float[] freq = new Float[26]instead. Also, you use str.replaceAll(), but str.replace() will suffice - they both replace all matches in the string.
To count the number of occurrences, you may want to use str.charAt(index) or break it up into a char array (str.toCharArray()) to compare the character with the values stored in the array. Since they are all single characters, you might also want to store the values as the primitive char instead of as a String.
The two while loops are completely unnecessary, as it can be done with the one forloop. Also, use str.length() instead of creating your own variable and using a for loop to increment strCount, especially when you specify to loop through it str.length() times...

Iterate through List of single character strings using indexOf()

I'm making a program that will take an input string and decode it using the Rot13 encryption method. This takes the alphabet, and rotates it by 13.
I'm having a hard time getting the index of a letter in the list, and every time I run it it gives me -1 as if the item is not in the list. I looked in the java documentation, and indexOf() asks for an object. I tried explicitly typing my input as an object but that didn't work either.
This is the code I have so far:
package rot13;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
/**
*
* #author andrewjohnson
*/
public class CipherKey {
List<String> alpha = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ");
List<String> alphaRev = Arrays.asList("Z", "Y", "X", "W", "V", "U", "T", "S", "R", "Q", "P", "O", "N", "M", "L", "K", "J", "I", "H", "G", "F", "E", "D", "C", "B", "A", " ");
public String codeDecode(String s) {
System.out.println(s);
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
//System.out.println(ch);
int x = alpha.indexOf(ch);
//System.out.println(x);
String y = alphaRev.get(x);
System.out.print(y);
}
return null;
}
public static String readInput() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter message to be encoded or decoded");
String s = br.readLine().toUpperCase();
//System.out.println(s);
return s;
}
}
And my main():
/**
*
* #author andrewjohnson
*/
public class Rot13 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
CipherKey x = new CipherKey();
x.codeDecode(x.readInput());
}
}
I'm not sure why it is not working, but I've narrowed it down to the line:
int x = alpha.indexOf(ch);
Not being able to find ch in alpha. I'm new to Java and I've tried everything that I can think of. Thanks for your suggestions!
The problem is here:
char ch = s.charAt(i);
int x = alpha.indexOf(ch); // <-------- HERE
You are searching for a char in a String array. Which of course doesn't exist. Hense the -1
Change it to int x = alpha.indexOf("" + ch);
or int x = alpha.indexOf(Character.toString(ch));
or int x = alpha.indexOf(String.valueOf(ch));
Any of these will do.
ch is of type char and your list contains String. List may accept Object for indexOf, but the type still counts.
Change int x = alpha.indexOf(ch); to int x = alpha.indexOf(String.valueOf(ch)); to fix it.
Example:
System.out.println(alpha.indexOf('D'));
System.out.println(alpha.indexOf(String.valueOf('D')));
will print
-1
3
That is not the rot13 algorithm - you just appear to be reversing the alphabet. rot13 maps the range A - M to N - Z, and vice versa. Two invocations of rot13 give you back the original text.
ASCII letters follow a numerical sequence. Instead of performing a linear search through a list to find the matching index, it's far faster to just calculate the difference between the current letter and A, and then use that difference to offset into a second array of characters (or a string).
i.e.
static String map = "NOPQRSTUVWXYZABCDEFGHIJKLM"; // for rot13
function rot13(String input) {
StringBuffer output;
for (char ch : input) {
int index = ch - 'A';
if (ch >= 0 && ch < 26) {
output.append(map.charAt(index));
} else {
output.append(ch);
}
}
return output.toString();
}
NB: untested, may not compile, E&OE etc

Categories