I'm looking for help correcting an exception error for 'string index out of range'. My code is supposed to take two strings as input from the user(string1 and string2) and create new strings that are parts of the originals.
So far I have the following:
modString1 = string1.substring(string1.length() -3, string1.length());
modString2 = string2.substring(0,3);
The above code is supposed to take the last 3 characters of string1 and the first 3 characters of string2. The problem I am having comes when the user inputs a string that is shorter than 3 characters.
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
For example, if the user enters 'A' for the first string it will change the string to 'xxA' and if 'A' is entered for the second string it will change that to 'Axx'?
Put an if statement before your code, checking the length of the string before you process it.
For example:
if(string1.length() < 3) {
// Add characters to the string
}
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
What you are looking for is called padding.
It can be done in a number of ways. The simplest is probably to use an external library such as Apache's StringUtils. You could also write a padding method yourself using a StringBuilder.
Related:
How can I pad a String in Java?
put the validation like below and add the string.
For ex.
if(string1.length()<3){
String op = 'xx';
string1 += op;
}
Related
How to create a method that will take imput of a String and an integer n and output the String divided into parts consisting of n characters and separated by a blank space? For example, imput String: "THISISFUN", integer:3, result: "THI SIS FUN".
When you answer, can you please really try to explain what each part of the code does? I really want to understand it.
I tried using StringBuilder and the split() method but the problem is that I don't understand how all of that works. Therefore, I ended up kind of thoughtlessly pasting parts of codes from different online articles which doesn't work the best if you want to actually learn something, especially if you simply cannot find any posts about a specific issue. I could only find things like: "how to divide the String into n parts" and "how to ad a space after a specific char" which are sort of similar issues but not the same.
Here is one way to do it:
public static void splitString(String str, int groupSize){
char[] arr = str.toCharArray(); // Split the string into character array ①
// Iterate over array and print the characters
for(int i=0; i<arr.length; i++){
// If 'i' is a multiple of 'groupSize' ②
if(i > 0 && i % groupSize == 0){ ③
System.out.print(" ");
}
System.out.print(arr[i]);
}
}
① Split the string into a character array (so that you can access the characters individually). You can also do it using the charAt() method without splitting the string into an array. Read the Javadoc for more details.
② Check if the loop counter i is a multiple of groupSize
③ Note the use of System.out.print() as we do not want to print a newline. Here you can use a StringBuilder too and print the contents at the end instead of printing the characters inside the loop.
I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan
I've got some String, and I'd like to replace some chars in it. Everything was running fine until the String hasn't two or more same chars, the program just replacing the first one, and I'm not able to change the second one.
StringBuilder userTitleBuilder = new StringBuilder(conversedTitle);
while (score>1) {
userLetter = userInput.next().charAt(0);
if (movieTitle.contains(String.valueOf(userLetter))) {
charIndex = movieTitle.indexOf(userLetter);
userTitleBuilder.replace(charIndex,userTitleBuilder.length(), String.valueOf(userLetter));
System.out.println(userTitleBuilder);
} else {
--score;
System.out.println("Wrong\nTries left "+score);
}
}
Here's the explanation of this code:
User from the start the program has a score equals to 10. userLetter it's just a char that will get some letter from the user, then if statement checking if movieTitle variable has char equals to that user just entered, if yes, charIndex will have it position (but it contains only first index, what if in word are more same letters?) now userTitleBuilder replace the chars in string that has that many "_" that movieTitle lenght, it's just covering the title.
*movieTitle and userTitleBuilder has the same value = "CocaCola"
I'd like to not get ready solution. I'd like to have some kind of hint, how do I replace more than one same character in String
A method called String.replace("old","new") can be used.
Follow this doc.
Questions like this one have been answered but none helped me understand and decide the best suited way to do this in my case.
The idea:
Input: 15k+5b-1m
Ouput: 15000+5000000000-1000000
Basically replacing k by 1,000 - m by 1,000,000 and b by 1,000,000,000 and multiply it to the value it is attached to.
How I thought I'd do it:
Using 2 StringTokenizer, one to parse math signs +,-,*,/ and one to parse
letter k,m,b that I call on every element the first parser got.
So if we apply the algorithm we'd have for my example:
Str Input = 15k+5b-1m
StringTokenizer math_token= new StringTokenizer(source, Input);
while (math_token.hasMoreTokens())
{
while(math_token.hasMoreElements())
{
Str token_value = math_token.nextElement();
parse_letters(token_value) and change values...
}
math_token.nextToken();
format stuff for the final string
}
So it goes like:
15k -> 15 -> 15000
If I understand your question, then you could replace b with nine zeros m with six zeros and k with three zeros. Also, by convention, Java variable names start with a lower-case letter. Something like,
String input = "15k+5b-1m";
input = input.replace("b", "000000000").replace("m", "000000")
.replace("k", "000");
System.out.println(input);
which outputs (as requested)
15000+5000000000-1000000
I'm writing a program that generates star wars names. The user inputs their first, last, mother's maiden name, birth city, and first car and the program gives a star wars name. I need the last two characters* of the user inputted last name. I know I can use substring, but I cannot get anything to work. The best I have is:
lastname.substring(lastname.length() -2)
which gives the first two letters of the last name, and not the last. Also, I cannot use lastname.substr(-2) because substr for some reason won't work (not sure why, this would be much easier).
Thanks for any help.
*EDIT: I hope I didn't confuse anyone, I need the last two characters of the last name.
Actually I see my problem now: my original last name variable is
String lastname = console.nextLine().substring(0,2).trim().toUpperCase();
which keeps the first two letters, so the reason I was getting the first two letters was because of this. I understand now. Is there a way to get the last two letters from this same variable?
So if the name was Michael, you just want Micha?
Try:
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
For example:
String lastName = "Michael";
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
System.out.println(trimmedLastName); // prints Micha
The reason mine works and yours doesn't is because the first parameter of substring is where to start. So I start from the first letter, and end on the second last letter (not inclusive).
What yours does is start on the second last letter, and continue on until the end of the string.
However, if you wanted just el from Michael, you could do this:
String lastName = "Michael";
String trimmedLastName = lastName.substring(lastName.length() - 2);
System.out.println(trimmedLastName); // prints el
Try this out,
lastname.substring(lastname.length() -3,lastname.length() -1);
If you need the different ways, here:
StringBuffer myString = new StringBuffer(inputString);
myString.revert();
StringBuffer userInput = new StringBuffer(myString.subString(2));
String result = userInput.revert();
Have a nice day.
Because String is immutable so when you call subString it doesn't change the value of lastname.
I think you should do:
String genName = lastname.subString(lastname.lengh()-2);
lastname.substring(lastname.length() - 2) should return the last 2 letters.
lastname.substring(0, 2) returns the first two.
substring(index) is includive
substring(index1, index2) is inclusive, exclusive respectively.