Function to Sanitize HTML Id attribute in Java - java

I have coded the next function. But surely someone has a more elegant way to perform this task.
/**
*
* HTML 4 Specification
* ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number
* of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
* #param s
* #return
*/
public static String sanitizeHTMLIdAttribute(String s) {
String sanitize = "";
if(s!=null) {
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '-' || s.charAt(i) == '_' || s.charAt(i) == ':' ||
s.charAt(i) == '.' || s.charAt(i) == '0' || s.charAt(i) == '1' ||
s.charAt(i) == '2' || s.charAt(i) == '3' || s.charAt(i) == '4' ||
s.charAt(i) == '5' || s.charAt(i) == '6' || s.charAt(i) == '7' ||
s.charAt(i) == '8' || s.charAt(i) == '9' ||
s.charAt(i) == 'a' || s.charAt(i) == 'b' || s.charAt(i) == 'c' ||
s.charAt(i) == 'd' || s.charAt(i) == 'e' || s.charAt(i) == 'f' ||
s.charAt(i) == 'g' || s.charAt(i) == 'h' || s.charAt(i) == 'i' ||
s.charAt(i) == 'j' || s.charAt(i) == 'k' || s.charAt(i) == 'l' ||
s.charAt(i) == 'm' || s.charAt(i) == 'n' || s.charAt(i) == 'o' ||
s.charAt(i) == 'p' || s.charAt(i) == 'q' || s.charAt(i) == 'r' ||
s.charAt(i) == 's' || s.charAt(i) == 't' || s.charAt(i) == 'u' ||
s.charAt(i) == 'w' || s.charAt(i) == 'x' || s.charAt(i) == 'y' ||
s.charAt(i) == 'z' ||
s.charAt(i) == 'A' || s.charAt(i) == 'B' || s.charAt(i) == 'C' ||
s.charAt(i) == 'D' || s.charAt(i) == 'E' || s.charAt(i) == 'F' ||
s.charAt(i) == 'G' || s.charAt(i) == 'H' || s.charAt(i) == 'I' ||
s.charAt(i) == 'J' || s.charAt(i) == 'K' || s.charAt(i) == 'L' ||
s.charAt(i) == 'M' || s.charAt(i) == 'N' || s.charAt(i) == 'O' ||
s.charAt(i) == 'P' || s.charAt(i) == 'Q' || s.charAt(i) == 'R' ||
s.charAt(i) == 'S' || s.charAt(i) == 'T' || s.charAt(i) == 'U' ||
s.charAt(i) == 'W' || s.charAt(i) == 'X' || s.charAt(i) == 'Y' ||
s.charAt(i) == 'Z') {
sanitize += s.charAt(i);
}
}
if(sanitize.length()>0) {
while(sanitize.charAt(0) == '0' || sanitize.charAt(0) == '1' ||
sanitize.charAt(0) == '2' || sanitize.charAt(0) == '3' ||
sanitize.charAt(0) == '4' || sanitize.charAt(0) == '5' ||
sanitize.charAt(0) == '6' || sanitize.charAt(0) == '7' ||
sanitize.charAt(0) == '8' || sanitize.charAt(0) == '9') {
sanitize = sanitize.substring(1, sanitize.length());
}
}
return sanitize;
}
return null;
}

