How to Check Every Letter as a String - java

I'm failing the following test case:
#Test (timeout=3000) public void gatenot_0(){
GateNot g = new GateNot (new Wire("inw"), new Wire("outa"));
g.feed("0");
boolean ans = g.propagate();
assertEquals(sigs1, g.read());
}
which says "Invalid character" - Exception thrown by the following method:
public static List <Signal> fromString(String inps)
{
List<Signal> values = new ArrayList<Signal>();
for(int i = 0; i < inps.length(); i++)
{
if(inps.charAt(i) != '1' && inps.charAt(i) != '0'
&& inps.charAt(i) != 'X' && inps.charAt(i) != 'x'
&& inps.charAt(i) != ' ' && inps.charAt(i) != '\t')
throw new ExceptionLogicMalformedSignal(inps.charAt(0), "Invalid character!");
else if(inps.charAt(i) == '1')
values.add(HI);
else if(inps.charAt(i) == '0')
values.add(LO);
else if(inps.charAt(i) == 'X')
values.add(X);
else if(inps.charAt(i) == 'x')
values.add(X);
}
return values;
}
Everytime I pass something including "0" or "1" it throws Exception So, should I check every letter of String inps as a String instead of charAt(). If yes, how should I check that? Thanks in advance.

To check every letter as a string you could use
Character.toString(inps.charAt(i))
instead of just inps.charAt(i)
I would recommend storing it in a variable for each iteration instead of calling many times.
You could also do
String.valueOf(inps.charAt(i))
There is a shortcut
inps.charAt(i) + ""
And yet another way:
inps.substring(i, i + 1)
Note that if you end of converting each letter to string, you should use the .equals method when comparing them.
For more information about this, you can look at How to convert a char to a String?

Related

Of the two constructers one works and the other doesn't when the argument is correct

