java.lang.StringIndexOutOfBoundsException: String index out of range: 7 - java

I don't really know how to program... I was working on this for a Computer Science Class
Instruction: Use nested loops to print out the square word pattern show below.
I'm guessing the error is in the toString method, but I can't spot where.
the desired output is: (when input is SQUARE)
SQUARE
Q R
U A
A U
R Q
ERAUQS
The code:
import static java.lang.System.*;
class BoxWord
{
private String word;
public BoxWord()
{
word="";
}
public BoxWord(String s)
{
setWord(s);
}
public void setWord(String w)
{
word=w;
}
public String toString()
{
String output=word +"\n";
for(int i =0;i<word.length(); i++){
output += word.charAt(i);
for(int j = 2; j<word.length();j++)
output += " ";
output+= word.charAt(word.length()-(i-1))+ "\n";
}
for(int k=0; k<word.length(); k++)
output+= word.charAt(k);
return output+"\n";
}
}
main:
import static java.lang.System.*;
public class Lab11f
{
public static void main( String args[] )
{
BoxWord test = new BoxWord("square");
out.println(test);
}
}

Try the following, I will explain the modifications in comments:
public static void main(String[] args)
{
String word = "square";
String output = word + "\n"; // Initialize with the word
for (int i = 1; i < word.length() - 1; i++) { // From '1' to 'length - 1' because we don't want to iterate over the first and last characters
output += word.charAt(i);
for (int j = 0; j < word.length() - 2; j++) // To add spaces
output += " ";
output += word.charAt(word.length() - (i + 1)) + "\n";
}
for (int k = word.length() - 1; k >= 0; k--) // Add word in reverse
output += word.charAt(k);
System.out.println(output);
}
Output:
square
q r
u a
a u
r q
erauqs

On the first two iterations of this loop you are going to have an error:
for(int i =0;i<word.length(); i++){
output += word.charAt(i);
for(int j = 2; j<word.length();j++)
output += " ";
output+= word.charAt(word.length()-(i-1))+ "\n";
^^^^^^^^^^^^^^^^^^^
}
This is equivalent to word.length() - i + 1 which is going to be an error when i is 0 or 1.

public String toString()
{
String output=word +"\n";
for(int i =0;i<word.length(); i++){
output += word.charAt(i);
for(int j = 2; j<word.length();j++)
output += " ";
output+= word.charAt(word.length()-(i-1))+ "\n";
}
output+= word.charAt(word.length()-(i-1))+ "\n"; this line is making string index out of bound exception

Related

program that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots

Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots.
Note: Avoid using inbuilt functions
Input: "i.like.this.program.very.much"
Output: "i.abc.this.abc.very.abc"
Would something like this work?
public String func(String s) {
String[] arr = s.split("\\.");
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 1)
arr[i]= "abc";
}
String rString = "";
for (int i = 0; i < arr.length - 1; i++) {
rString += arr[i];
rString += ".";
}
rString += arr[arr.length - 1];
return rString;
}
Not my most efficient work, but it was what I came up with on the spur of the moment.
Not sure what you exactly mean by avoiding built in methods, but this should work:
public String whyNot(String s) {
String[] sA = s.split("\\.");
String newS = sA[0];
for (int i = 1; i < sA.length; i=i+2) {
newS += ".abc." + sA[i];
}
return newS;
}
**
public class Main
{
public static void main(String[] args) {
String a="i.like.this.program.very.much.";
String[]arr=a.split("\\.");
for(int i=0;i<=arr.length-1;i++){
if(i%2==1)
arr[i]="abc";
}
String rs="";
for(int i=0;i<arr.length-1;i++){
rs+=arr[i];
rs+=".";
}
rs+=arr[arr.length-1];
System.out.println(rs);
}
}
**

[Java]Find duplicate characters in a string without hashmap and set

