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)
Related
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?
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".
I am creatings a simple Java program that in the main class asks for a string (input) and then prints out how many vowels (int count) and consonants are in the string. The number of vowels works perfectly however the number of consonants double, so the string "James" has 2 vowels and 6 consonants according to my program.
public class counter {
vowels p1 = new vowels();
public int con = 0;
public int count() {
String input = p1.getInput();
int i = 0;
int count = 0;
while (i < input.length()){
if (input.charAt(i) == 'a' || input.charAt(i) == 'e' || input.charAt(i) == 'i' || input.charAt(i) == 'o' || input.charAt(i) == 'u') {
count++;
} else if (input.charAt(i) != ' ') {
con++;
}
i++;
}
return count;
}
public int con() {
return con;
}
}
You are using an instance member con for counting the consonants, and you don't initialize it at the beginning of the count method, so multiple calls to that method will result in invalid counts.
seems like you are using
int con=0;
is used for consonant count
so instead of using
else if (input.charAt(i) != ' ') {
con++;
}
simply use
else {
con++;
}
Alternate :
subtract the vowel count from string length
'com = P1.length()-count;'
Try to set the variable con to zero at the begining of the method "count".
con = 0;
I hope it works.
char ch;
for(int i = 0; i < str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
count ++;
else
con;
}
you had nod consider the case when vowels are in caps I solved this in my code
hope my code helps you in this regard thanks.Happy coding
I'm working on a Pig Latin translator for a class. I had my program working before; it was printing out in the bottom for loop from the translatedWords array list. But the latest version does not print in the bottom for loop. I suspect it's a curly bracket but I can't seem to find it.
package stringTest;
import java.util.ArrayList;
public class StringTest {
public static void main(String[] args) {
String userString = "THIS IS A STRING";
// We might need to trim the string first it throws an error if theres
// white space around word
// Making string lowercase, first
userString = userString.toLowerCase();
// Splitting up string into individual words
String[] stringArray = userString.split(" ");
ArrayList<String> translatedWords = new ArrayList<String>();
// going through each string with foreach loop
for (String ss : stringArray) {
System.out.println("prints here in intial for loop");
// pulling out the words that start with a vowel
// since they just get "way" at the end
if (ss.charAt(0) == 'a' || ss.charAt(0) == 'e'
|| ss.charAt(0) == 'i' || ss.charAt(0) == 'o'
|| ss.charAt(0) == 'u') {
ss = ss.concat("way");
translatedWords.add(ss);
}
// If the words don't start with a vowel
// trying to figure out how to cut them at first vowel and
// concatenate to end
else {
for (int i = 0; i < ss.length();) {
if (ss.charAt(i) == 'a' || ss.charAt(i) == 'e'
|| ss.charAt(i) == 'i' || ss.charAt(i) == 'o'
|| ss.charAt(i) == 'u') {
ss = ss.substring(i, ss.length());
String sss = ss.substring(0, i + 1);
String ss44 = ss.substring(i + 1);
String ss33 = ss44 + sss;
ss33 = ss33 + "ay";
translatedWords.add(ss33);
System.out.println(ss33);
System.out.println("Why won't this print");
break;
}
}
}
for (String fs : translatedWords) {
System.out.print(fs.toString() + " ");
}
}
}
}
It's not a curly bracket but the for loop is running infinitely
The i is never incremented in for statement or inside the for
So the if condition will keep on running for the first character of the string ,if it is not a vowel which will be false for the string 'this', so it will never get inside the if statement
//for (int i = 0; i < ss.length();) {//no i++ implemented
for (int i = 0; i < ss.length();i++) {
if (ss.charAt(i) == 'a' || ss.charAt(i) == 'e'
|| ss.charAt(i) == 'i' || ss.charAt(i) == 'o'
|| ss.charAt(i) == 'u') {
ss = ss.substring(i, ss.length());
String sss = ss.substring(0, i + 1);
String ss44 = ss.substring(i + 1);
String ss33 = ss44 + sss;
ss33 = ss33 + "ay";
translatedWords.add(ss33);
System.out.println(ss33);
System.out.println("Why won't this print");
break;
}
}
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?