i'm new to programming. i don't understand why one of the constructers I'm using to check for the validity of the characters of a string argument in the constructer does not work. the constructer should check if the entered string contains only characters G,C,A,T, else it throws an IllegalArgumentException.
I tried using an array of characters to check for the validity of the string by using the toCharArray() method on the entered string. the constructer works for invalid strings, but not for valid strings. but another constructer i used works. please let me know why the first one doesn't.
//this is the first constructer that doesn't work for me
public class Fragment {
private String nucleotideSequence;
public Fragment(String nucleotides) throws IllegalArgumentException {
char[] validityCheck = nucleotides.toCharArray();
int validityCounter = 0;
for (char c : validityCheck) {
if(c != 'G' || c != 'C' || c != 'A' || c != 'T') {
validityCounter++;
}
}
if (validityCounter != 0) {
throw new IllegalArgumentException("Invalid characters present");
}
nucleotideSequence = nucleotides;
}
}
// this is the second constructer that works
public class Fragment {
private String nucleotideSequence;
public Fragment(String nucleotides) throws IllegalArgumentException {
boolean k = false;
for(int i = 0; i < nucleotides.length(); i++){
char lol = nucleotides.charAt(i);
if(lol=='A'||lol=='G'||lol=='C'||lol=='T'){
k = true;
}
else{
k = false;
}
if(k == false){
throw new IllegalArgumentException("Dosent work");
}
nucleotideSequence = nucleotides;
}
}
}
Your problem in the constructor that is not working is with the following 'if' statement:
if(c != 'G' || c != 'C' || c != 'A' || c != 'T')
This statement is always true. So the following:
for (char c : validityCheck) {
if(c != 'G' || c != 'C' || c != 'A' || c != 'T') {
validityCounter++;
}
}
equals:
for (char c : validityCheck) {
validityCounter++;
}
the correct statement would be
if(c != 'G' && c != 'C' && c != 'A' && c != 'T') {

How do I handle punctuation in this Pig Latin translator?

The rest of the code is working perfectly but I cannot figure out how to prevent punctuation from being translated.
public class PigLatintranslator
{
public static String translateWord (String word)
{
String lowerCaseWord = word.toLowerCase ();
int pos = -1;
char ch;
for (int i = 0 ; i < lowerCaseWord.length () ; i++)
{
ch = lowerCaseWord.charAt (i);
if (isVowel (ch))
{
pos = i;
break;
}
}
if (pos == 0 && lowerCaseWord.length () != 1) //translates if word starts with vowel
{
return lowerCaseWord + "way"; // Adding "way" to the end of string
}
else if (lowerCaseWord.length () == 1) //Ignores words that are only 1 character
{
return lowerCaseWord;
}
else if (lowerCaseWord.charAt(0) == 'q' && lowerCaseWord.charAt(1) == 'u')//words that start with qu
{
String a = lowerCaseWord.substring (2);
return a + "qu" + "ay";
}
else
{
String a = lowerCaseWord.substring (1);
String b = lowerCaseWord.substring (0,1);
return a + b + "ay"; // Adding "ay" at the end of the extracted words after joining them.
}
}
public static boolean isVowel (char ch) checks for vowel
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
{
return true;
}
return false;
}
}
I need the translation to ignore punctuation. For example "Question?" should be translated to "estionquay?" (question mark still in the same position and not translated)
As Andreas said, if the function is expecting only one word, it should be the responsibility of the calling function to ensure there's no full sentence or punctuation being passed to it. With that said, if you require the translator to handle this, you need to find the index of the string where the punctuation or non-letter character occurs. I added in a main method to test the function:
public static void main(String[] args) {
System.out.println(translateWord("QUESTION?"));
}
I added a loop into the qu case to find the punctuation being input, the two checks are to see if the character at position i is inside the range of a - z. The sub-string then only goes to the point where the punctuation is found.
int i;
for (i = 0; i < lowerCaseWord.length(); i++) {
if(lowerCaseWord.charAt(i) > 'z' || lowerCaseWord.charAt(i) < 'a') {
break;
}
}
String a = lowerCaseWord.substring (2, i);
String b = lowerCaseWord.substring(i);
return a + "qu" + "ay" + b;
This may need some tweaking if you're worried about words with hyphens and whatnot but this should put across the basic idea.
Here's the output I received:
$javac PigLatintranslator.java
$java -Xmx128M -Xms16M PigLatintranslator
estionquay?

Take a string as input and returns valid if it is composed entirely of the characters A, T, C, and G in Java