I have written a Java program to find duplicate characters in a string without Hashmap and set.
Below is the program,
package practice;
public class Duplicate {
public static void main(String[] args) {
String src= "abcad";
char[] srcChar= src.toLowerCase().toCharArray();
int len=srcChar.length;
int j=0;
boolean flag=false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k=0;
for(int i=0;i<len;i++)
{
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for(j=0;j<len;j++)
{
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if(srcChar[i]==srcChar[j])
{
k++;
}
}
if(k>1)
{
if(srcChar[i]>1)
{
System.out.println("This character "+srcChar[i]+" has repeated "+k+ " time");
}
else
{
System.out.println("There are no characters repeated in the given string");
}
}
k=0;
}
}
}
Output here is:
This character a has repeated 2 time
This character a has repeated 2 time
Here, I want the output like
This character a has repeated 2 time
i.e. not repeating the output twice. Since the character "a" is repeated twice, the output is also repeated twice.
kindly help me to get the output once instead of twice.
Thank you,
class PrintDuplicateCharacter
{
public static void main(String[] args)
{
String str = "HelloJava";
char[] ch = str.toCharArray();
int i=0,j=0;
for(i=0;i<ch.length;i++)
{
int count = 0 ;
for( j = i+1;j<ch.length;j++)
{// 4 6 , 8 , 10
if(ch[i] == ch[j] )
{
count++;
}
}
if(count != 0)
{
System.out.print(str.charAt(i) + " Occured " + count + " time");
}
}
}
}
private static void duplicateChar(String str){
char[] arr1 = str.toUpperCase().toCharArray();
int length = str.length();
int count = 1;
String s = "";
char c1 = '\u0000';
for(int i=0;i<length;i++){
count = 1;
for(int j=i+1;j<length;j++){
if(arr1[i] == arr1[j]){
count++;
c1 = arr1[i];
}
if(j == (length-1) && c1 != '\u0000' && !s.contains(String.valueOf(c1))){
s = s+" "+String.valueOf(c1)+" No of times: "+count+"\n";
}
}
}
System.out.println("\nDuplicate char are:\n"+s);
}
You can make a 2 dimensional array, 2 wide, the source strings height. In this array you store a character when it gets replaced and add one to the amount of times it has been replaced.
Something like(I don't know if these counters are correct):
replacements[j][0] = charAt(j);
replacements[j][1] += 1;
You would have to check if the character you are replacing already exists in this array and you can only print elements of the array if they aren't null.
You print this after the original loop.
All you need to fix is to start the second loop from i instead of 0.
for (int i = 0; i < len; i++) {
for (j = i; j < len; j++) {
...
}
...
}
Imports:
import java.util.ArrayList;
import java.util.List;
Code:
public static void main(String args[]) {
String input = "abcad"; // Input value
char[] chars = input.toLowerCase().toCharArray(); // Creates ArrayList
// of all characters
// in the String
List<Character> charR = new ArrayList<>(); // Creates a List used to
// saving the Characters it
// has saved
List<Integer> valR = new ArrayList<>(); // Creates a List that will
// store how many times a
// character is repeated
for (int i = 0; i < chars.length; i++) { // Loop through items in the
// ArrayList
char c = chars[i]; // Create Character value containing the value of
// the item at the "i" index of the ArrayList
if (charR.contains(c)) { // If the List contains item...
for (int i2 = 0; i2 < charR.size(); i2++) { // Loop through its
// items
if (charR.get(i2).equals(c)) { // If you find a match...
valR.set(i2, valR.get(i2) + 1); // Increase repeated
// value by 1
i2 = charR.size(); // Stop loop
} else { // Else...
i2++; // Increase index by 1
}
}
} else { // Else...
charR.add(c); // Add the Character to the List
valR.add(1); // Add the value 1 to the List (Meaning that the
// Character repeated once)
}
}
for (int i = 0; i < charR.size(); i++) { // Loop through all the items
// in the List
System.out.println("'" + charR.get(i) + "' : " + valR.get(i)); // Display
// what
// the
// character
// is
// and
// how
// many
// times
// it
// was
// repeated
}
}
Output:
'a' : 2
'b' : 1
'c' : 1
'd' : 1
char[] array=value.toCharArray();
int count=0;
char ch;
for(int i=0;i<array.length-1;i++)
{
ch=array[i];
count=1;
if(ch!='#'){
for(int j=i+1;j<array.length;j++)
{
if(ch==array[j]){
count++;
array[j]='#';
}
}
if(count>1)
{
System.out.println("char is " + ch + "count" + count);
}
}
}
You can also solve this problem with this code like :
public static void main(String[] args) {
String src = "abcad";
char[] srcChar = src.toLowerCase().toCharArray();
int len = srcChar.length;
int j = 0;
boolean flag = false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k = 0;
for (int i = 0; i < len; i++) {
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for (j = 0 + i; j < len; j++) {
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if (srcChar[i] == srcChar[j]) {
k++;
}
}
if (k > 1) {
if (srcChar[i] > 1) {
System.out.println("This character " + srcChar[i] + " has repeated " + k + " time");
} else {
System.out.println("There are no characters repeated in the given string");
}
}
k = 0;
}
}
just we need to start the inner loop with j=0+i ;
for (j = 0 + i; j < len; j++)
This will you can observe above code;

How do I print the characters of a String variable in a diagonal line?

How can I take a String variable and print it's contents in a diagonal line downward? Preferably using a for or while loop.
This is the code I have now, which doesn't work as intended:
String str = JOptionPane.showInputDialog("enter a string");
for(int i = 0; i <= str.length(); i++)
{
System.out.println(str.charAt(i));
}
This outputs str in a line downwards, but not diagonal. How can I make it look like this:
E
X
A
M
P
L
E
Just add one more loop to add proper amount of spaces equal to i before your character.
for(int i = 0; i < str.length(); i++) {
for (int spacesCount = 0; spacesCount<i; spacesCount++){
System.out.print(" ");
}
System.out.println(str.charAt(i));
}
public class HelloWorld {
public static void main(String[]args) {
printDiagonal("hello");
}
public static void printDiagonal(String s)
{
String holdSpace = "";
while (s.length() > 0)
{
String c = s.substring(0,1);
if(s.length() > 0)
{
s = s.substring(1);
}
holdSpace += " ";
System.out.println(holdSpace + c);
}
}
}

How to rearrange the columns in a 2d array matrix alphabetically

I want to take the following matrix below and rearrange the chars TOAD to ADOT and the rearrange the corresponding columns below to where the char above moved, so for example A moved to col 0 so now VGD should all be in col 0 etc.
TOAD is a separate array by the way! im using that keyword to sort the martrix alphabetically.
//Matrix output and then the code.
T O A D
V V V X
D V G G
D F D V
public String printMatrix(String s [][]){
char key[] = polyCipher.getKeyword().toCharArray();
String keyOut = "";
for(int i=0;i<key.length;i++){
keyOut += key[i] + " ";
}
keyOut += "\n";
for (int i = 0; i < s.length; i++) {
// keyOut += PHRASE_KEY[i] + " ";
for (int j = 0; j < s[i].length; j++) {
keyOut += s[i][j] + " ";
}
keyOut += "\n";
}
return keyOut.toUpperCase();
}
public static String [][] buildMatrix (String translation, String outermarker, String innermarker) {
// outerdelim may be a group of characters
String [] sOuter = translation.split("[" + outermarker + "]");
int size = sOuter.length;
// one dimension of the array has to be known on declaration:
String [][] result = new String [size][size];
int count = 0;
for (String line : sOuter)
{
result [count] = line.split (innermarker);
++count;
}
return result;
}
public void sortArray(){
// do tomorrow
}
public String matrixFormatter(String x){
String resultstr = "";
int i = 0;
while(i < x.length()) {
// If end of string: only add character.
if (i == x.length() - 1) {
resultstr += x.substring(i, i + 1);
} else {
if ( ((i + 1) % 4) == 0) {
resultstr += x.substring(i, i + 1) + "|";
} else {
resultstr += x.substring(i, i + 1) + ",";
}
}
i++;
}
return resultstr;
}
}

