Integer variable does not update when if condition is true - java

public class test
{
static Scanner store = new Scanner(System.in);
public static void main(String[] args)
{
String str1 = args[0];
String str2 = args[1];
System.out.printf("%nThere are %d dissimilar characters in the two strings.%n", CountNotSim(str1, str2));
}
public static int CountNotSim(String str1, String str2)
{
String s1 = str1.toLowerCase();
String s2 = str2.toLowerCase();
char[] a1 = new char[s1.length()];
char[] a2 = new char[s2.length()];
for (int g = 0; g < s1.length(); g++)
a1[g] = s1.charAt(g);
for (int h = 0; h < s2.length(); h++)
a2[h] = s2.charAt(h);
int check = 0, stored;
char[] array = new char[26];
int ctr = s1.length() + s2.length();
for (int i = 0; i < a1.length; i++)
{
check = 0;
stored = 0;
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j])
{
check++;
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ')
if (stored == 0)
array[k] = a1[i];
if (a1[i] == array[k])
{
stored = 1;
break;
}
}
System.out.print(stored + "/ ");
}
}
if (check > 0)
{
if (stored == 0)
ctr -= (check + 1);
else if (stored == 1)
ctr--;
}
System.out.print(ctr + " "); //checker
}
System.out.println();
return ctr;
}
}
The program checks for dissimilar letters in two strings inputted from the command line. Variable "stored" is supposed to change to 1 whenever there's a match to avoid extra deductions to variable "ctr". However, for some reason, not only does "stored's" value not change, the array "array" also doesn't update its elements whenever there's a match. I'm at a loss on how to fix it--nothing looks incorrect.