So, I have this class that takes a string as an argument and returns valid if it is only composed of the characters A, T, C, and G. This is what I have so far.
public class test {
public static void main(String[] args) {
String s = args[0];
for(int i = 0; i < s.length(); i++) {
char chr = s.charAt(i);
if(chr != 'A' || chr != 'C' || chr != 'T' || chr != 'G') {
System.out.println("invalid");
break;
}
System.out.println("valid");
}
}
}
It is returning invalid for everything when CTGATCG should return valid and DGHAIS should return invalid.
I can't figure out what I'm doing wrong. Any ideas?
You have to change your if-statement from:
if(chr != 'A' || chr != 'C' || chr != 'T' || chr != 'G') {
to
if(chr != 'A' && chr != 'C' && chr != 'T' && chr != 'G') {
Each char is not equal to either A or C or the other ones. In your current version, you are basically excluding everything.
Furthermore, you would print "valid" for every char in your input.
The correct code should look like this:
String s = args[0];
for(int i = 0; i < s.length(); i++) {
char chr = s.charAt(i);
if(chr != 'A' && chr != 'C' && chr != 'T' && chr != 'G') {
System.out.println("invalid");
return;
}
}
System.out.println("valid");
If you want to do more stuff in your program, you should use a boolean variable in this case.
How about this:
public class test {
public static void main(String[] args) {
String s = args[0];
if(!s.matches("[ACGT]+")
System.out.println("invalid");
else
System.out.println("valid");
}
}
You don't need all that code. 1 line is all you need:
public static void main(String[] args) {
System.out.println(args[0].matches("[ACGT]*") ? "valid" : "invalid");
}
This code will perform pretty well too.
You should not use || (OR) in this case, you should use && (AND).
Your condition now means "If the character is not A,C,T,G at the same, it is invalid".

String Index out of bounds exception when using blank space

I'm making a chatbot, and it needs to break down every sentence into an array list of strings. It gives me a string index out of bounds exception whenever I use a space. I honestly don't know what to do about this, I've looked all over the forums, please help.
char tempChar;
String tempLetter;
String tempString = "";
for (int i = 1; i <= input.length(); i++) {
Scanner breakDownScan = new Scanner(input);
tempChar = breakDownScan.next().charAt(i-1);
if (tempChar != ' ' && tempChar != '.' && tempChar != '!' && tempChar != '?') {
tempLetter = Character.toString(tempChar);
tempString += tempLetter;
}
if (tempChar == ' ' || tempChar == '.' || tempChar == '!' || tempChar == '?') {
System.out.println("test");
words.add(tempString);
}
if (i == input.length()) {
breakDownScan.close();
}
}
Thank you in advanced for any and all help you can provide :D
Just use the split method. Example:
String[] words = input.split(insert your desired parser here);
I do believe you can do just the same with an Array List :)
(for the parser, use a space(" "), or what ever your words are separated by)

Recursive Substrings out of bounds error

I have to create a recursive method to display all substrings of a given string before the letter 'A' or 'a', and ignore that letter in the process. The termination condition works fine. However, in the continue condition I am thrown a indexoutofbounds error and I'm not entirely sure why. As far as I can tell I stop the loop before the index reaches the string's length. but I will post it here in case I missed something.
class Tree
{
void subStrings(String s)
{
if(s.length() == 1)
{
if(s.charAt(0) == 'A' || s.charAt(0) == 'a')
{
System.out.println("Cannot shorten substring.");
}
else
{
System.out.println(s);
}
}
else
{
String subString = "";
int i = 0;
while(s.charAt(i) != 'A' && i < s.length())//bad line
{
subString += s.charAt(i);
i++;
}
if(subString.equals(""))
subStrings(s.substring(i));
else
{
System.out.println(subString);
subStrings(s.substring(i));
}
}
}
int treeHeight(String tree)
{
return 0;
}
}
Even Robby's refactoring won't get you where you won't on account of some other issues. For what concerns your exception you must iterate to i < s.length() - 1 since you're incrementing the index in the loop, and charAt method you use inside the loop starts at index 0.
Checked further and you should change your substring(i) to subStrings(s.substring(0, i)) otherwise you would end up with the same string in recursion. The following should work for you
void subStrings(String s)
{
if(s == null || s.length() == 0 || s.charAt(0) == 'A' || s.charAt(0) == 'a')
{
System.out.println("Cannot shorten substring.");
return;
}
if(s.length() != 1)
{
String subString = "";
int i = 0;
while(s.charAt(i) != 'A' && s.charAt(i) != 'a' && i < s.length() - 1)//bad line
{
subString += s.charAt(i);
i++;
}
if(subString.equals(""))
subStrings(s.substring(i));
else
{
System.out.println(subString);
subStrings(s.substring(0, i));
}
}
}
You need to reverse these two conditions:
while(s.charAt(i) != 'A' && i < s.length()) { /*...*/ }
So, it should be:
while(i < s.length() && s.charAt(i) != 'A') { /*...*/ }
Otherwise you get an out of bounds exception when the string is empty and you try to access the first character (at position 0).
If you just want to split a string using a or A as a delimiter, you might as well do:
String[] substrings = str.split("[aA]");
If it absolutely has to be implemented using a recursive method, instead of processing the string character by character, you could use indexOf to find the position of the next a or A. It could look something like this:
public static void subStrings(String s) {
int i = s.toLowerCase().indexOf('a');
if (i >= 0) {
System.out.println(s.substring(0, i));
if (i + 1 < s.length()) {
subStrings(s.substring(i + 1));
}
}
}

Categories

Resources