I would do something like this:
/**
*
* HTML 4 Specification ID and NAME tokens must begin with a letter
* ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]),
* hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
*
* #param s
* #return
*/
public static String sanitizeHTMLIdAttribute(String s) {
if (s == null) return null;
StringBuilder sb = new StringBuilder();
int firstLegal = 0;
while (firstLegal < s.length() && !isAZ(s.charAt(firstLegal)))
++firstLegal;
for (int i = firstLegal; i < s.length(); ++i){
final char ch = s.charAt(i);
if (isOkIdInnerChar(ch)) sb.append(ch);
}
return sb.length() == s.length()? s : sb.toString();
}
private static boolean isOkIdInnerChar(char ch) {
return isAZ(ch) || isNum(ch) || isSpecial(ch);
}
private static boolean isSpecial(char ch) {
switch (ch) {
case '-': case '_':
case ':': case '.':
return true;
default:
return false;
}
}
private static boolean isAZ(char ch) {
return ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z');
}
private static boolean isNum(char ch) {
return '0' <= ch && ch <= '9';
}
... except that I'd probably prefer to throw an NullPointerException if s == null, and IllegalArgumentException if s contains no legal characters, but that's a matter of preference, of course. Some extra features:
If s is a valid ID, it's returned as-is to save space (fewer string instances floating around) and time (String construction is expensive -- yes, I know allocation is cheap, but there's more going on there than allocation).
I don't use Character.isDigit 'cause it returns true for all Unicode digits, including stuff like "٣"
I don't use Character.isLetter 'cause it returns true for all Unicode letters, including stuff like "å"

You could significantly shorten your code by using Character.isLetterOrDigit(char); e.g.
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isLetterOrDigit(c) || c == '.' || etc ...) {
}
}
You could do this in conjunction with storing the permitted punctuation characters in a Set; e.g.
private static final Set<Character> ALLOWED =
new HashSet<Character>(Arrays.asList('.', '-', '_', ':'));
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (ALLOWED.contains(c)) {
}
}

