How to check if a char is upper/lowercase? - java

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;
}

Related

Using Bubble Sort to Alphabetically Sort Array of Names in Java

I've been trying to tackle this bug for a while, but I can't get around to it. The purpose of the program below is to use bubble sort to alphabetically order an array of names. For example, if the names are ["Bob Joe", "Bob Frank", and "Bob Johnson"], the correctly sorted array would be ["Bob Frank", "Bob Joe", "Bob Johnson"].
The main challenge I am having is comparing any 2 strings past name.charAt(0). If I only compare the characters of any 2 strings at 1 specific index point, my code works. However, if I try to make the comparison move past index 0 if index 0 of both strings are equal to each other, my program no longer works.
The code is outlined below
public static void sortAlpha (String names[])
{
for (int i = 0 ; i < names.length - 1 ; i++)
{
for (int a = 0 ; a < names.length - 1 - i ; a++)
{
int length1 = names [a].length ();
int length2 = names [a + 1].length ();
int min = 1;
if (length1 > length2)
{
min = length2;
}
else
{
min = length1;
}
for (int b = 0 ; b < min ; b++)
{
if ((int) names [a].toLowerCase ().charAt (b) > (int) names [a + 1].toLowerCase ().charAt (b))
{
String tempName = names [a];
// sort:
names [a] = names [a + 1];
names [a + 1] = tempName;
break;
}
}
}
}
}
If I simply default the min value to 1, the code runs and does its intended job. However, if the min value stays dynamic, the program does not work. I'm trying to discern why this is so and what the fix is. Any help would be appreciated!
Check this out.
public static void sortAlpha(String names[]) {
for (int i = 0; i < names.length - 1; i++) {
for (int a = 0; a < names.length - 1 - i; a++) {
int lengthLeft = names[a].length();
int lengthRight = names[a + 1].length();
int minLength = lengthLeft > lengthRight ? lengthRight : lengthLeft;
for (int b = 0; b < minLength; b++) {
int letterLeft = (int) names[a].toLowerCase().charAt(b);
int letterRight = (int) names[a + 1].toLowerCase().charAt(b);
if (letterLeft > letterRight) {
String tempName = names[a];
// sort:
names[a] = names[a + 1];
names[a + 1] = tempName;
break;
} else if (letterLeft == letterRight) {
// if the letters are the same go for the next letters
continue;
} else {
// if it's already in the right position - stop.
break;
}
}
}
}
}
Use this
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
You can simply use compareTo() and a temp variable to compare and store
Scanner sc = new Scanner(System.in);
String n[]= new String[5];
System.out.println("Enter the String");
for(int k = 0;k<5;k++) {
n[k] = sc.nextLine();
}
String temp;
System.out.println("sorted order:");
for (int j = 0; j < n.length; j++) {
for (int i = j + 1; i < n.length; i++) {
if (n[i].compareTo(n[j]) < 0) {
temp = n[j];
n[j] = n[i];
n[i] = temp;
}
}
System.out.println(n[j]);

Integer variable does not update when if condition is true

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) {
...

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++){

printing the total value only one time without iteration

I want to print the statement System.out.println(sb.append(ss));
Only the last time I tried to take it out of the for loop but the result is wrong.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
System.out.println(sb.append(ss));
}
return sb.toString();
}
Put System.out.println(sb.append(ss)); out of the loop:
public static String constatment vertBinaryStringToString(String string){
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss=null;
//for each character
for (int j = 0; j < chars.length; j+=8) {
int idx = 0;
int sum =0;
//for each bit in reverse
for (int i = 7; i>= 0; i--) {
if (chars[i+j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div=sum/4;
System.out.println(div);
System.out.println((char)div);
int rem=sum%4;
System.out.println(rem);
ss=(char)div+""+rem;
}
System.out.println(sb.append(ss));
return sb.toString();
}
Because System.out.println(sb.append(ss)); contains a call to sb.append(ss)); taking the statement out of the for loop will have a different result than the one expected.
You should keep sb.append(ss); inside the loop and add System.out.println(sb) outside the loop.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
sb.append(ss);
}
System.out.println(sb);
return sb.toString();
}

