Text justification not formatting correctly - java

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

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]);

convert java code in c#

I am using this code for sentence similarties the code is available on java i want to use this in c#.
public static int getWordChanges(String s1, String s2) {
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
s2 = s2.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.split(" ").length; i++) {
boolean exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.split(" ").length; j++) {
//Is the word misspelled?
if ((getLevenshteinDistance(s1.split(" ")[i], s2.split(" ")[j]) * 100 / s1.split(" ")[i].length()) < similarityThreshold) {
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists) {
wordChanges++;
}
}
return wordChanges;
}
This is Java code i want to execute this code in c#
After convert the code in c#
public int getWordChanges(String s1, String s2)
{
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
s2 = s2.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.Split(' ').Length; i++)
{
bool exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.Split(' ').Length; j++)
{
//Is the word misspelled?
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
{
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists)
{
wordChanges++;
}
}
return wordChanges;
}
}
}
There are error at this line
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
on length error will show how i resolve this one
Add this function to your project
public static int getLevenshteinDistance(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
Source
And change .Length() to .Length Because String.Length is a property and not a method

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

access array elements in java outside the loop

I am developing a simple program to print seat numbers, where the row are numbered from 1-5 and columns from a-e. the code i am using is as follows
public class JavaApplication5 {
public static void main(String[] args) {
int j =1,k;
int i;
char c;
String[] arr = new String[25];
for( i = 0;i < arr.length;i++)
{
while(j <= 5)
{
for(k = 97;k < 102; k++)
{
c = ((char)k);
arr[i] = j + "" + c;
System.out.println(arr[i]);
}
j++;
}
}
}
}
this displays desired result. but when I print an element outside the for loop I get the result as null like below
public static void main(String[] args) {
int j =1,k;
int i;
char c;
String[] arr = new String[25];
for( i = 0;i < arr.length;i++)
{
while(j <= 5)
{
for(k = 97;k < 102; k++)
{
c = ((char)k);
arr[i] = j + "" + c;
}
j++;
}
}
System.out.println(arr[6]);
}
how to solve this?
this will leave all elements as null
String[] arr = new String[25];
this will iterate until j == 5 so only until arr[5]
while(j <= 5) {
j++;
}
Therefore arr[6] is still null
Change
arr[j] = j + "" + c;
instead of
arr[i] = j + "" + c;
Now it works.
public static void main(String[] args) {
int j = 1, k;
int i;
char c;
String[] arr = new String[25];
for (i = 0; i < arr.length; i++) {
while (j <= 5) {
for (k = 97; k < 102; k++) {
c = ((char) k);
arr[j] = j + "" + c;
}
j++;
}
}
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
System.out.println(arr[4]);
System.out.println(arr[5]);
System.out.println(arr[6]); // null because your check j <= 5 in while loop
}
You can access the array elements normally outside of the loop. In your example, arr[6] is just null. The fault is not in the way you access it. (Although i cant see the bug yet ;))
The problem in your code is that you simply write 5 time on index 1, then 5 time on index 2 and so on.
So you never wrote on index 6.
Your code should be changed to code below:
String[] arr = new String[25];
int i = 0;
int j = 1;
while (j <= 5) {
for (k = 97; k < 102; k++) {
c = ((char) k);
arr[i++] = j + "" + c;
}
j++;
}
System.out.println(arr[6]);
Because your loops run 5*5 times, then your i index will never pass arr array length.
But you better control it like this to prevent your code from being error prone:
if(i < arr.length) {
arr[i++] = j + "" + c;
} else {
break;
}

null pointer exception sorting merged array list

I have been trying to figure out how to properly print the return of my method.
When the program prints the return of my method, I am giving a nullPointerException error on line 45(the line where i am trying to print the method).
*I did try to make the return to the method static so it is accessible.
How do I initialize the "answer" variable so that i can print it outside of my method?
Thank you in advance
import javax.swing.JOptionPane;
public class ListSortMerge {
static int[]answer;
public static void main(String[] args) {
int v1 = 0, v2 = 0;
for(int c = 0; c <= 1; c++) {
String values = JOptionPane.showInputDialog("How many values would you like to store in list "+(c+1)+"?");
if (c==0) {
v1 = Integer.parseInt(values);
}
else{
v2 = Integer.parseInt(values);
}
}
int[] numbers1 = new int[v1];
int[] numbers2 = new int[v2];
merge(numbers1,numbers2);
int i;
System.out.println("\nList 1 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v1); i++) {
System.out.println(numbers1[i]);
}
System.out.println("\nList 2 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v2); i++) {
System.out.println(numbers2[i]);
}
System.out.println("\nList after the sort");
System.out.println("--------------------");
for(i = 0; i < (v1+v2); i++) {
System.out.println(answer[i]);
}
}
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
for(int c = 0; c < (a.length); c++)
{
String aVal1 = JOptionPane.showInputDialog("Input list 1 value " +(c+1));
a[c] = Integer.parseInt(aVal1);
}
for ( int c = 0; c < (b.length); c++){
String aVal2 = JOptionPane.showInputDialog("Input list 2 value " +(c + 1));
b[c] = Integer.parseInt(aVal2);
}
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
answer[k++] = a[i++];
else
answer[k++] = b[j++];
}
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
}
You have two different answer variables: one is a local variable in the merge function and another is a static field in the class. You never initialize the second one.

Categories