You might want to check the expressions (regex isn't my forte), but this should drop invalid characters:
private static Pattern INVALID_LEADING = Pattern.compile("^[^a-zA-Z]+");
private static Pattern INVALID = Pattern
.compile("[^\\w\\u002e\\u003a\\u002d\\u005f]+");
private static String sanitize(String id) {
Matcher matcher = INVALID_LEADING.matcher(id);
if (matcher.find()) {
id = matcher.replaceFirst("");
}
Matcher invalid = INVALID.matcher(id);
if (invalid.find()) {
id = invalid.replaceAll("");
}
return id;
}
If you aren't happy with regex, be aware that many of your characters are in contiguous ranges, so can be detected with methods like this:
private static boolean isLatinDigit(char ch) {
return ch >= '0' && ch <= '9';
}

Related

Word game importing TXT file

How would I go about setting up a point scoring Scrabble type game that only scans words in a word document. So, in the following code I would have a text file with 30 different words and then I wouldn't need a println of all the lines in the file with the points per work i.e racecar is 11 points
import java.util.HashMap;
import java.util.Map;
class Scrabble {
private String word;
Scrabble(String word) {
this.word = word;
}
int getScore() {
Map<Character, Integer> lettersMap = new HashMap<>();
String lettersCap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < lettersCap.length(); i++) {
if (lettersCap.charAt(i) == 'A' || lettersCap.charAt(i) == 'E' ||
lettersCap.charAt(i) == 'I' || lettersCap.charAt(i) == 'O' ||
lettersCap.charAt(i) == 'U' || lettersCap.charAt(i) == 'L' ||
lettersCap.charAt(i) == 'N' || lettersCap.charAt(i) == 'R' ||
lettersCap.charAt(i) == 'S' || lettersCap.charAt(i) == 'T') {
lettersMap.put(lettersCap.charAt(i), 1);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
}
if (lettersCap.charAt(i) == 'D' || lettersCap.charAt(i) == 'G') {
lettersMap.put(lettersCap.charAt(i), 2);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 2);
}
if (lettersCap.charAt(i) == 'B' || lettersCap.charAt(i) == 'C' ||
lettersCap.charAt(i) == 'M' || lettersCap.charAt(i) == 'P') {
lettersMap.put(lettersCap.charAt(i), 3);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 3);
}
if (lettersCap.charAt(i) == 'F' || lettersCap.charAt(i) == 'H' ||
lettersCap.charAt(i) == 'V' || lettersCap.charAt(i) == 'W' ||
lettersCap.charAt(i) == 'Y') {
lettersMap.put(lettersCap.charAt(i), 4);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 4);
}
if (lettersCap.charAt(i) == 'K') {
lettersMap.put(lettersCap.charAt(i), 5);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 5);
}
if (lettersCap.charAt(i) == 'J' || lettersCap.charAt(i) == 'X') {
lettersMap.put(lettersCap.charAt(i), 8);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 8);
}
if (lettersCap.charAt(i) == 'Q' || lettersCap.charAt(i) == 'Z') {
lettersMap.put(lettersCap.charAt(i), 10);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 10);
}
}
int totalValue = 0;
for (int j = 0; j < word.length(); j++) {
totalValue += lettersMap.get(word.charAt(j));
}
return totalValue;
}
}
Fill the Map once and use read from the file, I guess every line has only one word.
You can read the file from Files#lines and loop over every line and count the score of every word
public class Scrabble {
private static Map<Character, Integer> lettersMap = new HashMap<>();
static {
fillMap();
}
private static void fillMap() {
String lettersCap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < lettersCap.length(); i++) {
if (lettersCap.charAt(i) == 'A' || lettersCap.charAt(i) == 'E' || lettersCap.charAt(i) == 'I'
|| lettersCap.charAt(i) == 'O' || lettersCap.charAt(i) == 'O' || lettersCap.charAt(i) == 'U'
|| lettersCap.charAt(i) == 'L' || lettersCap.charAt(i) == 'N' || lettersCap.charAt(i) == 'R'
|| lettersCap.charAt(i) == 'S' || lettersCap.charAt(i) == 'T') {
lettersMap.put(lettersCap.charAt(i), 1);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
} else if (lettersCap.charAt(i) == 'D' || lettersCap.charAt(i) == 'G') {
lettersMap.put(lettersCap.charAt(i), 2);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 2);
} else if (lettersCap.charAt(i) == 'B' || lettersCap.charAt(i) == 'C' || lettersCap.charAt(i) == 'M'
|| lettersCap.charAt(i) == 'P') {
lettersMap.put(lettersCap.charAt(i), 3);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 3);
} else if (lettersCap.charAt(i) == 'F' || lettersCap.charAt(i) == 'H' || lettersCap.charAt(i) == 'V'
|| lettersCap.charAt(i) == 'W' || lettersCap.charAt(i) == 'Y') {
lettersMap.put(lettersCap.charAt(i), 4);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 4);
} else if (lettersCap.charAt(i) == 'K') {
lettersMap.put(lettersCap.charAt(i), 5);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 5);
} else if (lettersCap.charAt(i) == 'J' || lettersCap.charAt(i) == 'X') {
lettersMap.put(lettersCap.charAt(i), 8);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 8);
} else if (lettersCap.charAt(i) == 'Q' || lettersCap.charAt(i) == 'Z') {
lettersMap.put(lettersCap.charAt(i), 10);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 10);
}
}
}
public static int readFileAndGetScore(String fileName) {
int result = 0;
Files.lines(new File(fileName).toPath()).forEach(wordInLine -> {
result += getScore(wordInLine);
});
return result;
}
private static int getScore(String word) {
int totalValue = 0;
for (int j = 0; j < word.length(); j++) {
totalValue += lettersMap.get(word.charAt(j));
}
return totalValue;
}
}
main function
public static void main(String[] args) {
String fileName = "data.txt";
int totalScore = Scrabble.readFileAndGetScore(fileName);
System.out.println(totalScore);
}
The readability of your code is not really good and has a lot of more or less code duplicates.
Since you were asking about a good way to set up the scoring system of your class, I'd suggest that you initialize it only once and not each time your scoring-method is called. That means you should create a static Map and use a static initializer.
class Scrabble {
private static final Map<Character, Integer> POINTS_FOR_LETTER = new HashMap<>();
static {
addLettersWithPoints("AEIOULNRST", 1);
addLettersWithPoints("DG", 2);
addLettersWithPoints("BCMP", 3);
addLettersWithPoints("FHVWY", 4);
addLettersWithPoints("K", 5);
addLettersWithPoints("JX", 8);
addLettersWithPoints("QZ", 10);
}
private static void addLettersWithPoints(String chars, Integer points) {
for (char nextLetter : chars.toCharArray()) {
POINTS_FOR_LETTER.put(nextLetter, points);
POINTS_FOR_LETTER.put(Character.toLowerCase(nextLetter), points);
}
}
private static int getScore(String word) {
int score = 0;
for (char nextLetter : word.toCharArray()) {
score += POINTS_FOR_LETTER.get(nextLetter);
}
return score;
}
public static void main(String[] args) {
for (String word : Arrays.asList("Test", "Racecar", "PhysicsquestionWithXAndY")) {
System.out.println(word + " -> " + getScore(word));
}
}
}
Now you can get the score for a word by calling the getScore()-method as shown in the main-method.

