I'm getting String out of range
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
5 at java.lang.String.charAt(String.java:658) at
Lab6.DataSentinelWhile3.main(DataSentinelWhile3.java:24)
public static void main(String[] args) {
String sentence;
char ch = 'a';
int ind = 0, upperLetter=0, lowerLetter=0, digits=0, punctuation=0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a sentence (full-stop to terminate):");
sentence = input.nextLine();
while(ch != '.') {
if(ch >= 'a' && ch <= 'z')
lowerLetter++;
else if(ch >= 'A' && ch <= 'Z')
upperLetter++;
else if(ch >= '0' && ch <= '9')
digits++;
else
punctuation++;
ind++; //increase the index of the sentence by 1
ch = sentence.charAt(ind); //extract every character from sentence
}
System.out.print("\n\n*****Lexical Analysis of your Sentence*****" +
"\nLowercase letters: " + lowerLetter +
"\nUppercase letters: " + upperLetter +
"\nDigits: " + digits +
"\nPunctuation symbols: " + (punctuation+1));
input.close();
}
Use forloop when possible, possibility of error reduces by 10 folds:, for while loop:
ind i = 0;
while(ind < sentence.length){
ch = sentence.charAt(ind);
if(ch == '.') break;
if(ch >= 'a' && ch <= 'z')
lowerLetter++;
else if(ch >= 'A' && ch <= 'Z')
upperLetter++;
else if(ch >= '0' && ch <= '9')
digits++;
else
punctuation++;
ind++;
}
try this loop
while(ind < sentence.length)
{
}
change this
ch = sentence.charAt(ind);
ind++;
while(ch != '.')
You should set your loop on the string length, if sentence doesn't end with a final dot "." it doesn't stop.
Related
The question that my teacher gave me is : Create a Group Assignment that prompts the user for his or her name and then displays a group assignment. The group assignment depends on the FIRST LETTER OF THE STUDENT'S LAST NAME. Last names beginning with A through I are assigned to group 1, J through S are assigned to group 2 and T through Z are assigned to group 3.
example output:
Enter you first and last name: Janus Smith
You are assigned to group 2.
I don't know the code to get the first letter of the second word and if they are still code error please do fix it. Tnx.
Scanner scan = new Scanner(System.in);
String name;
System.out.println("Enter your first and last name: ");
name = scan.nextLine();
for (int i = 0; i < name.length; i++){
char ch = name.charAt(0);
if(ch >= 'A' || ch >= 'a' || ch <= 'I' || ch <= 'i'){
System.out.println("You are assigned to group 1.");
}
else if (ch >= 'J' || ch >= 'j' || ch <= 'S' || ch <= 's'){
System.out.println("You are assigned to group 2.");
}
else if (ch >= 'T' || ch >= 't' || ch <= 'Z' || ch <= 'z'){
System.out.println("You are assigned to group 3.");
}
}
You can split the whitespace-separated strings and extract the parts like this:
String name = "First Second";
String[] parts = name.split(" ");
// extract the second string from the 0-indexed array
String second = parts[1];
// extract the first character from the second string
char ch = second.charAt(0);
// no need to loop for a single name check
if(ch >= 'A' && ch <= 'I' || ch >= 'a' && ch <= 'i'){
System.out.println("You are assigned to group 1.");
}
else if (ch >= 'J' && ch <= 'S' || ch >= 'j' && ch <= 's'){
System.out.println("You are assigned to group 2.");
}
else if (ch >= 'T' && ch <= 'Z' || ch >= 't' && ch <= 'z'){
System.out.println("You are assigned to group 3.");
}
else {
System.out.println("Invalid input.");
}
Use String#split to split the name by space to get two parts.
String[] parts = name.split(" ");
parts[0] has the first name and parts[1] has the last name.
Get the first char of the last name as
char ch = parts[1].charAt(0);
Also your conditions are wrong. You must use && to check if the char is between a range.
if(ch >= 'A' && ch <= 'I' || ch >= 'a' && ch <= 'i')
To simplify the conditions, you can convert the character to either lower or upper case and check for one set of range.
char ch = Character.toUpperCase(parts[1].charAt(0));
if (ch >= 'A' && ch <= 'I') {...}
else if (ch >= 'J' && ch <= 'S') {...}
else {...}
Currently I have a simple problem to solve:
Given a String str, what is the best way of counting the amount of alphabetic literals in the string?
Right now I am thinking something like this:
int letterCount = 0;
for(int i = 0 : str){
String check = "" + str.charAt(i);
if(check.isLetter())
letterCount++
}
Are there any more efficient or elegant ways?
I’m pretty fond of streams (since Java 8):
String str = "A string";
long letterCount = str.chars().filter(Character::isLetter).count();
System.out.println(letterCount);
7
Your for loop is another nice solution. Here’s a version that works:
for (int index = 0; index < str.length(); index++) {
if (Character.isLetter(str.charAt(index))) {
letterCount++;
}
}
String str = "#CodeWines65";
int upper = 0, lower = 0, number = 0, special = 0;
for(int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z')
upper++;
else if (ch >= 'a' && ch <= 'z')
lower++;
else if (ch >= '0' && ch <= '9')
number++;
else
special++;
}
System.out.println("Lower case letters : " + lower);
System.out.println("Upper case letters : " + upper);
System.out.println("Number : " + number);
System.out.println("Special characters : " + special);
// If you are not concerned about uppercase or lowercase you can add them both & get the total count
I have wrote a below code to find a keyword co_e in the below string, where _ represents any other character.
It works good if I change the String to "aaacodebbb" or "codexxcode"
but if I change it to "xxcozeyycop" it throws StringIndexOutOfBoundsException
public int countCode(String str) {
int count = 0;
String result = "";
boolean yes = true;
for (int i = 0; i < str.length(); i++) {
// yes = str.charAt(i+3);
if (str.length() >= 3) {
if (str.charAt(i) == 'c' && str.charAt(i + 1) == 'o' && str.charAt(i + 3) == 'e')
count++;
}
}
return (count);
}
Your out-of-bounds error occured in this line:
if (str.charAt(i) == 'c' && str.charAt(i + 1) == 'o' && str.charAt(i + 3) == 'e')
The error happened at str.charAt(8) for str = "xxcozeyycop", because str.length() is 11, and str.charAt(11) is clearly out of bounds (and so are all str.charAt(str.length()))
Here is one possible solution. Note that if str.length() < 4, the for loop cannot run, as i + 3 will always go out of bounds. Also, when i == str.length() - 4 for all strings longer than four chars, i+3 would equal the last index of the string, str.length() - 1.
for (int i = 0; i < str.length() - 3; i++) {
char c1 = str.charAt(i);
char c2 = str.charAt(i + 1);
char c4 = str.charAt(i + 3);
if (c1 == 'c' && c2 == 'o' && c4 == 'e')
count++;
}
In the loop, you are checking accessing i+3. So, you have to stop when i is at 4th last position.
Replace if(str.length()>= 3) with if(str.length()>= 3 && str.length() - i >3)
OR
You can put the following as the first condition in your for loop:
if(str.length() - i <=3){
break;
}
How can I add 0 in front of every single digit number? I mean 1 to 01 etc.
I have tried to add ifs like
if(c >='A' && c<= 'I')
str = "0"+str;
but it just adds 0 in front of everything like abcd converts to 00001234 not 01020304.
This is my code.
String A[] = new String[size];
for (int i = 0; i < size; i++) {
A[i] = jList1.getModel().getElementAt(i);
String[] Text = A[i].split("");
String s = jList1.getModel().getElementAt(i);
String str = ("");
for (int z = 0; z < Text.length; z++) {
for (int y = 0; y < Text[z].length(); y = y + 1) {
char c = s.charAt(z);
if (c >= 'A' && c <= 'Z') {
str += c - 'A' + 1;
} else if (c >= 'a' && c <= 'z') {
str += c - 'a' + 1;
} else {
str += c;
}
}
str = str + "";
}
}
This Worked for me
public String addZero(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}``
One way to do this would be to use a StringJoiner with Java 8:
String s = "abcdABCD";
s = s.chars()
.mapToObj(i -> Integer.toString((i >= 'a' && i <= 'z' ? i - 'a' : i - 'A') + 1))
.collect(Collectors.joining("0", "0", "")));
System.out.println(s);
>> 0102030401020304
String str = "abcd-zzz-AAA";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.toLowerCase().charAt(i);
if (ch >= 'a' && ch <= 'z') {
sb.append('0');
sb.append(ch - 'a' + 1);
} else {
sb.append(ch);
}
}
Result: abcd-zzz-AAA -> 01020304-026026026-010101
Final fix :-)
use String#chars to get a stream of its characters, then for each one do the manipulation you want.
public class Example {
public static void main(String[] args) {
String s = "aBcd1xYz";
s.chars().forEach(c -> {
if (c >= 'a' && c <= 'z')
System.out.print("0" + (c - 'a' + 1));
else if (c >= 'A' && c <= 'Z')
System.out.print("0" + (c - 'A' + 1));
else
System.out.print(c);
});
}
}
Ouput:
0102030449024025026
You can add zero in front of single digit number using String.format.
System.out.println(String.format("%02d",1));
System.out.println(String.format("%02d",999));
The first line will print 01, second line prints 999 no zero padding on the left.
Padding zero with length of 2 and d represents integer.
I hope this helps.
I want to add the letters "ç," "ğ," "ı," "ö" and "ü" into this encrypter's alphabet, and maybe special chars, too. How can I do that?
for (int i = 0; i < metin.length(); i++) {
char harf = metin.charAt(i);
if (harf >= 'a' && harf <= 'm') harf += i;
else if (harf >= 'A' && harf <= 'M') harf += i;
else if (harf >= 'n' && harf <= 'z') harf -= i;
else if (harf >= 'N' && harf <= 'Z') harf -= i;
System.out.print(harf);
}
You are using the Java intern Char's as ints to implement the cipher.
A better way would be to use a String charSet = "abcdefgh.... %&/(öäüô"; with the chars you want in you charSet.
String charset = "abcdefghijklmnopqrstuvwxyzäöü";
for (int i = 0; i < metin.length(); i++) {
int j = charset.indexOf(metin.charAt(i));
if(j < -1)
{
//deal with unknown char
}
if(j == charset.length)
{
j=0;
}
System.out.print(charset.charAt(j+1);
}
I hope you get the idea.
You can make the strategy more general like this.
String text = "abcdefghijklmnopqrstuvwxyz0123456789!$%^&*()äöü";
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
ch--;
if (ch % 32 < 13)
ch += 13;
else if (ch % 32 < 26)
ch -= 13;
else if (ch % 32 < 29)
ch += 3;
else
ch -= 3;
ch++;
System.out.print(ch);
}
prints
nopqrstuvwxyzabcdefghijklm#$%&'()*+,.12[3756ñéÿ