The input is meant to appear like this, example.
\n
Kazan R
\n
6789
\n
Nzk462
\n
However the output I receive looks like this
kzn462nullnzk
Why is this? and How can i solve it?
private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {
secondname = JOptionPane.showInputDialog("Enter your surname:");
firstname = JOptionPane.showInputDialog("Enter your firstname:");
idno = JOptionPane.showInputDialog("Enter your idno:");
nametag = firstname.substring(0, 1);
initials = secondname + " " + nametag;
int randnum;
do {
randnum = (int) (Math.random() * 900) + 100;
} while (randnum % 2 != 0);
code = secondname.replaceAll("[aeiou || AEIOU](?!\\b)", "")+randnum ;
txaDisplay.append(initials + '\n' + idno.substring(6,10) + '\n' + code);
int length = secondname.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + secondname.charAt(i);
}
String end = reverse + code;
txaDisplay.append( reverse);
Why don't you use
new StringBuilder(secondname).reverse().toString()
to reverse your String? It's better, simple and more maintanable.
Get the character array from your source string
Create a new char array of same length
Start iterating from 0 to (sourceStringLength-1)
In each iteration, get the last character
from the end in your source array and populate in your new array
Create a new string from this new array
String source = "abcdefg";
char[] chars = source.toCharArray();
char[] reverseChars = new char[source.length()];
int len = source.length();
for(int i= 0; i < len; i++){
reverseChars[i] = chars[len-1-i];
}
String reverse = new String(reverseChars);
System.out.println(reverse);
Since You don't want to use StringBuilder/StringBuffer.
Try this
String reversedString="";
for(int i=inputString.length-1;i>=0;){
reversedString+=inputString.charAt(i--);
}
I think the problem is your definition of reverse, maybe you have something like:
String reverse;
Then you don't initialize your "reverse" so when your program makes the first concatenation in your loop, it looks like this:
reverse = null + secondname.charAt(i);
The null value is converted to a string so it can be visible in the output.
I hope this information helps you.
Good Luck.
Related
I'm encountering some confusing behavior when trying to create an array of certain length. The length is obtained by a file read in the function getTermNums. When I try to create an array of this size, my code runs in a strange order, my i values are skewed, and the code generally doesn't run as intended. When I instead create an array of a set integer amount, the code runs as intended without error.
double[] terms;
int numTerms = getNumTerms(lines[0]);
terms = new double[numTerms];
int i = 1;
for (i = 1; i<terms.length; i++){
//terms[i] = calculateTerm(T, lines[i]);
}
the above code runs incorrectly.
double[] terms;
int numTerms = getNumTerms(lines[0]);
int myNum = 200;
terms = new double[myNum];
int i = 1;
for (i = 1; i<terms.length; i++){
//terms[i] = calculateTerm(T, lines[i]);
the above code runs correctly
int getNumTerms(String line){
int i = 60;
int j = 0;
char[] word;
word = new char[4];
int numTerms;
int numTermLen = 0;
while(new String(word).compareTo("TERM") != 0){
for (j=0; j<4; j++){
word[j] = line.charAt(i + j);
}
i++;
}
j = i - 3;
while( new Character(line.charAt(j)).equals(' ') == false){
numTermLen++;
j--;
}
j++;
println("i in here: ", i);
numTerms = Integer.parseInt(line.substring(j, j + numTermLen));
return numTerms;
}
this is the function that I'm calling to read the numterms for the size of the array in the first example that doesn't work correctly.
When I use the function call to set the size of array terms[], i starts at some value like 380, and the iteration through array lines[] begins somewhere in the middle of the array.
When I use the integer myNum to set the size of array terms[], i starts at 1, and the iteration through array lines[] begins at the first line, as intended.
Any explanation is appreciated! I'm new to coding in java and am confused by the source of this error.
Thanks in advance.
Without seeing the text it's tiresome to deduct where in your getNumTerms the error occurs.
You can make use of String's indexOf() to find the index of "TERM" and substring() to extract the String containing the integer value.
As far as I understand the ideal string would have "TERM" followed by an integer then a space character. If these items are found and the value fits within 32 bits you should be able to use something like this:
String line = "LINE START TERM-1238847 LINE END";
int getTerm(String line){
int result = Integer.MAX_VALUE;
final String SEARCH_TOKEN = "TERM";
// look for TERM token and remember index
int termIndex = line.indexOf(SEARCH_TOKEN);
// handle not found
if(termIndex < 0){
System.err.println("error: " + SEARCH_TOKEN + " not found in line");
return result;
}
// move index by the size of the token
termIndex += SEARCH_TOKEN.length();
int spaceIndex = line.indexOf(' ',termIndex);
if(spaceIndex < 0){
System.err.println("error: no SPACE found after " + SEARCH_TOKEN);
return result;
}
// chop string extracing between token end and first space encountered
String intString = line.substring(termIndex,spaceIndex);
// try to parse int handling error
try{
result = Integer.parseInt(intString);
}catch(Exception e){
System.err.println("error parsing integer from string " + intString);
e.printStackTrace();
}
return result;
}
System.out.println("parsed integer: " + getTerm(line));
This question already has answers here:
Java substring: 'string index out of range'
(13 answers)
Closed 3 years ago.
I'm attempting to scramble two random letters of a string which isn't the first letter, or last two. I'm getting a "String index out of range" error when compiling. I've tried workshopping many different solutions, but nothing seems to work.
For this assignment, we have to use a method and .charAt commands. I've tried creating variables for the two random characters then adding them back into the string flipped, but couldn't get that to work either.
public static String scramble(String input) {
int range = input.length() - 3;
int place = (int)(Math.random() * range);
String newWord = "";
newWord = input.substring(0, place);
newWord = newWord + newWord.charAt(place) + 2;
newWord = newWord + newWord.charAt(place) + 1;
return newWord;
I'm expecting an output of a string with two of its characters scrambled. For example, "Fantastic" would be "Fantsatic", or "Fnatastic".
Try something like this:
public static String scramble(String input) {
int range = input.length() - 3;
int place = (int)(Math.random() * range);
String newWord = input.substring(0, place);
newWord = newWord + input.charAt(place + 1);
newWord = newWord + input.charAt(place);
// if you need the whole input, just 2 characters exchanged, uncomment this next line
// newWord = newWord + input.substring(place + 2, range);
return newWord;
}
You do :
newWord = input.substring(0, place);
So the indexes inside newWord goes from 0 to place-1
Then you do:
newWord.charAt(place);
But this index does not exist in your String. It is Out of Bound
See the doc
When you create newWord = input.substring(0, place) it has exactly place characters. You can't request charAt(place) from it, the last character is at place-1.
If you want to swap characters convert input to char[] and generate random indexes to swap.
String input = "Fantastic";
// random constraints
int min = 1;
int max = input.length() - 3;
// random two characters to swap
int from = min + (int) (Math.random() * max);
int to;
do {
to = min + (int) (Math.random() * max);
} while (to == from); // to and from are different
// swap to and from in chars
char[] chars = input.toCharArray();
char tmp = chars[from];
chars[from] = chars[to];
chars[to] = tmp;
String result = new String(chars);
System.out.println(result); // Ftntasaic
you can try
public static String scramble(String input) {
if(input.length() >3){
int range = input.length() - 3;
int place = 1+ new Random().nextInt(range) ;
input=input.substring(0, place) +input.charAt(place + 1)+input.charAt(place) +input.substring( place+2);
}
return input;
}
input: Fantastic
output : Fanatstic , Fatnastic ,Fanatstic
I need to get a new string based on an old one and a lag. Basically, I have a string with the alphabet (s = "abc...xyz") and based on a lag (i.e. 3), the new string should replace the characters in a string I type with the character placed some positions forward (lag). If, let's say, I type "cde" as my string, the output should be "fgh". If any other character is added in the string (apart from space - " "), it should be removed. Here is what I tried, but it doesn't work :
String code = "abcdefghijklmnopqrstuvwxyzabcd"; //my lag is 4 and I added the first 4 characters to
char old; //avoid OutOfRange issues
char nou;
for (int i = 0; i < code.length() - lag; ++i)
{
old = code.charAt(i);
//System.out.print(old + " ");
nou = code.charAt(i + lag);
//System.out.println(nou + " ");
// if (s.indexOf(old) != 0)
// {
s = s.replace(old, nou);
// }
}
I commented the outputs for old and nou (new, but is reserved word) because I have used them only to test if the code from position i to i + lag is working (and it is), but if I uncomment the if statement, it doesn't do anything and I leave it like this, it keeps executing the instructions inside the for statmement for code.length() times, but my string doesn't need to be so long. I have also tried to make the for statement like below, but I got lost.
for (int i = 0; i < s.length(); ++i)
{
....
}
Could you help me with this? Or maybe some advices about how I should think the algorithm?
Thanks!
It doesn't work because, as the javadoc of replace() says:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
(emphasis mine)
So, the first time you meet an 'a' in the string, you replace all the 'a's by 'd'. But then you go to the next char, and if it's a 'd' that was an 'a' before, you replace it once again, etc. etc.
You shouldn't use replace() at all. Instead, you should simply build a new string, using a StringBuilder, by appending each shifted character of the original string:
String dictionary = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char oldChar = input.charAt(i);
int oldCharPositionInDictionary = dictionary.indexOf(oldChar);
if (oldCharPositionInDictionary >= 0) {
int newCharPositionInDictionary =
(oldCharPositionInDictionary + lag) % dictionary.length();
sb.append(dictionary.charAt(newCharPositionInDictionary));
}
else if (oldChar == ' ') {
sb.append(' ');
}
}
String result = sb.toString();
Try this:
Convert the string to char array.
iterate over each char array and change the char by adding lag
create new String just once (instead of loop) with new String passing char array.
String code = "abcdefghijklmnopqrstuvwxyzabcd";
String s = "abcdef";
char[] ch = s.toCharArray();
char[] codes = code.toCharArray();
for (int i = 0; i < ch.length; ++i)
{
ch[i] = codes[ch[i] - 'a' + 3];
}
String str = new String(ch);
System.out.println(str);
}
My answer is something like this.
It returns one more index to every character.
It reverses every String.
Have a good day!
package org.owls.sof;
import java.util.Scanner;
public class Main {
private static final String CODE = "abcdefghijklmnopqrstuvwxyz"; //my lag is 4 and I added the first 4 characters to
#SuppressWarnings("resource")
public static void main(String[] args) {
System.out.print("insert alphabet >> ");
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
char[] char_arr = s.toCharArray();
for(int i = 0; i < char_arr.length; i++){
int order = CODE.indexOf(char_arr[i]) + 1;
if(order%CODE.length() == 0){
char_arr[i] = CODE.charAt(0);
}else{
char_arr[i] = CODE.charAt(order);
}
}
System.out.println(new String(char_arr));
//reverse
System.out.println(reverse(new String(char_arr)));
}
private static String reverse (String str) {
char[] char_arr = str.toCharArray();
for(int i = 0; i < char_arr.length/2; i++){
char tmp = char_arr[i];
char_arr[i] = char_arr[char_arr.length - i - 1];
char_arr[char_arr.length - i - 1] = tmp;
}
return new String(char_arr);
}
}
String alpha = "abcdefghijklmnopqrstuvwxyzabcd"; // alphabet
int N = alpha.length();
int lag = 3; // shift value
String s = "cde"; // input
StringBuilder sb = new StringBuilder();
for (int i = 0, index; i < s.length(); i++) {
index = s.charAt(i) - 'a';
sb.append(alpha.charAt((index + lag) % N));
}
String op = sb.toString(); // output
public String getEncryption(String text){
String x = "";
for(int i = 0; i < text.length(); i++){
String sub = text.substring(i, i+1);
System.out.println(i + " = " + sub);
String en = encrypt_code[Integer.parseInt(sub)];
System.out.println("Result:" + en);
x = x.concat(en);
}
return x;
}
I have this coding which works perfectly but I need to know how to use the charAt method to convert this and works in the same way? I have this so far
public String getEncryption2(String text){
String x = "";
for(int i = 0; i < text.length(); i++){
char ch = text.charAt(i);
You're reading every char as a substring, and parse it as an int. So, you get for example "4" as the substring, and parse it to get the int 4.
If you use charAt(), you'll get the char '4' instead. To transform it to the integer 4, you just need to subtract '0' from it:
String en = encrypt_code[ch - '0'];
Note that replacing the whole string by a new one at each iteration is time consuming. You should use a StringBuilder instead:
StringBuilder x = new StringBuilder();
for (...) {
x.append(en);
}
return x.toString();
I have a string like this:[name ;24, name;23, name;22]. How can i split this string to obtain only the numbers after";"?
String s = "[name ;24, name;23, name;22]";
String couples[] = s.replace("]", "").split(",");
int ages[] = new int[couples.length];
for (int i=0; i< couples.length; i++)
ages[i] = Integer.parseInt(couples[i].split(";")[1]);
// Your input looks like this.
String s = "[name ;24, name;23, name;22]";
String[] numberStrings = s
// First get rid of the known prefix and suffix
.substring("[name ;".length(), s.length - "]".length())
// Then split on the repeated portion that occurs between numbers.
.split(", name;");
yet another method
String str = "name ;24, name;23, name;22";
int p = 0;
while ((p = str.indexOf(";", p + 1)) > -1) {
System.out.println(str.substring(p+1).split("[^0-9]")[0]);
}