How to use a switch...case loop in java inside a nested if...else if...else loop?

import java.util.Scanner;
import javax.lang.model.util.ElementScanner14;
class mudit {
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
System.out.print("Enter!!!");
final char n = input.next().charAt(0);
art :
if ((n >= 'a' && n <= 'z' ) || (n >= 'A' && n <= 'z'))
System.out.println(n + " is an alphabet.");
dart :
if ( n == 'a' || n == 'e' || n == 'i' || n == 'o' || n == 'u' || n == 'A' || n == 'E' || n == 'I' || n == 'O' || n == 'U')
System.out.println("VOWEL");
break dart;
else
System.out.println("CONSONANT");
break dart;
else if ( n * 1 == n)
System.out.println(n + " is a numerical value.");
else
System.out.println("Something else");
input.close();
}
}
When ever i run this code i run into an error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "else", delete this token
at mudit.main(mudd.java:28)
I want it to tell whether the entered charachter is an alphabet(vowel or consonant) or numerical
I am using vs code editor.
The problem is that the if statement block is more than one line. You can only use an if statement, else statement, or else if statement without curly braces if the block is only a single line. To fix this problem, simply wrap your conditions in curly braces.
On another note, breaking in this context doesn't do anything. You can only break out of a for-loop, advanced for-loop, while loop, do-while loop, and switch statement. I may have forgotten 1 or 2 scenarios so feel free to remind me!
If there is more then one line inside a "if" or "else" you need to enclose those statements with { }. This should work now.
import java.util.Scanner;
import javax.lang.model.util.ElementScanner14;
class mudit {
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
System.out.print("Enter!!!");
final char n = input.next().charAt(0);
art :
if ((n >= 'a' && n <= 'z' ) || (n >= 'A' && n <= 'z')) {
System.out.println(n + " is an alphabet.");
dart :
if ( n == 'a' || n == 'e' || n == 'i' || n == 'o' || n == 'u' || n == 'A' || n == 'E' || n == 'I' || n == 'O' || n == 'U') {
System.out.println("VOWEL");
break dart;
} else {
System.out.println("CONSONANT");
break dart;
}
}
else if ( n * 1 == n)
System.out.println(n + " is a numerical value.");
else
System.out.println("Something else");
input.close();
}
}

Read input from user and ignore the spaces between words, converting letters to telephone numbers

