I want get a String like this "SsjAasdLlswAasdMm"
and print a String like this "salam"
(print characters as String that are next to a Capital)
I wrote this :
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
char[] capitalalphabet = new char[]{'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'};
Scanner input = new Scanner(System.in);
String s1 = input.next();
StringBuffer s2 = new StringBuffer();
for (int i=0 ; i < s1.length() ; i++) {
for (int j = 0; j < capitalalphabet.length; j++) {
if (s1.charAt(i) == capitalalphabet[j]){
int k = 0 ;
s2.setCharAt(k , s1.charAt(i+1));
k++;
}
}
}
System.out.println(s2);
}
}
and i got this error :
SAhfdsdEDsa
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.StringBuffer.setCharAt(StringBuffer.java:257)
at Temp.main(Temp.java:14)
It happens at this line:
s2.setCharAt(k, s1.charAt(i+1));
According to the documentation:
Throws:
StringIndexOutOfBoundsException - if start is less than zero, or greater than the length of this object.
Since your s2 string is empty (its length is 0), you're exceeding the bounds when you try to add to it.
Also, since your k variable is always initialized to zero right before the setChatAt method, and it's only defined inside the if-statement block, you'll always be setting at index 0, even if you could.
I'd suggest you just simply try to use StringBuilder instead, as well as discard the messy loop of captial letters - their ASCII code is sequential, you could simply ask if character is in range:
for (int i=0 ; i < s1.length()-1; i++) {
char c = s1.charAt(i);
if (c >= 'A' && c <= 'Z') {
s2.append(s1.charAt(i+1));
}
}
System.out.println(s2);
Note that the loop scans until the index before last, since it might access the next index (and since there's no need to check the last character - it cannot be followed by anything, capital or otherwise).
Note you could also replace the if condition with Character.isUpperCase(c) which is more readable and elegant.
Related
I'm trying to make a code that deletes the repeated characters. For example - if we have a string "aabacdc", we want to make it as "abd". If the character exists twice in the string, then we delete both characters as we did in the above example. The 'a' occurs 3 times in our string, so we just deleted the 2 a and left 1 remaining.
What I'm trying to do in this code is use two nested for loops - first for loop to compare the first character with the other characters. If the character has a duplicate in the string, then just delete both the characters. How can I fix this code?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str2 = input.nextLine();
StringBuilder str = new StringBuilder(str2);
for (int k = 0; k < str.length() - 1; k++) {
for (int i = 1; i < str.length() - 1; i++) {
if (str.charAt(k) == str.charAt(i)) {
str.deleteCharAt(k);
str.deleteCharAt(i);
}
}
}
System.out.println(str);
}
My interpretation of what you're trying to do based on your expected output is that you want to remove characters from the string 1 pair at a time. So if there is an odd number of a character in the string, 1 should remain, and if there's an even number 0 should remain.
Any time you're removing elements from a structure while you're iterating by index, you need to loop over the structure backwards, so that the index values don't shift as you delete elements. This means you should only delete elements which the outer loop is currently at, or has already seen (i.e. only delete elements at indexes >= i).
Scanner input = new Scanner(System.in);
String str = input.nextLine();
StringBuilder sb = new StringBuilder(str);
for (int i = sb.length() - 2; i >= 0; i--) {
for (int j = i + 1; j < sb.length(); j++) {
if (sb.charAt(i) == sb.charAt(j)) {
sb.deleteCharAt(j);
sb.deleteCharAt(i);
break;
}
}
}
System.out.println(sb);
Ideone Demo
I have two exact copies of code here, except one has '<' in the for loops while the other has '<='. Could someone please explain why I get the index out of bounds exception when I use '<=', but then it works fine with '<'
Error code:
for(int i = 0; i <= str.length(); i++) {
int count = 0;
char currentChar = str.charAt(i);
for(int j = 0; j <= str.length(); j++) {
if (currentChar == str.charAt(j) ) {
count++;
Working code:
for(int i = 0; i < str.length(); i++) {
int count = 0;
char currentChar = str.charAt(i);
for(int j = 0; j < str.length(); j++) {
if (currentChar == str.charAt(j) ) {
count++;
If I don't use <= how will it compare the last character in the string?
Valid String indexes in Java, just like the indexes in any array, go from zero to length minus one. So clearly if you set up your condition to go up to i <= str.length(), you'll get outside the string.
Remember that a String on the inside is nothing more than a char[], and again: the valid indexes go from 0 to length-1. This is a convention, followed by many other programming languages that decided to start counting from zero instead of one.
Because you cannot access str.chatAt(str.length()) without throwing a exception.
a < b means "a is less than b" and it will be false when a equals to b.
a <= b means "a is less than or equals to b" and it will be true when a equals to b.
To compare the last character in the string, write some code to do so, compile and run.
bool res = currentChar == str.charAt(str.length() - 1); // assuming str has string with one character or more
str.length() returns the number of characters in the String. So "String".length() returns 6.
Now, when using indices, you start with zero. so "String".charAt(0) returns 'S'. "String".charAt(6) gives you a StringIndexOutOfBoundsException because the last character in "String" is at index 5.
String indexes begin at 0. str.length() returns how many elements are in your array. if you have a string
"dog"
"dog".length() = 3,
'd':0, 'o':1, 'g':2.
Since your for loop initializes i to 0, the working loop goes through indexes 0-2, which is 3 values, while the non-working one goes 0-3, and references a null, and str.charAt(3) does not exist.
Given a non-empty string str like "Code" print a string like "CCoCodCode". Where at each index in the string you have to reprint the string up to that index.
I know there is DEFINITELY something wrong with this code that I wrote because the answer should be CCoCodCode, but instead it's giving me the alphabet! I don't know how I should change it.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String str = scan.next();
int x = str.length();
for(char i = str.charAt(0); i <= str.charAt(x-1); i++)
{
System.out.print(i);
}
}
The char datatype can be treated as a number; you can increment it and manipulate it as a number.
What you really want is successive substrings of str to be printed. Loop over an int that will represent the ending position of the substring to be printed.
for (int i = 0; i < str.length(); i++)
{
System.out.print(str.substring(0, i + 1));
}
The end index argument to substring is exclusive, which is why I added 1.
Let's say that str is "Code". We can perform some mental substitutions to see what happens to your loop.
str is "Code"
x is 4
str.charAt(0) is 'C'
str.charAt(x-1) is 'e'
Making these substitutions, your loop is:
for(char i = 'C'; i <= 'e'; i++)
{
System.out.print(i);
}
Does this help you see the problem? I would think you'd have a loop from 0 to 3, not from 'C' to 'e'...
Many ways to get it done, suppose we have the input from user stored in a string named "c"... then...
String c = "Code";
for (int i = 0; i < c.length(); i++) {
System.out.print(c.substring(0, i));
}
System.out.print(c);
And this will print the sequence you are looking for.
It is outputting the alphabet because you are printing the counter instead of the characters in the string!
As it is, the first iteration of the for loop will set i to the first character, print that, then the operation i++ will increment i by one. Wait, so if the first character is "C", so i = 'C', what is i++?
Well it turns out characters can be represented by numbers. For example, 'C' has a value of 67. So incrementing it makes it 68, which represents 'D'. So if you run the loop on "Code", it will increment your counter 4 times, giving "CDEF". If you run on "Codecodecode", that will make the loop run 12 times, giving "CDEFGHIJKLMN".
What you really want is to loop through the string by its index instead:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.next();
int length = str.length();
for (int i = 0; i < length; i++) {
System.out.print(str.substring(0, i + 1));
}
}
I'm trying to write a program which accepts a word in lowercase, converts it into uppercase and changes the vowels in the word to the next alphabet. So far, I've done this:
import java.util.*;
class prg11
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word in lowercase.");
String word = sc.next();
word = word.toUpperCase();
int length = word.length();
char ch[] = new char[length+1];
for (int i = 0; i<=length; i++)
{
ch[i] = word.charAt(i);
if("aeiou".indexOf(ch[i]) == 0)
{
ch[i]+=1;
}
}
String str = new String(ch);
System.out.println(str);
}
}
The code compiles fine. But, when I run the program and enter a word, say 'hey', the word is printed in uppercase only. The vowels in it (in this case, 'e'), do not get changed to the next alphabet.
How do I resolve this? TIA.
Need to change three places, according to the code in the question.
word = word.toUpperCase();
int length = word.length();
// yours: char ch[] = new char[length + 1];
// resulting array needs to be as same length as the original word
// if not, there will be array index out of bound issues
char ch[] = new char[length];
// yours: for (int i = 0; i<=length; i++)
// need to go through valid indexes of the array - 0 to length-1
for (int i = 0; i < length; i++) {
ch[i] = word.charAt(i);
// yours: if ("aeiou".indexOf(ch[i]) == 0) {
// two problems when used like that
// 1. indexOf() methods are all case-sensitive
// since you've uppercased your word, need to use AEIOU
// 2. indexOf() returns the index of the given character
// which would be >= 0 when that character exist inside the string
// or -1 if it does not exist
// so need to see if the returned value represents any valid index, not just 0
if ("AEIOU".indexOf(ch[i]) >= 0) {
ch[i] += 1;
}
}
Here's a little concise version. Note the changes I've done.
String word = sc.next().toUpperCase();
char ch[] = word.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ("AEIOU".indexOf(ch[i]) >= 0) {
ch[i] += 1;
}
}
Java doc of indexOf().
public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
If a character with value ch occurs in the character sequence represented by this String object,
then the index (in Unicode code units) of the first such occurrence is returned.
For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:
this.charAt(k) == ch
is true. For other values of ch, it is the smallest value k such that:
this.codePointAt(k) == ch
is true. In either case, if no such character occurs in this string, then -1 is returned.
Parameters:
ch - a character (Unicode code point).
Returns:
the index of the first occurrence of the character in the character sequence represented by this object,
or -1 if the character does not occur.
I think this should do it, let me know if it doesn't
public class prg11 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word.");
String word = sc.next();
sc.close();
word = word.toUpperCase();
int length = word.length();
char ch[] = new char[length+1];
for (int i = 0; i<length; i++) {
ch[i] = word.charAt(i);
if("AEIOU".indexOf(ch[i]) > -1) {
ch[i]+=1;
}
}
String str = new String(ch);
System.out.println(str);
}
}
Let me know if it works.
Happy coding ;) -Charlie
Use:
for (int i = 0; i<length; i++)
instead as the last index is length-1.
use for (int i = 0; i<=length-1; i++) instead of for (int i = 0; i<=length; i++) and if("AEIOU".indexOf(ch[i]) != -1) instead of if("aeiou".indexOf(ch[i]) == 0)
reason
1.array index starts from 0 that's why length-1
2. As you already made your string in upper case so check condition on "AEIOU"
3. every non-vowel character will return -1 so use if("AEIOU".indexOf(ch[i]) != -1)
"aeiou".indexOf(ch[i]) == 0 will only match 'a' characters (since that is the character at index 0). You should be looking for any index that is greater than -1. Additionally, since you've already converted the string to uppercase, you should be checking against "AEIOU" instead of "aeiou".
I'm trying to create a code that writes an array backwards and can only use an array, character, and an integer. So far I have this, but it isn't doing anything. I'm a beginner at java.
import javax.swing.JOptionPane;
public class TestingArraysUsingOneArray
{
public static void main(String args[])
{
{
String str = JOptionPane.showInputDialog("Enter any text that you want to reverse.");
char[] charArray = str.toCharArray();
char current;
int a = 0;
for (int i = 0; i>=str.length()%2; i++) {
current = str.charAt(a);
charArray[a] = str.charAt(str.length()-a);
charArray[str.length()-a] = current;
a++;
}
System.out.println(charArray);
}
}
}
The output I'm getting is hello when I enter in hello. What do I need to change to get this program to work?
Your don't need half the code. I would try to make it as simple as possible. Try this
String str = ...
for(int i = str.length() - 1; i >= 0; i--)
System.out.print(str.chatAt(i));
System.out.println();
If the assignment says you have to reverse an array of chars you can do this.
String str = ...
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length/2; i++) {
char ch = chars[i];
chars[i] = chars[chars.length - i - 1];
chars[chars.length - i - 1] = ch;
}
System.out.println(new String(chars));
As you can see this is needlessly complicated, so you would not do this. Another way you can do this if you don't want to use a loop is
String str = ...
System.out.println(new StringBuilder(str).reverse());
Well, for one thing, I think you want i<str.length()/2 - this will give you half the length. If you say i>=str.length()%2, you're getting the remainder when its length is divided by 2 - which is always either 1 or 0, and the loop continues as long as i is more than either 1 or 0. This should result in an infinite loop. Also, you don't need the variable a, as it is always equivalent to i. This, however, results in the string index being out of bounds sometimes, but I'll let you figure out how to solve that.
Your for loop is never entering because it should be i < str.length(), because at the moment when i is 0, the current check will immediately fail.
With that condition set, you need to change the two instances of str.length()-a to str.length()-a-1, because str.length-a when a is 0 will cause an StringIndexOutOfBoundException because the maximum index you can access is str.length-1.
Those are just corrections to the existing code. There's a better, more concise way of reversing the string suggested in another answer, which is the one you should accept.
What you want to do is replace the first character with the last and so on..
char[] charArray = str.toCharArray();
char current;
for (int i = 0; i < charArray.length / 2; i++) {
current = charArray[i];
charArray[i] = charArray[charArray.length - i - 1];
charArray[charArray.length - i - 1] = current;
}
The a int is completely redundant, and it would be a second int in your code - don't forget the variable in the for loop.