I need to input and load some chars in a boolean 2-D array. If the char is X, mark the array element as true; else if the char is ., mark the array element as false.
Here is my design:
boolean[][] Array = new boolean[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (System.in.read() == '.') {
Array[i][j] = false;
} else if (System.in.read() == 'X') {
Array[i][j] = true;
}
}
}
And, for example, if I type in .... or XXXX, it does not produce the correct result. Also for other input the result is not correct.
So how to deal with this?
You are reading a character a second time in the loop if the first character is not a '.'.
You should only read one character per loop. Save the character in a variable before your if statement, and then compare the variable to '.' and 'X' in turn.
You shouldn't call the read() function in each if statement. Call it one time and store it in a variable so you don't keep reading through the input. That could be one thing messing up your function. Another is how you are comparing chars with the == operator. Should use char.equals method for character comparison. Put a couple breakpoints in and see what values are being sent through to debug. Maybe try something like the following:
boolean[][] Array= new boolean[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Character input = (char)System.in.read();
if (input.equals('.')) {
Array[i][j] = false;
} else if (input.equals('X')) {
Array[i][j] = true;
}
}
}
Related
This question already has answers here:
How to replace multiple consecutive occurrences of a character with a maximum allowed number of occurences?
(2 answers)
Closed 3 years ago.
I need to write a method that takes a String as a parameter and returns a new String obtained by replacing every instance of repeated adjacent letters with a 'n' instances of that string.
For example, if "aaabcccd" as an input String and n =2, it returns "aabccd". I already tried the following code, but not getting expected output
String in = "aaadbbb";
char[] s = in.toCharArray();
int len = s.length;
int n = 2;
StringBuffer new_s = new StringBuffer("");
int count = 1;
char prev='\0';
for (int i = 0; i < len - 1; i++) {
if (s[i] == s[i + 1]) {
if(count <= n){
new_s.append(s[i]);
count++;
}else{
count=1;
}
} else {
new_s.append(s[i]);
}
}
System.out.println(new_s);
output-aaadb
expected-aadbb
Can be done with regexp magic using backreferences.
String in = "aaaaddbbbbc";
int n = 2;
String pattern = String.format("(([a-z])\\2{%d})\\2+", n - 1);
System.out.println(in.replaceAll(pattern, "$1"));
Outputs:
aaddbbc
Explanation:
The number inside {} is n-1.
([a-z]) is a capture group, matching any single lowercase letter from a to z. Since it's a second group of parentheses in the expression, it can be referenced as 2.
(([a-z])\\2{n}) means "match n+1 repetitions of same letter". It makes up a first capture group, and we'll use that as replacement
\\2+ matches all the extra repetitions of the same letter. They are discarded after replacement.
public static String test(String input, int repetitions) {
String flag = "";
String replacement = "";
String output = input;
ArrayList<Character> prevLetters = new ArrayList<Character>();
for(int x = 0; x < input.length(); x++) {
if(!prevLetters.contains(input.charAt(x))) {
for(int y = 0; y <= repetitions ; y++) {
flag += String.valueOf(input.charAt(x));
}
if(input.contains(flag)) {
replacement = flag.substring(0, flag.length()-1);
while(output.contains(flag)){
output = output.replace(flag, replacement);
}
}
flag = "";
prevLetters.add(input.charAt(x));
}
}
return output;
}
That is my solution, which follows a similar idea as yours. Rather than comparing each character value however, I thought it would be easier to simply check for a break in the rules (character appearing n+1 times in a row) and 'fix' it.
If you are interested in using your method, one potential issue that I noticed is that you aren't assigning count to 1 in your last else. You also won't have the chance to add the final character due to you only adding the character at index 'i' when the duration for the loop is len - 1.
To add one more alternative:
String in = "aaadbbbjjkllllllopp";
int n = 2;
StringBuilder sb = new StringBuilder();
char temp = in.charAt(0);
for(int i = 0; i < in.length()-1;){ // note that the incrementation of i is moved to the while loop
temp = in.charAt(i); // save current char in temp variable
int count = 0;
while (i < in.length() && in.charAt(i) == temp) { ///iterate as long as you find same chars or hit the end of the string
i++;
count++;
}
if (count > n){ // if and only if count is greater than max allowed set it to max allowed
count = n;
}
for(int j = 0; j < count; j++){ // append count chars
sb.append(temp);
}
}
System.out.println(sb.toString());
Look at this solution. You should take care of the last char in your input string, as you iterate only to the last but one.
private void replaceConsecutiveDuplicates() {
String input = "aaadbbb";
int n = 2;
StringBuffer sb = new StringBuffer();
int count = 1;
char current;
for( int i = 0; i < input.length(); ++i){
current = input.charAt(i);
if (i + 1 < input.length() && current == input.charAt(i + 1)) {
++count;
} else if (count > 1) {
for(int j = 0; j < n; ++j) {
sb.append(current);
}
count = 1;
}
else {
sb.append(current);
}
}
System.out.println(sb.toString());
}
I think you're on the right track. I'm not sure whether this is an assignment, so I don't want to just straight up give you an answer, but here are some hints that might help:
You're already iterating over the string. This is great! However, I think you want to compare the current character with the previous character, and not the next character.
You don't need to convert your input to a char array to iterate over it, just use charAt(idx)
You never seem to use prev, but I think you had the right idea in mind when you declared it!
Break your problem into two parts: When to update count and when to append a character. You can tackle both in your for loop, but instead of trying to do both things in the same if statements, break it up into multiple ifs.
The 3 things to do are:
Update Prev Value
Update Count
Update new String
Getting the right order for these and the exact implementation I'll leave to you (again, because I'm not sure if this is an assignment or not)
Update: Since others posted, here is my solution (with single for loop):
private String replaceConsecutiveDuplicates(String input, int n) {
if (input == null || input.length() < n) return input;
if (n == 0) return "";
StringBuffer sb = new StringBuffer();
int count = 1;
char prev = input.charAt(0);
sb.append(prev);
char current;
for( int i = 1; i < input.length(); i++) {
current = input.charAt(i);
if (prev == current) {
if (++count > n) continue;
} else {
count = 1;
}
prev = current;
sb.append(current);
}
return sb.toString();
}
This question already has answers here:
Java: Print a unique character in a string
(20 answers)
Closed 4 years ago.
I am trying to print a character from a string which occurs only one time in the string. Here is the code I am using, but it is showing the answer always as H.
How can I fix this?
class StringRepeat {
static int i,j;
public static void main(String[] args) {
String s1 = "How are How";
outer:for(i=0;i<=s1.length(); i++)
{
inner:for(j=1;j<s1.length(); j++)
{
if (s1.charAt(i) != s1.charAt(j))
break outer;
}
}
System.out.println(s1.charAt(i));
}
}
Basically you can solve this in 2 ways - brute force (using arrays) and a bit more intelligently (using maps).
Brute force way
For every character in the input string check if it is the same as some other character:
public void uniqueCharsBruteForce(String input) {
for (int i = 0; i < input.length(); ++i) {
char candidate = input.charAt(i);
if (!contains(input, candidate, i)) {
System.out.println(candidate);
}
}
}
private boolean contains(String input, char candidate, int skipIndex) {
for (int i = 0; i < input.length(); ++i) {
if (i == skipIndex) {
continue;
}
if (candidate == input.charAt(i)) {
return true;
}
}
return false;
}
Code is simple but very slow, so use only for short strings. Time complexity is O(n^2).
Using maps
As you iterate through the input, count how many times each character appears. At the end, print only those who appear once only:
public void uniqueCharsBetter(String input) {
Map<Character, Integer> occurences = new HashMap<>();
for (int i = 0; i < input.length(); ++i) {
Character key = Character.valueOf(input.charAt(i));
occurences.put(key, occurences.getOrDefault(key, 0) + 1);
}
occurences.entrySet().forEach(entry -> {
if (entry.getValue().intValue() == 1) {
System.out.println(entry.getKey());
}
});
}
This can be optimized further but it's possible this is enough for your requirements. Time complexity is O(n).
This will give an StringIndexOutOfBoundsException if no unique
char is found:
outer:for(i=0;i<=s1.length(); i++)
replace it with
int i = 0;
outer: for(;i<s1.length(); i++)
There's no need for an inner label, and you need to start the search
from 0, not 1, so replace
inner:for(j=1;j<s1.length(); j++)
with
for(int j=0;j<s1.length(); j++)
You have your test inverted. If the characters at i and j are
the same, you need to continuue with the outer loop. Also, you need to
make sure you don't compare when i==j. So your test changes from:
if (s1.charAt(i) != s1.charAt(j))
break outer;
to
if (i!=j && s1.charAt(i) == s1.charAt(j))
continue outer;
If the inner for loop terminates, i.e. gets to the end of the
string, then the character at i is unique, so we need to break out
of the outer loop.
When you exit the outer loop you need to determine if you found a unique element, which will be the case if i < s1.length().
Putting this all together we get:
String s1= "How are How";
int i = 0;
outer: for(;i<s1.length(); i++)
{
for(int j=0;j<s1.length(); j++)
{
if (i!=j && s1.charAt(i) == s1.charAt(j))
continue outer;
}
break;
}
if(i<s1.length()) System.out.println(s1.charAt(i));
Here a link to the code (IDEOne).
This will print out every character that appears only once in the text.
final String s1 = "How are How";
outer:for(int i = 0; i < s1.length(); i++)
{
for(int j = 0; j < s1.length(); j++)
{
if(s1.charAt(i) == s1.charAt(j) && i != j)
{
continue outer;
}
}
System.out.println(s1.charAt(i);
}
Try this
String s = inputString.toLowerCase();
boolean[] characters = new boolean[26];
for(int i = 0; i < 26; i++)
characters[i] = true;
for(int i = 0; i < s.length(); i++)
{
if(characters[s.charAt(i) - 'a'])
{
System.out.println(s.charAt(i));
characters[s.charAt(i) - 'a'] = false;
}
}
Hope this helps. I have assumed that u treat lowercase and uppercase as same else u can modify accordingly
So let's say I have an array called arr with the values &&&&.&&. I want to find the number of ampersands (&) that are after the decimal point and store the value into numDecimalDigits.
int numDecimalDigits = 0;
char[] arr = new char[7]
for (int i = 0; i < str.length(); i ++)
{
for (int decimal = (arr[pos] = '.'); decimal <= arr.length; decimal ++)
{
numDecimalDigits += 1;
}
}
I'm not sure if this is the right approach. So the outside for loop runs through each index value of the array. The inner for loop starts at the decimal, and ends at the end of the array. Every time a new value is found, numDecimalDigits is added by one. However, in my code I think numDecimalDigits is returning an incorrect value.
You only need one loop:
boolean foundDot = false;
for (int i = 0; i < arr.length; i++) {
if(arr[i] == '.') {
foundDot = true;
} else if(foundDot) {
numDecimalDigits ++;
}
}
No need to use array. It would be easy like this:(Assuming str value must contains one '.' )
int numDecimalDigits = str.split("\\.")[1].length();
Or you can do by subtracting str.length()-1 with indexOf(".")
int numDecimalDigits = str.length()-1 - str.indexOf(".");
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to check to see if, entered a string, that the string is a palindrome
if it is display something positive
if not... something negative (invalid)
I am currently getting the answer invalid both times (no matter what is entered)
i'm not quite sure if there is a problem with the for loops or the boolean statement.
//ACTION FROM BUTTON PERFORMED HERE
private void ButtonActionPerformed(ActionEvent evt) {
//creating variables
String myString = textField1.getText();
int stringLength = myString.length();
char arrayOne[] = new char[stringLength];
char arrayTwo[] = new char[stringLength];
boolean palindrome = false;
//for loop to setup ARRAY ONE
for(int i = 0; i < stringLength-1; i++){
arrayOne[i] = myString.charAt(i);
}
//for loop to setup ARRAY TWO
for(int i = stringLength-1; stringLength-1 > i; i--){
arrayTwo[i] = myString.charAt(i);
}
//for loop checking if array indexes are equivalent in value (char)
for(int i = 0; i < stringLength-1; i++){
if(arrayOne[i] != arrayTwo[i]){
palindrome = false;
}
else{
palindrome = true;
}
}
//assigning text to the text boxes based on boolean palindrome
if(palindrome == true){
textField2.setText("Valid");
}
if(palindrome ==false){
textField2.setText("Invalid");
}
}
}
i think i commented it descently
Change
for(int i = stringLength-1; stringLength-1 > i; i--)
to
for(int i = 0; i < stringLength-1; i++)
and change
for(int i = stringLength-1; i-1 > 0; i--)
to
for(int i = stringLength-1; i-1 >= 0; i--)
EDIT:
That was a debugging fest!!
Here is a working code:
String myString = textField1.getText();
int stringLength = myString.length();
char arrayOne[] = new char[stringLength];
char arrayTwo[] = new char[stringLength];
boolean palindrome = true;
//for loop to setup ARRAY ONE
for(int i = 0; i <= stringLength-1; i++){
arrayOne[i] = myString.charAt(i);
}
//for loop to setup ARRAY TWO
for(int i = stringLength-1, pos = 0; i >= 0; i--, pos++){
arrayTwo[pos] = myString.charAt(i);
}
//for loop checking if array indexes are equivalent in value (char)
for(int i = 0; i <= stringLength-1; i++){
if(arrayOne[i] != arrayTwo[i]){
palindrome = false;
break;
}
}
//assigning text to the text boxes based on boolean palindrome
if(palindrome == true){
textField2.setText("Valid");
}
else{
textField2.setText("Invalid");
}
I agree with the other answers about your error, but I think a more concise solution would be
boolean isPalindrome(String myString) {
int n = myString.length;
for( int i = 0; i < n/2; i++ )
if (myString.charAt(i) != myString.charAt(n-i-1)) return false;
return true;
}
Your code would now be
private void ButtonActionPerformed(ActionEvent evt) {
String myString = textField1.getText();
textField2.setText( isPalindrome(myString) ? "Valid" : "Invalid" );
}
//for loop to setup ARRAY TWO
for(int i = stringLength-1; stringLength-1 > i; i--){
arrayTwo[i] = myString.charAt(i);
}
This falls over after the first iteration.
You need to change it to something like:
//for loop to setup ARRAY TWO
for(int i = stringLength-1; i > 0; i--){
arrayTwo[i] = myString.charAt(i);
}
This loop copies all characters except the last one which probably is not what you wanted:
//for loop to setup ARRAY ONE
for(int i = 0; i < stringLength-1; i++){
arrayOne[i] = myString.charAt(i);
}
It should probably be fixed like this:
//for loop to setup ARRAY ONE
for(int i = 0; i < stringLength; i++)
{
arrayOne [i] = myString.charAt (i);
}
Body of this loop:
//for loop to setup ARRAY TWO
for (int i = stringLength-1; stringLength-1 > i; i--)
{
arrayTwo [i] = myString.charAt (i);
}
is never executed, because initial value of i: stringLength - 1 does not satisfy loop condition: stringLength - 1 > i.
You should probably change it to be:
// For loop to setup ARRAY TWO
for (int i = 0; i < stringLength; i++)
{
arrayTwo [i] = myString.charAt (stringLength - i - 1);
}
Also, after this loop:
// for loop checking if array indexes are equivalent in value (char)
for (int i = 0; i < stringLength-1; i++)
{
if (arrayOne [i] != arrayTwo [i])
{
palindrome = false;
}
else
{
palindrome = true;
}
}
variable palindrome will contain result of last comparison only, so if all characters except the last ones were different but last characters were equal, palindrome will be true which is probably not what you wanted. Probably you should change the code like this:
palindrome = true;
for (int i = 0; i < stringLength; i++)
{
if (arrayOne [i] != arrayTwo [i])
{
palindrome = false;
}
}
Note that I also changed stringLength - 1 to stringLength, otherwise you were ignoring last characters.
The easiest way to test for a palindrome in java
String str = "Able was I ere I saw Elba"
boolean palindrome = str.equalsIgnoreCase(new StringBuilder(str).reverse().toString());
Yep, that's it.
public static void main(String[] args) {
String s = "akaq";
boolean b = false;
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
if (s.charAt(i) == s.charAt(j)) {
b = true;
continue;
} else {
b = false;
break;
}
}
if (b)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
Try something like this instead of 2-3 for loops.
Change the first for loop from stringLength-1 to just stringLength because you are using < and not <=
Change the second for loop to
if(int i = stringLength-1; i>=0; i--)
Also, set palindrome to true by default and remove the
else{
palindrome = true;
}
part because now if the first and last characters of the loop are the same, but not the middle, it will return true.
EDIT: Also the third for loop should be stringLength and not stringLength-1 because you are using < and not <=
There's no need to copy everything into arrays. String is basically an array itself. You can access the individual characters with charAt().
Also there is no need to loop the entire length of the String since equality is associative.
So simply use :
public boolean isPalindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) { // only until halfway
if (s.charAt(i) != s.charAt(s.length() - i - 1)) { // accessing characters of String directly
return false;
}
}
return true;
}
One last remark : if the String's length is odd, you don't need to check the middle chracter. So in the code above the diision by
I have a string
String word = "FrenciusLeonardusNaibaho";
while I'm trying to make matrix like this:
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 1; i < 16; i++) {
for (int j = 1; j < 16; j++) {
matriks[i][j] = word.charAt(k);
k++;
}
}
I got this error
String index out of range: 24
How can I achieve this?
Thanks..
You are overflowing beyond the end of word at word.charAt(k);. Basically you dont have enough alphabets to fill your matrix.
You can do something like this
if(k >= word.length())
break;
Below the inner loop. Or you can init the element to some default value with this condition.
Additionally as others have mentioned, i,j should start at 0, unless you have a good reason to start at 1.
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
matriks[i][j] = word.charAt(k%word.length());
k++;
}
}
So it can go from start to end,then restart.
try adding
if(k >= word.length())
k = 0;
to your inner for loop, this will continue filling the array from the beginning of the word.
'Out of bounds' or 'out of range' occures when you try to read or write in an array, list, string or whatever with a range beyond it's boundary. You can't read a a character at index 8 when your string contains only 7 character. It's not your string's RAM and it would cause RAM corruption like it is happening sometimes in C-arrays.
When you set up your array and your for-loop try to check if you are still in bounds of your string with a size or length function of your container. In special case of string it is length.
I think you are trying to split a list of names stored in a string. In such a case it is easier to create a dynamic container, something like list (http://www.easywayserver.com/blog/java-list-example/).
Here I have a little example. For those purposes I prefer a while-loop. In cases I know the length of a list at least at runtime without interpreting data a for-loop is a good choice, but not in this:
String names = "Foo Bar";
List<String> seperatedNames = new List<String>();
String name = "";
int i = 0;
while (i < names.length()) {
if (names.charAt(i) == ' ') { // you can check for upper case char too
seperatedNames.add(name); // add name to list
name = ""; // clear name-buffer
i++; // increment i, else it would produce an infinite loop
}
name += names.charAt(i++); // add current char to name-buffer and increment current char
}
I hope I could help a bit.
of course, you will get this error surely because the character in your word are only 24 character.
to avoid this your need to check the length of your word and need to break the all looping.
Try this code.
char matriks[][] = new char[16][16];
int k = 0;
int lenght = word.length();
outerloop:
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
matriks[i][j] = word.charAt(k);
k++;
if(k >= lenght){
break outerloop;
}
}
}
You are filling 16x16 array and iterating the loop 16x16 times but your word size is less than 16x16. So put a check when k becomes equal to the word length then terminate the loop.Change your code like this.
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 1; i < 16; i++) {
for (int j = 1; j < 16; j++) {
if(k >=word.length)
break;
matriks[i][j] = word.charAt(k);
k++;
}
}