I've been trying to figure out how to ignore the blank space/digits/letters by using the character.isDigit & character.isLetter method when the users enters a String.. Can you guys please advise me?
When I tried the input with GETLOAN (Without the space) it works well...
But when I enter a space between e..g. Get Loan, the program shows an error..
public static void main(String[] args) {
String letters;
char phoneDigit;
Scanner kb = new Scanner(System.in);
System.out.println("Enter letters : ");
letters = kb.next();
for (int i = 0; i < 7; i++) {
phoneDigit = letters.charAt(i);
// Using character.isDigit...
if (Character.isDigit(phoneDigit) == true || Character.isLetter(phoneDigit) == true);
{
if (i == 3) {
System.out.println("-");
} //If
if (phoneDigit >= 'A' && phoneDigit <= 'C'
|| phoneDigit >= 'a' && phoneDigit <= 'c') {
System.out.println("2");
} else if (phoneDigit >= 'D' && phoneDigit <= 'F'
|| phoneDigit >= 'd' && phoneDigit <= 'f') {
System.out.println("3");
} else if (phoneDigit >= 'G' && phoneDigit <= 'I'
|| phoneDigit >= 'g' && phoneDigit <= 'i') {
System.out.println("4");
} else if (phoneDigit >= 'J' && phoneDigit <= 'L'
|| phoneDigit >= 'j' && phoneDigit <= 'l') {
System.out.println("5");
} else if (phoneDigit >= 'M' && phoneDigit <= 'O'
|| phoneDigit >= 'm' && phoneDigit <= 'o') {
System.out.println("6");
} else if (phoneDigit >= 'P' && phoneDigit <= 'S'
|| phoneDigit >= 'p' && phoneDigit <= 's') {
System.out.println("7");
} else if (phoneDigit >= 'T' && phoneDigit <= 'V'
|| phoneDigit >= 't' && phoneDigit <= 'v') {
System.out.println("8");
} else if (phoneDigit >= 'W' && phoneDigit <= 'Z'
|| phoneDigit >= 'W' && phoneDigit <= 'z') {
System.out.println("9");
} // If
} // If
} // For loop
} //PSVM
remove the semicolon(;) from here
if (Character.isDigit(phoneDigit) == true || Character.isLetter(phoneDigit) == true);//semicolon
; means end of statement.This means if conditions ended there.The statements under if will always be executed irrespective of what if returns(true or false) so the rest of statements under {} will simply behave as non static blocks
When I tried the input with GETLOAN (Without the space) it works well... But when I enter a space between e..g. Get Loan, the program shows an error..
You are getting error when you enter space because of the reason I specified above as the statements under if will always be executed
If you enter two words separated by a space, e.g. "get loan", the Scanner produces two output elements, i.e. the invocation of kb.next() just returns "get". A second invocation would return "loan". The Scanner class is not the right class to use for your purpose.
Use something like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
to read from the console.

System.out.print() is not displaying everything I expect and is unexpectedly printing new lines