Find longest repeating substring with length between x and y

Given a string : "blablafblafbla" and 2 limits : x=3, y=5
I want to find the longest repeating substring that has the length between x and y.If there are many, the first one
In my example that would be "blaf"
Several questions:
1. is it easier to use regex?
2.I know how to find the longest substring but where do i have to put the conditions for it to be between x and y?
public static String longestDuplicate(String text)
{
String longest = "";
for (int i = 0; i < text.length() - 2 * longest.length() * 2; i++)
{
OUTER: for (int j = longest.length() + 1; j * 2 < text.length() - i; j++)
{
String find = text.substring(i, i + j);
for (int k = i + j; k <= text.length() - j; k++)
{
if (text.substring(k, k + j).equals(find))
{
longest = find;
continue OUTER;
}
}
break;
}
}
return longest;
}
The code you provide is an extremely inefficient way to solve the problem you have. I would implement the solution using Rabin-Karp or some other rolling hash algorithm and this will enable you to solve your problem with complexity O((y-x) * L).
You can't use regular expressions here- they are meant to solve copletely different tasks.
As for your question on how to use your solution to find longest substring with length between x and y, simply modify the loop over j to only consider values that are in the interval [x, y]. Here is how you can do that.
for (int j = Math.max(longest.length() + 1, x) ; j * 2 < text.length() - i && j < y; j++)
EDIT: to find the longest substring, reverse the for cycle:
for (int j = Math.min((text.length() - i -1)/2, y) ; j > longest.length() && j >=x; j--)
public static int commonPrefix (String string, int x, int y)
{
int l = string.length ();
int n = 0;
int oy = y;
while (x < oy && y < l && string.charAt (x) == string.charAt (y))
{
n++; x++; y++;
}
return n;
}
public static String longestRepeatingSubstring (
String string, int minLength, int maxLength)
{
String found = null;
int l = string.length ();
int fl = minLength;
for (int x = 0; x < l - fl * 2; x++)
for (int y = x + 1; y < l - fl; y++)
{
int n = commonPrefix(string, x, y);
if (n >= maxLength)
return string.substring(x, x + maxLength);
if (n > fl)
{
found = string.substring (x, x + n);
fl = n;
}
}
return found;
}
public static void main(String[] args) {
System.out.println (longestRepeatingSubstring ("blablafblafblafblaf", 3, 5));
}
Here is a clunky implementation with regex:
//import java.util.regex.*;
public static String longestRepeatingSubstring (String string, int min, int max)
{
for (int i=max; i>=min; i--){
for (int j=0; j<string.length()-i+1; j++){
String substr = string.substring(j,j+i);
Pattern pattern = Pattern.compile(substr);
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) count++;
if (count > 1) return substr;
}
}
return null;
}
public static void main(String[] args) {
System.out.println (longestRepeatingSubstring ("blablafblafbla", 3, 5));
}
public static int getCount(String string , String subString){
int count = 0;
int fromIndex = 0;
do{
if(string.indexOf(subString, fromIndex) != -1){
count++;
fromIndex = string.indexOf(subString, fromIndex);
}
}while(fromIndex == string.length()-1);
return count;
}
public static String longestRepeatingSubstring (int min,int max , String string){
Vector substrs = new Vector();
Vector substrs_length = new Vector();
for (int i=min; i<=max; i++){
for (int j=0; j<string.length()-i+1; j++){
String substr=string.substring(j, i+j);
System.out.println(substr);
if (substrs.indexOf(substr) == -1){
int count =getCount(string, substr);
if (count != 0) {
substrs.addElement(substr);
substrs_length.addElement(count);
}
}
}
}
int maxLength = 0;
int index = -1;
for(int i = 0 ; i < substrs_length.size() ; i++){
int length = (int) substrs_length.elementAt(i);
if(length > maxLength){
maxLength = length;
index = i;
}
}
return (String) substrs.elementAt(index);
}
public static void main(String [] arg){
System.out.print(longestRepeatingSubstring(3, 5, "blablafblafbla"));
}

Categories