You wrote this:
char[] array = new char[26];
...
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ') {
...
But you simply set the length of array not its content.
As a char array, it's filled with the default char value, which is not the character space but the value 0 (not the character 0, but the numeric value 0)
So array[k] == ' ' will never be true.
Try with that:
for (int k = 0; k < 26; k++)
{
if (array[k] == 0) {
...

Related

How to check if a char is upper/lowercase?

The following code is supposed to convert letters to numbers and give the sum, but ignore any letters that are uppercase.
Example:
The input abcde should return 15. The input abCde should return 12.
Any help is appreciated.
static int strScore(String str[], String s, int n) {
int score = 0, index=0;
for (int i = 0; i < n; i++) {
if (str[i] == s) {
for (int j = 0; j < s.length(); j++)
score += s.charAt(j) - 'a' + 1;
index = i + 1;
break;
}
}
score = score * index;
return score;
}
public static void main(String[] args) {
String str[] = { "abcde" };
String s = "abcde";
int n = str.length;
int score = strScore(str, s, n);
System.out.println( score);
}
Use Character.isLowerCase(...).
So this is what your strScore method should look like:
static int strScore(String str[], String s, int n) {
int score = 0, index = 0;
for (int i = 0; i < n; i++) {
if (str[i].equals(s)) {
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
if(Character.isLowerCase(c)) // <-- This is the important part
score += c - 'a' + 1;
}
index = i + 1;
break;
}
}
score = score * index;
return score;
}
As pointed out in the comments, there is no need for the str and therfore neither the n parameter. This is a better version:
static int strScore(String s) {
int score = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(Character.isLowerCase(c))
score += c - 'a' + 1;
}
return score;
}
There are two things to address:
You have used == to compare strings. You need to use .equals
You need to put a check like if(s.charAt(j)>= 'a' && s.charAt(j)<'z')
for (int i = 0; i < n; i++) {
if (str[i].equals(s)) {
for (int j = 0; j < s.length(); j++)
if(s.charAt(j)>= 'a' && s.charAt(j)<'z') {
score += s.charAt(j) - 'a' + 1;
You can avoid passing String str[] = { "abcde" }; which has one element which equals s
to The method. You can also avoid passing n which is an simply str.length():
static int strScore(String s) {
int score = 0, index = 0;
for (int i = 0; i < s.length(); i++) {
for (char c : s.toCharArray()) {
if(c >= 'a' && c <'z') { //alternatively if(Character.isLowerCase(c))
score += c - 'a' + 1;
}
}
index = i + 1;
break;
}
score = score * index;
return score;
}

combine two string word by word in java

I'm trying to combine two sentences word by word in java without using any special string methods except charAt and length.
It's like
String s1="hello world";
String s2="programmers are greeting"
I want to combine that two string get one word from s1 then get one word from s2 and keep until there is no word left in s1 and s2 in s3.
String s3="hello programmers world are greeting"
Here's my method but when I run it doesn't return anything. I couldn't find the problem:
void combine(String str1, String str2) {
int i,
j,
sl1,
sl2,
s,
test;
sl1 = str1.length();
sl2 = str2.length();
test = sl1 + sl2;
char[] ar1 = new char[sl1];
char[] ar2 = new char[sl2];
for (i = 0; i < ar1.length; i++)
{
ar1[i] = str1.charAt(i);
}
for (j = 0; j < ar2.length; j++)
{
ar2[j] = str2.charAt(j);
}
char[] array = new char[test];
s = array.length;
i = 0;
j = 0;
while (s <= i + j) {
while (ar1[i] != ' ')
{
if (i == sl1) break;
array[i + j] = ar1[i];
i = i + 1;
}
while (ar2[j] != ' ')
{
if (j == sl2) break;
array[j + i] = ar2[j];
j = j + 1;
}
}
for (i = 0; i < s; i++)
{
System.out.print(array[i]);
}
}
The method combine is void which should become int otherwise you should output the answer using a System.out.println();

Text justification not formatting correctly

I'm trying to make a program that will format text entered so that each line is set to a specific Length and cant go over e.g. 20 and then have the characters format accordingly on each line and have "." pad the gaps to make up the set length.
This is the output I've got so far:
This.is..an..example
of..text..that..will
have..straight..left
and.right....margins
after formatting ...
For some reason the "." are not appearing between after and formatting as well as after the "g" a dot is missing a space is taking its place instead. It seems to always happen's on the last line.
This is what the output should look like:
This.is..an..example
of..text..that..will
have..straight..left
and.right....margins
after.formatting....
Code:
import java.util.*;
public class FormattedPadding {
public static ArrayList<String> fullJustify(ArrayList<String> a, int b) {
ArrayList<String> result = new ArrayList<String>();
if(a == null || a.size() == 0)
return result;
int i = 0;
int currentLength = 0;
String temp = "";
for(i = 0; i < a.size(); i++){
currentLength += a.get(i).length() + 1;
if(currentLength > b + 1) {
result.add(temp);
temp = "";
currentLength = 0;
i--;
//System.out.println("Intermediate result: " + result);
}
else
temp += a.get(i) + " ";
}
if(!temp.equals(""))
result.add(temp);
for(i = 0; i < result.size() - 1; i++){
temp = result.get(i);
String[] tempArray = temp.split(" ");
int totalLength = 0;
for(int j =0; j < tempArray.length; j++)
totalLength += tempArray[j].length();
int[] spaceCount = getSpaceCount(b-totalLength, tempArray.length);
for(int l =0; l < spaceCount.length; l++)
System.out.print(spaceCount[l] + " " );
System.out.println();
temp = "";
for(int j = 0; j < tempArray.length; j++){
temp += tempArray[j];
for(int k = 0; k < spaceCount[j]; k++)
temp += ".";
}
result.set(i, temp);
}
temp = result.get(result.size() - 1);
if(temp.length() < b){
while(temp.length() < b)
temp += ".";
}
else if(temp.length() > b)
temp = temp.substring(0, b);
result.set(result.size() - 1, temp);
return result;
}
public static int[] getSpaceCount(int freeSpace, int numOfStrings) {
int size = numOfStrings - 1;
int[] ret = new int[size + 1];
if(size == 0){
ret[0] = freeSpace;
}
else {
for(int i =0; i < ret.length; i++) {
if(size != 0){
ret[i] = freeSpace % size == 0 ? freeSpace/size : freeSpace/(size + 1);
}
freeSpace = freeSpace - ret[i];
size--;
}
}
return ret;
}
public static void main(String[] args) {
//ArrayList<String> a = new ArrayList<String>();
System.out.println("#Enter ");
String usrInput = BIO.getString();
String[] items = usrInput.split("\\s+"); // Split where whitespace is encounterd using the RegEx
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(items));
// ^Split input into ArrayList
int b = 20; // Line length
ArrayList<String> result = fullJustify(newList, b);
for(int i =0; i < result.size(); i++) {
System.out.println(result.get(i));
}
System.out.println(result);
}
}
First of all, I think your code will go to infinite loop if any of the words has length more than "b"
About the issue, you create different logic for the last line
temp = result.get(result.size() - 1);
if(temp.length() < b){
while(temp.length() < b)
temp += ".";
}
else if(temp.length() > b)
temp = temp.substring(0, b);
result.set(result.size() - 1, temp);
You can remote those part, and change the loop from result.size()-1 to result.size(), so it will cover all lines:
for(i = 0; i < result.size(); i++){

How to delete duplicate characters in a string?

I have a method that supposed to delete all the dups from string passed inside it. I can print the dups, how can I delete them in the original string ? Say, 'miami' will need to be 'mia' when it will return. Thanks.
public static String removeDups( String str1){
char[] str = str1.toCharArray();
if (str == null) return null;
int len = str.length;
if (len < 2) return new String(str);
char[] newStr = new char[len+1];
int copyLength = 0;
for ( int i = 1 ; i < len; i++){
for( int j=0; j< i; j++){
if ( str[i] == str[j]){
System.out.println(" str[i] == str[j] = "+ str[i] + " , "+str[j]);
break;
}
}
}
return new String(str);
}
I found this to be easier using a StringBuilder rather than a String
EDIT
This can also be done with a combination of StringBuilder and regex
Regex Pattern breakdown:
(.) --> matches any character and puts in group 1.
?= --> this is called a positive lookahead.
?=.*\\1 --> positive lookahead of zero or more characters for the first group
Code Sample:
public static void main(String[] args) throws Exception {
System.out.println(removeDuplicates("miamimiamimiami"));
System.out.println(removeDuplicatesRegex("miamimiamimiami"));
}
public static String removeDuplicates(String input){
StringBuilder data = new StringBuilder(input);
for (int i = 0; i < data.length(); i++) {
String character = String.valueOf(data.charAt(i));
int dupIndex = data.indexOf(character, i + 1);
while (dupIndex != -1) {
data.deleteCharAt(dupIndex);
dupIndex = data.indexOf(character, i + 1);
}
}
return data.toString();
}
public static String removeDuplicatesRegex(String input) {
return new StringBuilder(
new StringBuilder(input)
.reverse()
.toString()
.replaceAll("(.)(?=.*\\1)", ""))
.reverse().toString();
}
Results:
mia
mia
Here's another option:
StringBuffer buf = new StringBuffer( originalString);
int len = str.length();
for (int i = 0; i < len; i++) {
char c = buf.charAt( i );
for (int j = len - 1; j > i; j--) {
if ( buf.charAt( j ) == c ) {
buf.deleteCharAt( j );
len--;
}
}
}
Remove all duplicate chars in a String:
public static String removeDuplicates(String str1) {
if (str1 == null)
return null;
char[] str = str1.toCharArray();
int len = str.length;
if (len < 2)
return str1;
char temp = str[0];
for (int i = 1; i < len; i++) {
if (temp != 0)
for (int j = i; j < len; j++)
if (temp == str[j])
str[j] = 0;
temp = str[i];
}
int i = 0;
char[] str2 = new char[len];
for (char c : str)
if (c != 0)
str2[i++] = c;
return (new String(str2)).trim();
}
You can also use Arraylist to store the unique characters:
public static String removeDups( String str1){
ArrayList<Character> set=new ArrayList<Character>();
char[] str=str1.toCharArray();
for(int i=0;i<str.length;i++)
{
if(!set.contains(str[i])){
set.add(str[i]);
}
}
for(char e:set)
{
System.out.print(e);
}
}
Your loop seems to be a bit strange.
char[] str = str1.toCharArray();
int len = str.length;
if (str == null || len < 2) return null;
char[] newStr = new char[len+1];
int newStrLength = 0;
for( int i = 1; i < len; i++ ){ //Iterate complete string
for( int j=0; j < i; j++ ){ //Iterate the already-finished part
if( str[i] == str[j] )
break;
}
newStr[newStrLength++] = str[i];
}
}
newStr[newStrLength] = 0;
In this example I make a completly new string and don't alter the original one. It makes the code clearer to read.
Alternatively you could take a look at this question which has some more efficient answers.

Exception in thread main ArrayIndexOutOfBoundsException

Can someone maybe help me with the following error. Exception in thread main java.lang.arrayindexoutofboundsexception : 3 at RowTrans.encrypt(Rowtrans.java:33)
at RowTrans.main(Rowtrans.java :7)
In my program I want to get a text. Put it in a matrix with 5 columns and determine the rows according to the length of the text. Then i want to change the column and row position so that the row gets the columns position and the column the row. And when a row does not contain 5 values I want to add the character Z in the empty spaces. Can anyone assist me on this error please.
Here is my code
import java.util.Scanner;
public class ColTrans {
public static void main(String[] args)
{
String ori = "This is my horse";
String enc = encrypt(ori);
System.out.println(enc);
// String dec = decrypt(enc);
// System.out.println(dec);
}
static String encrypt(String text)
{
String result = "";
text = text.toUpperCase();
int length = text.length();
int rows = length / 5;
char[][] b = new char[rows][5];
char[][] c = new char[5][rows];
char[] d = new char[length];
if ((length % 5) != 0)
rows = rows + 1;
int k = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < 5; j++)
{
if (k > length)
b[i][j] = 'Z';
else
{
d[k] = text.charAt(k);
b[i][j] = d[k];
}
k++;
}
for (int i = 0; i < 5; i++)
for (int j = 0; j < rows; j++)
{
c[i][j] = b[j][i];
result = result + c[i][j];
}
return result;
}
}
Here is the cause:
You are increamenting row variable by one, once you have defined the array.
Move following line before line char [][] b =new char[rows][5];
if ((length % 5) != 0)
rows = rows + 1;
There are 2 issues in your code. First move the mod part before the matrix instantiation :
if ((length % 5) != 0)
rows = rows + 1;
char [][] b =new char[rows][5];
[...]
Then change if ( k > length ) to if ( k >= length )
just change your code as following:
if ((length % 5) != 0)
rows = rows + 1;
char[][] b = new char[rows][5];
char[][] c = new char[5][rows];
char[] d = new char[length];
According to your description:
text = text.toUpperCase();
char[] b = text.toCharArray();
char[][] c = new char[b.length][5];
int bLen = 0;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < 5; j++) {
if(bLen < b.length)
c[i][j] = b[bLen++];
else
c[i][j] = 'Z';
}
}
//change the column and row position
char[][]d = new char[c[0].length][c.length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
d[i][j] = c[j][i];
}
}
Output: TI EZZZZZZZZZZZZHSHZZZZZZZZZZZZZI OZZZZZZZZZZZZZSMRZZZZZZZZZZZZZ YSZZZZZZZZZZZZZ

Categories