System.out.print() is not displaying everything in the output box and when I enter to many characters it automatically makes a new line. I am entering 645 characters and when I press enter it should give me the corresponding 215 characters. Should i be using something other than System.out.print() for this?
import java.io.*;
public class Animal {
public static void main(String[] args) {
int A = 0;
int B = 1;
int C = 2;
System.out.print("codons=");
String str = read();
for (int num = 0; num <= str.length() / 3; num++) {
if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print("a");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print("b");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("c");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("d");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'A') {
System.out.print("e");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print("f");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("g");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("h");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print("i");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("j");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("k");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("l");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'A') {
System.out.print("m");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print("n");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print("o");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("p");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print("q");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print("r");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("s");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print("t");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("u");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print("v");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("w");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print("x");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'T') {
System.out.print("y");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("z");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("0");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("1");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("2");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'T') {
System.out.print("3");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print("4");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'G') {
System.out.print("5");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("6");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'T') {
System.out.print("7");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print("8");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print("9");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print(" ");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.println("");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print(">");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("<");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("+");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print("}");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("/");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("=");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print(".");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print("!");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print(":");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print("'");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print(",");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'G') {
System.out.print("#");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("-");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("newline");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("\\");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'A') {
System.out.print("{");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("(");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("&");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'G') {
System.out.print(")");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("$");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("]");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("#");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print(";");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print("*");
}
A += 3;
B += 3;
C += 3;
}
System.out.println("");
}
public static String read() {
byte[] buffer = new byte[647];
try {
int numBytes = System.in.read(buffer);
} catch (IOException e) {
System.out.print("Error: " + e);
System.exit(1);
}
String str = new String(buffer);
return (str);
}
public static void write(String str) {
System.out.print(str);
}
}
It's unclear what you're trying to do but I'll try to give you some pointers in the hope they will help solve your problem.
Format your code correctly. It's impossible to read otherwise.
Use meaningful variables names. A, B, C, and str are all meaningless. People (yourself included) will have an easier time reading your code if you provide hints via clear variable and method names.
When you find yourself re-writing the same lines of code over and over again (like your massive list of conditionals) that's a good hint you should restructure your code. It looks like you're trying to map groups of three characters to single characters, a Map<String, String> can do this easily in roughly three lines.
In that vein, look closely at the functionality provided by String, particularly String.substring() - you can get each three-letter substring easily, without manually extracting each character.
Avoid repeated function calls; even if you keep your str.charAt() behavior, you can put them at the top of your for loop and assign them to variables so they're only done once per iteration, then each conditional simply checks the variables. str.charAt() is fast, but many other methods aren't, and there's no need to waste the effort of calling the same method over and over again.
There's no need to directly read from System.in's byte stream. You can simply use a Scanner or if necessary a BufferedReader.
You have a println midway through your conditional block, for the first "GGG" case. Is that intentional? If not, it might be why you're seeing unexpected new lines. Otherwise, there's nothing in your code that will generate undesirable new lines, it's possible your terminal is simply wrapping the single line across multiple lines visually so you can see the whole output.
You never use your write() method; you should probably just delete that.
This will give you 215 characters, only if in your input string each time any if condition satisfied. Otherwise it will not be able to print anything. if you still think, that your input string satisfy the conditions and you are not getting output as expected then share your input for this program.
One more correction to your question, for the below condition, you are using System.out.println whereas for others it is System.out.print, if this condition get's satisfied then you will get the other characters in new line.
else if (str.charAt(A) == 'G' && str.charAt(B) == 'G'
&& str.charAt(C) == 'G') {
System.out.println("");
}

Converting charAt check 'containing A-Z' to 'not containing A-Z'

I would like to check if a String input contains characters other than alphabets. Below is my current code:
if ((name.charAt(i) >= 'a' && name.charAt(i) <= 'z') ||
((name.charAt(i) >= 'A' && name.charAt(i) <= 'Z')))
How can I change the code such that it functions as check if name.charAt(i) "is not equals to A to Z OR a to z?
Just negate your condition :
if (!((name.charAt(i) >= 'a' && name.charAt(i) <= 'z') || ((name.charAt(i) >= 'A' && name.charAt(i) <= 'Z'))))
String str = "1234";
if(!str.matches("[a-zA-Z]+")){
System.out.println("not contains alphabets");
}else{
System.out.println("contains alphabets");
}
I'll demonstrate a systematic approach to this which can help you in other similar situations. First, to improve readability, extract the char to a local var.
char ch = name.charAt(i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') ...
Now you can work with this in terms of DeMorgan's laws. To make things easier, I'll declare some helper boolean vars for each part:
boolean a = ch >= 'a',
z = ch <= 'z',
A = ch >= 'A',
Z = ch <= 'Z';
So, we have your original expression as
(a && z) || (A && Z)
We want the negative of that expression:
!(a && z || A && Z)
Let's clean it up. Apply
to get
!(a && z) && !(A && Z)
Then apply
to the inner expressions:
(!a || !z) && (!A || !Z)
Now substitute the original expresions back in, negating <= into >, >= into <:
(ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z')
this is the negated expression you are looking for, cleaned up of any explicit negations.
Instead of comparing characters for upper & lowercase, use Character.isLetter(char c) method as it checks for both the cases.
char[] chars = name.toCharArray();
boolean isAlphabet = true;
for (char c : chars) {
if (!Character.isLetter(c)) {
//if character is not A-Z or a-z
isAlphabet = false;
}
}

Categories