I am trying to get user input for sortValues[] array using the for statement (enter character 1, enter character 2, etc).
However, when I execute this, the program will not allow me to enter for character 2, instead skipping directly to character 3, as seen below.
How to resolve this? The code is included below.
thanks!
static public void s_1d_char () {
int counter=0;
int x=0;
c.print("How many characters? ");
counter = readInt();
char[] sortValues = new char[counter+1];
for (x=1;x<=counter;x++) {
System.out.println("Enter character "+(x)+":");
sortValues[x] = readChar();
}
}
readChar implementation (this is from a library):
public synchronized char readChar ()
{
char result, ch;
if (ungotChar != EMPTY_BUFFER)
{
result = (char) ungotChar;
ungotChar = EMPTY_BUFFER;
return (result);
}
if (lineBufferHead != lineBufferTail)
{
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
return (result);
}
startRow = currentRow;
startCol = currentCol;
if (currentRow > maxRow)
{
startRow++;
currentCol = 1;
}
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (true);
// Wait for a character to be entered
while (true)
{
ch = getChar ();
if (ch == '\n')
{
clearToEOL = false;
if (echoOn)
print ("\n");
clearToEOL = true;
lineBuffer [lineBufferHead] = '\n';
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
break;
}
if (ch == '\b')
{
if (lineBufferHead == lineBufferTail)
{
consoleCanvas.invertScreen ();
}
else
{
int chToErase;
lineBufferHead = (lineBufferHead + lineBuffer.length - 1) % lineBuffer.length;
chToErase = lineBuffer [lineBufferHead];
if (echoOn)
{
if (chToErase != '\t')
{
erasePreviousChar ();
}
else
{
int cnt;
eraseLineOfInput ();
cnt = lineBufferTail;
while (cnt != lineBufferHead)
{
print (lineBuffer [cnt]);
cnt = (cnt + 1) % lineBuffer.length;
}
}
}
}
} // if backspace
else if (ch == '\025')
{
if (echoOn)
{
eraseLineOfInput ();
}
lineBufferHead = lineBufferTail;
}
else
{
if (echoOn)
{
print (ch);
}
lineBuffer [lineBufferHead] = ch;
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
}
} // while
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (false);
return (result);
}
I recommend getting user input with a scanner:
import java.util.Scanner;
// ...
int counter = 0;
System.out.println("How many characters?");
Scanner keyboard = new Scanner(System.in);
counter = keyboard.nextInt();
char[] sortValues = new char[counter+1];
// Start your index variable off at 0
for (int x = 0; x < counter; x++) {
System.out.println("Enter character "+(x)+":");
keyboard = new Scanner(System.in);
String line = keyboard.nextLine();
sortValues[x] = line.charAt(0);
}
This will capture the first character of the line. If the user enters more than one character, the program will read only the first.
Also, you should really start your index variable x off at 0, considering arrays are 0-based indexed.
instead of readChar() try:
sortValues[x] = Integer.parseInt(System.console().readLine());
How to read integer value from the standard input in Java
Related
I'm currently doing an online course on hyperskill. There's a task:
The password is hard to crack if it contains at least A uppercase
letters, at least B lowercase letters, at least C digits and includes
exactly N symbols. Also, a password cannot contain two or more same
characters coming one after another. For a given numbers A, B, C, N
you should output password that matches these requirements.
And here's my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = scan.nextInt();
int lower = scan.nextInt();
int digits = scan.nextInt();
int quantity = scan.nextInt();
String symbolsUpper = "QWERTYUIOPASDFGHJKLZXCVBNM";
String symbolsLower = "qwertyuiopasdfghjklzxcvbnm";
String symbolsDigits = "1234567890";
boolean exit = false;
Random random = new Random();
ArrayList<Character> password = new ArrayList<>();
if (upper > 0) {
for (int i = 0; i < upper; i++) {
password.add(symbolsUpper.charAt(random.nextInt(symbolsUpper.length())));
}
}
if (lower > 0) {
for (int k = 0; k < lower; k++) {
password.add(symbolsLower.charAt(random.nextInt(symbolsLower.length())));
}
}
if (digits > 0) {
for (int z = 0; z < digits; z++) {
password.add(symbolsDigits.charAt(random.nextInt(symbolsDigits.length())));
}
}
if (quantity - digits - upper - lower > 0) {
for (int m = 0; m < (quantity - digits - upper - lower); m++) {
password.add(symbolsDigits.charAt(random.nextInt(symbolsDigits.length())));
}
}
Collections.shuffle(password);
while (!exit) {
if (password.size() > 1) {
for (int i = 1; i < password.size(); i++) {
if (password.get(i).equals(password.get(i - 1))) {
char buffer = password.get(i);
password.remove(i);
password.add(buffer);
i--;
} else {
exit = true;
}
}
} else {
exit = true;
}
}
StringBuilder buildPassword = new StringBuilder();
for (Character character : password) {
buildPassword.append(character);
}
System.out.println(buildPassword);
}
}
When I run the code in IntelliJ IDEA, the program works just fine, however, the hyperskill platform doesn't accept this code as the right one.
The topic is "Processing string".
Can anyone here tell me please, what am I doing wrong? Is there a better way to write this code?
Can anyone here tell me please, what am I doing wrong?
The problem is that, due to the nature of random numbers, you might be very unlucky in the characters which are picked. This can result in two problems:
You can pick the same characters from the pool of characters. When you create a password using the input 0 0 0 2 it might be possible that two same digits are picked. As an example the password "55" can never satisfy the condition of having not two characters next to each other be the same, no matter how many time you shuffle it.
When the password is very long and you find two characters same next to each other you put one of the character to the end. This can happen twice for the same character. This means that the password "........44........44........." can result in the password ".........4.........4...........44", and now you have two same characters again (at the end).
Is there a better way to write this code?
Yes.
I don't know if you are trying for best performance, but here is a fun solution:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int uppers = scan.nextInt();
int lowers = scan.nextInt();
int digits = scan.nextInt();
int quantity = scan.nextInt();
int freeChoices = quantity - uppers - lowers - digits;
if (freeChoices < 0) {
System.exit(1);
}
ThreadLocalRandom r = ThreadLocalRandom.current();
StringBuilder password = new StringBuilder();
boolean isPasswordReady = false;
int lastUpper = -1, lastLower = -1, lastDigit = -1;
PasswordPart[] options = PasswordPart.values();
while (!isPasswordReady) {
int partChoice = r.nextInt(0, options.length);
switch (options[partChoice]) {
case DIGIT:
if (digits > 0 || freeChoices > 0) {
CharIndexHolder result = options[partChoice].get(lastDigit, -1, r);
password.append(result.c);
lastDigit = result.i;
if (digits == 0) {
freeChoices--;
} else {
digits--;
}
}
break;
case LOWER:
if (lowers > 0 || freeChoices > 0) {
CharIndexHolder result = options[partChoice].get(lastLower, lastUpper, r);
password.append(result.c);
lastLower = result.i;
if (lowers == 0) {
freeChoices--;
} else {
lowers--;
}
}
break;
case UPPER:
if (uppers > 0 || freeChoices > 0) {
CharIndexHolder result = options[partChoice].get(lastUpper, lastLower, r);
password.append(result.c);
lastUpper = result.i;
if (uppers == 0) {
freeChoices--;
} else {
uppers--;
}
}
break;
}
isPasswordReady = uppers == 0 && lowers == 0 && digits == 0 && freeChoices == 0;
}
System.out.println(password.toString());
}
enum PasswordPart {
UPPER("QWERTYUIOPASDFGHJKLZXCVBNM"), LOWER("qwertyuiopasdfghjklzxcvbnm"), DIGIT("1234567890");
private String pool;
PasswordPart(String pool) {
this.pool = pool;
}
public CharIndexHolder get(int lastIndex, int additionalIndex, ThreadLocalRandom random) {
int i = random.nextInt(0, pool.length());
while (i == lastIndex || i == additionalIndex) {
i = random.nextInt(0, pool.length());
}
return new CharIndexHolder(pool.charAt(i), i);
}
}
private static class CharIndexHolder {
char c;
int i;
CharIndexHolder(char c, int i) {
this.c = c;
this.i = i;
}
}
import java.util.*;
public class Main_5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for(int i = 0; i < m; i++){
String password = sc.nextLine();
System.out.println(got(password));
}
}
public static String got(String password) {
HashMap<Character, Integer> checkpass = new HashMap<>();
Character ch = null;
Integer val = 0;
int odd = 0, even = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (checkpass.containsKey(ch) == false) {
checkpass.put(ch, 1);
} else {
val = (Integer) checkpass.get(ch);
checkpass.put(ch, val + 1);
}
}
Set<Character> hashval = checkpass.keySet();
for (Character key : hashval) {
val = (Integer) checkpass.get(key);
if (val == password.length())
return "YES";
else if (val % 2 == 1)
odd++;
else
even++;
}
if (odd == 1 || odd == 0)
return "YES";
else
return "NO";
}
}
PLEASE TEST THIS OUT FOR YOURSELF
As you can see, there is integer m in the main method. When I hit run, it makes integer m as if it were part of the got method. This is a code to find if x Strings can be a permutation palindrome.
This should what the console should look like:
*Input*:
3
ccaabcbb
azzza
bbbbccccdddddddd
*Output*:
NO
YES
YES
Use sc.next() instead sc.nextLine() as its giving the empty line created by your first enter.
import java.util.*;
public class Main_5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for(int i = 0; i < m; i++){
String password = sc.next();
System.out.println(got(password));
}
}
public static String got(String password) {
HashMap<Character, Integer> checkpass = new HashMap<>();
Character ch = null;
Integer val = 0;
int odd = 0, even = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (checkpass.containsKey(ch) == false) {
checkpass.put(ch, 1);
} else {
val = (Integer) checkpass.get(ch);
checkpass.put(ch, val + 1);
}
}
Set<Character> hashval = checkpass.keySet();
for (Character key : hashval) {
val = (Integer) checkpass.get(key);
if (val == password.length())
return "YES";
else if (val % 2 == 1)
odd++;
else
even++;
}
if (odd == 1 || odd == 0)
return "YES";
else
return "NO";
}
}
I my be wrong, but rewritting getting m to this:
int m = Integer.parseInt(sc.nextLine());
should do the trick. There is problem using scanner's nextInt() and reading new line from standard input.
Hi All I'm using the following function to check the Consecutive digits in java
The issue im facing here is it works for the first Consecutive digits only
For example it work for 123456789123456XXXX
but want this to work Consecutive any where
XXXX123456789123456 or XX123456789123456XX
Update
Now if i found 13 Consecutive digits then i need to pass all Consecutive digits to the mask function
and my result should be
something like this
for input 123456789123456XXXX result should be 123456%%%%%3456XXXX
for input XXXX123456789123456 result should be XX123456%%%%%3456XX
Please help me to solve this
My Code
public void checkPosCardNoAndMask(String cardNo) {
String maskNumber = "";
String starValue = "";
boolean isConsecutive = false;
int checkConsecutive = 0;
for (int i = 0, len = cardNo.length(); i < len; i++) {
if (Character.isDigit(cardNo.charAt(i))) {
maskNumber = maskNumber + cardNo.charAt(i);
} else {
if (checkConsecutive >= 13)
isConsecutive = true;
else
break;
starValue = starValue + cardNo.charAt(i);
}
checkConsecutive++;
}
if (isConsecutive)
{
cardNo = maskCCNumber(maskNumber) + starValue;
System.out.printIn("Consecutive found!!:"+cardNo);
}
else
{
System.out.printIn("Consecutive not found!!:"+cardNo);
}
}
Masking logic
public String maskCCNumber(String ccNo)
{
String maskCCNo = "";
for (int i = 0; i < ccNo.length(); i++)
{
if (i > 5 && i < ccNo.length() - 4)
{
maskCCNo = maskCCNo + '%';
}
else
{
maskCCNo = maskCCNo + ccNo.charAt(i);
}
}
return maskCCNo;
}
With regex you can do this way:
String str = "XX123456789123456XX";
if (str.matches(".*\\d{13}.*")) {
System.out.println(true);
Pattern compile = Pattern.compile("\\d+");
Matcher matcher = compile.matcher(str);
matcher.find();
String masked = maskCCNumber(matcher.group());//send 123456789123456 and returns 123456%%%%%3456
String finalString=str.replaceAll("\\d+", masked);// replace all digits with 123456%%%%%3456
System.out.println(finalString);
}
Output:
true
XX123456%%%%%3456XX
There are few issues:
You're breaking out of else, when first time you find non-digit character. This will skip any consecutive digit coming after that. So, you should not break.
In fact, you should add break out of the loop once you find 13 consecutive digit.
You're not really looking for consecutive digits, but just total number of non-cosnecutive digits. At least the current logic without break would work this way. You should reset the checkConsecutive variable to 0 when you find a non-digit character.
So, changing your for loop to this will work:
for (int i = 0, len = cardNo.length(); i < len; i++)
{
if (Character.isDigit(cardNo.charAt(i))) {
checkConsecutive++;
} else if (checkConsecutive == 13) {
isConsecutive = true;
break;
} else {
checkConsecutive = 0;
}
}
Of course I don't know what is starValue and maskValue, so I've removed it. You can add it appropriately.
BTW, this problem can also be solved with regex:
if (cardNo.matches(".*\\d{13}.*")) {
System.out.println("13 consecutive digits found");
}
try this
public void checkPosCardNoAndMask(String cardNo) {
if (cardNo.matches("[0-9]{13,}")) {
System.out.println("Consecutive found!!");
} else {
System.out.println("Consecutive not found!!");
}
}
If you want to work with your code then make one change
public void checkPosCardNoAndMask(String cardNo) {
String maskNumber = "";
String starValue = "";
boolean isConsecutive = false;
int checkConsecutive = 0;
for (int i = 0, len = cardNo.length(); i < len; i++) {
if (Character.isDigit(cardNo.charAt(i))) {
maskNumber = maskNumber + cardNo.charAt(i);
checkConsecutive++;
} else {
if (checkConsecutive >= 13)
{isConsecutive = true;break;}
else
checkConsecutive=0;
starValue = starValue + cardNo.charAt(i);
}
}
if (isConsecutive) {
System.out.printIn("Consecutive found!!");
} else {
System.out.printIn("Consecutive not found!!");
}
}
try this
public static void checkPosCardNoAndMask(String cardNo) {
int n = 1;
char c1 = cardNo.charAt(0);
for (int i = 1, len = cardNo.length(); i < len && n < 13; i++) {
char c2 = cardNo.charAt(i);
if (c2 >= '1' && c2 <= '9' && (c2 - c1 == 1 || c2 == '1' && c1 == '9')) {
n++;
} else {
n = 0;
}
c1 = c2;
}
if (n == 13) {
System.out.println("Consecutive found!!");
} else {
System.out.println("Consecutive not found!!");
}
}
My understanding is that you want to mask card numbers in a string. There is one external dependency in following code http://commons.apache.org/proper/commons-lang/ for StringUtils
/**
* Returns safe string for cardNumber, will replace any set of 13-16 digit
* numbers in the string with safe card number.
*/
public static String getSafeString(String str) {
Pattern CARDNUMBER_PATTERN = Pattern.compile("\\d{13,16}+");
Matcher matcher = CARDNUMBER_PATTERN.matcher(str);
while (matcher.find()) {
String cardNumber = matcher.group();
if (isValidLuhn(cardNumber)) {
str = StringUtils.replace(str, cardNumber, getSafeCardNumber(cardNumber));
}
}
return str;
}
public static boolean isValidLuhn(String cardNumber) {
if (cardNumber == null || !cardNumber.matches("\\d+")) {
return false;
}
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
/**
* Returns safe string for cardNumber, will keep first six and last four
* digits.
*/
public static String getSafeCardNumber(String cardNumber) {
StringBuilder sb = new StringBuilder();
int cardlen = cardNumber.length();
if (cardNumber != null) {
sb.append(cardNumber.substring(0, 6)).append(StringUtils.repeat("%", cardlen - 10)).append(cardNumber.substring(cardlen - 4));
}
return sb.toString();
}
This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
When I do different combinations like d-c+a+b it gives me a inccorect number like 118.0. Can someone tell me where in my code my calculations are wrong..
Thank you
the ValVarPairs.txt contains these numbers-> a=100,b=5,c=10,d=13
This is what i coded.
package com.ecsgrid;
import java.io.*;
public class testC {
public static void main(String[] args) {
int i = 0,j = 0;
double result, values[] = new double[4];
char k, operators[] = new char[3];
for (i = 0; i <= 2; i++)
operators[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)){
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
}
catch(FileNotFoundException e) { System.err.println(e); return; }
catch(IOException f) { System.out.println(f); return; }
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine();
}
catch(IOException f) { System.out.println(f); return; }
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
result = values[0];
for (i = 0; i <= 2; i++){
if (operators[i] == '+')
result = result + values[i+1];
else
result = result - values[i+1];
}
System.out.println(result);
}
}
Right now you would be getting the same output if your input was -++
You never parse for the order or a, b, c and d. You always assume the order a->b->c->d.
So d-c+a+b will be: a-b+c+d which is consistent with the output you provided(100-5+10+13 = 118)
OP's CODE
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
/OP'S CODE
In this loop, when k is not an operator, you should be reading which letter it is, and store the order in which the letters appeared. Or build some other kind of mapping. In any case you can't just ignore non-operator characters because they are part of the input.
Let's debug this a little, add a few system outs...
this is what you would see for each step
100.0 - 5.0
95.0 + 10.0
105.0 + 13.0
118.0
your value array is {100,5,10,13} and your operator array is {-,+,+}
you have not mapped a = 100, b = 5, c= 10, d = 13, unless you map those then parse the operands using the mapping based on the non operand input keys, it is not going to work.
So, if I were to use the character's int values, I would be able to translate it this way.
import java.io.*;
public class TestC {
public static void main(String[] args) {
int i = 0, j = 0;
double result, values[] = new double[4];
char k, operatorsAndOperands[] = new char[3];
for (i = 0; i <= 2; i++)
operatorsAndOperands[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)) {
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
for (int l = 0; l < values.length; l++) {
System.out.println(values[l]);
}
} catch (FileNotFoundException e) {
System.err.println(e);
return;
} catch (IOException f) {
System.out.println(f);
return;
}
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine().toUpperCase();
} catch (IOException f) {
System.out.println(f);
return;
}
if(InputText.length() > 0){
operatorsAndOperands = new char[InputText.length()];
} else {
System.out.println("No Operations specified");
return;
}
for (i = 0; i < InputText.length(); i++) {
k = InputText.charAt(i);
operatorsAndOperands[j++] = k;
}
result = 0;
for (i = 0; i < operatorsAndOperands.length; i++) {
System.out.println(operatorsAndOperands[i] + " " + (int)operatorsAndOperands[i]);
if(i+1<operatorsAndOperands.length)
System.out.println(operatorsAndOperands[i+1]);
switch(operatorsAndOperands[i]){
case '+':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result+=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
case '-':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result-=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
default:
result = values[(int)operatorsAndOperands[i] - (int)'A'];
break;
};
System.out.println(result);
}
System.out.println(result);
}
}
My goal is to write a program that compresses a string, for example:
input: hellooopppppp!
output:he2l3o6p!
Here is the code I have so far, but there are errors.
When I have the input: hellooo
my code outputs: hel2l3o
instead of: he213o
the 2 is being printed in the wrong spot, but I cannot figure out how to fix this.
Also, with an input of: hello
my code outputs: hel2l
instead of: he2lo
It skips the last letter in this case all together, and the 2 is also in the wrong place, an error from my first example.
Any help is much appreciated. Thanks so much!
public class compressionTime
{
public static void main(String [] args)
{
System.out.println ("Enter a string");
//read in user input
String userString = IO.readString();
//store length of string
int length = userString.length();
System.out.println(length);
int count;
String result = "";
for (int i=1; i<=length; i++)
{
char a = userString.charAt(i-1);
count = 1;
if (i-2 >= 0)
{
while (i<=length && userString.charAt(i-1) == userString.charAt(i-2))
{
count++;
i++;
}
System.out.print(count);
}
if (count==1)
result = result.concat(Character.toString(a));
else
result = result.concat(Integer.toString(count).concat(Character.toString(a)));
}
IO.outputStringAnswer(result);
}
}
I would
count from 0 as that is how indexes work in Java. Your code will be simpler.
would compare the current char to the next one. This will avoid printing the first character.
wouldn't compress ll as 2l as it is no smaller. Only sequences of at least 3 will help.
try to detect if a number 3 to 9 has been used and at least print an error.
use the debugger to step through the code to understand what it is doing and why it doesn't do what you think it should.
I am doing it this way. Very simple:
public static void compressString (String string) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
int count = 1;
while (i + 1 < string.length()
&& string.charAt(i) == string.charAt(i + 1)) {
count++;
i++;
}
if (count > 1) {
stringBuffer.append(count);
}
stringBuffer.append(string.charAt(i));
}
System.out.println("Compressed string: " + stringBuffer);
}
You can accomplish this using a nested for loops and do something simial to:
count = 0;
String results = "";
for(int i=0;i<userString.length();){
char begin = userString.charAt(i);
//System.out.println("begin is: "+begin);
for(int j=i+1; j<userString.length();j++){
char next = userString.charAt(j);
//System.out.println("next is: "+next);
if(begin == next){
count++;
}
else{
System.out.println("Breaking");
break;
}
}
i+= count+1;
if(count>0){
String add = begin + "";
int tempcount = count +1;
results+= tempcount + add;
}
else{
results+= begin;
}
count=0;
}
System.out.println(results);
I tested this output with Hello and the result was He2lo
also tested with hellooopppppp result he2l3o6p
If you don't understand how this works, you should learn regular expressions.
public String rleEncodeString(String in) {
StringBuilder out = new StringBuilder();
Pattern p = Pattern.compile("((\\w)\\2*)");
Matcher m = p.matcher(in);
while(m.find()) {
if(m.group(1).length() > 1) {
out.append(m.group(1).length());
}
out.append(m.group(2));
}
return out.toString();
}
Try something like this:
public static void main(String[] args) {
System.out.println("Enter a string:");
Scanner IO = new Scanner(System.in);
// read in user input
String userString = IO.nextLine() + "-";
int length = userString.length();
int count = 0;
String result = "";
char new_char;
for (int i = 0; i < length; i++) {
new_char = userString.charAt(i);
count++;
if (new_char != userString.charAt(i + 1)) {
if (count != 1) {
result = result.concat(Integer.toString(count + 1));
}
result = result.concat(Character.toString(new_char));
count = 0;
}
if (userString.charAt(i + 1) == '-')
break;
}
System.out.println(result);
}
The problem is that your code checks if the previous letter, not the next, is the same as the current.
Your for loops basically goes through each letter in the string, and if it is the same as the previous letter, it figures out how many of that letter there is and puts that number into the result string. However, for a word like "hello", it will check 'e' and 'l' (and notice that they are preceded by 'h' and 'e', receptively) and think that there is no repeat. It will then get to the next 'l', and then see that it is the same as the previous letter. It will put '2' in the result, but too late, resulting in "hel2l" instead of "he2lo".
To clean up and fix your code, I recommend the following to replace your for loop:
int count = 1;
String result = "";
for(int i=0;i<length;i++) {
if(i < userString.length()-1 && userString.charAt(i) == userString.charAt(i+1))
count++;
else {
if(count == 1)
result += userString.charAt(i);
else {
result = result + count + userString.charAt(i);
count = 1;
}
}
}
Comment if you need me to explain some of the changes. Some are necessary, others optional.
Here is the solution for the problem with better time complexity:
public static void compressString (String string) {
LinkedHashSet<String> charMap = new LinkedHashSet<String>();
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
int count;
String key;
for (int i = 0; i < string.length(); i++) {
key = new String(string.charAt(i) + "");
charMap.add(key);
if(countMap.containsKey(key)) {
count = countMap.get(key);
countMap.put(key, count + 1);
}
else {
countMap.put(key, 1);
}
}
Iterator<String> iterator = charMap.iterator();
String resultStr = "";
while (iterator.hasNext()) {
key = iterator.next();
count = countMap.get(key);
if(count > 1) {
resultStr = resultStr + count + key;
}
else{
resultStr = resultStr + key;
}
}
System.out.println(resultStr);
}