Add x number of spaces between the letters of a string in Java?

I need to recieve a integer and have it print out that number of spaces in between the letters of a name. Right now I have it printing out one space.
public static void printLongName(int spaces){
String name
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++)
System.out.print(" " + letter[i]);
System.out.println();
}
public static void printLongName(String name, int numOfSpacesBetweenLetters) {
StringBuffer sbSpace = new StringBuffer();
for (int i = 0; i <= numOfSpacesBetweenLetters; i++) {
sbSpace.append(" ");
}
char[] letter = name.toCharArray();
for (int i = 0; i < letter.length; i++) {
System.out.println(sbSpace + letter[i]);
}
}
use System.out.format()
System.out.format("%10c", letter[i]);
update
int spaces=10;
String name ="aaaaaaaa";
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++)
System.out.format("%10c", letter[i]);
//System.out.print(" " + letter[i]);
//System.out.print(getSpace(10) + letter[i]);like this you can
public String getSpace(int count)
{
String space="";
for(int i=0;i<count;i++)
space+=" ";
return space;
}
I believe your looking for something like this:
System.out.format("[%13s]%n", ""); // prints "[ ]" (13 spaces)
System.out.format("[%1$3s]%n", ""); // prints "[ ]" (3 spaces)
This regular expression will allow you to add your spaces appropriately.
You need build the space string first with parameter input. Please look at below code:
public static void printLongName(int spaces){
String name = "hello";
StringBuilder sb = new StringBuilder();
String spaceStr = "%"+spaces+"c";
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++) {
if (i == 0) {
sb.append(letter[i]);
} else {
sb.append(String.format(spaceStr, letter[i]));
}
}
System.out.println(sb);
}
public static void main(String[] args) {
printLongName(4);
}
Update some code.
This function will return a string with spaces:
String nameWithSpaces(String name, int spaces) {
StringBuilder sbname = new StringBuilder(name);
String spaces = String.valueOf(new char[spaces]).replace("\0", " ");
for (int i=1; i < sbname.length(); i += spaces.length()+1)
sbname.insert(i, spaces);
return sbname.toString();
}

Categories

Resources