Format text in php [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I have this code in java and i want to convert it into php. With this function i want to format some data and write them in a txt file.
Is there any classes as the text class in java to handle it?
here is the code :
public static void printAll(int n1, int n2, double[][] m,
String[] labs, double scaling, JTextArea outext)
{
// Some definitions for handling output formating
NumberFormat myFormat = NumberFormat.getNumberInstance();
FieldPosition fp = new FieldPosition(NumberFormat.INTEGER_FIELD);
// Following suppresses e.g. comma in 1,000 = 1000 for English locale.
myFormat.setGroupingUsed(false);
int w;
double maxval;
maxval = SMALL;
for (int i =0; i < n1; i++) {
for (int j =0; j < n2; j++) {
// Scale up values by 'scaling' factor
if (m[i][j] > maxval) maxval = m[i][j];
}
}
String temp = myFormat.format(maxval*scaling,
new StringBuffer(), fp).toString();
// Output display field width of each number: extra 2 to
// account for possible minus sign, and 1 space.
w = fp.getEndIndex() - fp.getBeginIndex() + 2;
// System.out.println(" Output field width = " + w);
// In the next few lines we say how we want numbers to appear.
// max integer digits = max no. of digits before dec. point
// max fraction digits = max no. of digits following dec. point
// min fraction digits = min no. of digits following dec. point
myFormat.setMaximumIntegerDigits(w);
// We will set min and max nos. of digits following dec. point to 0
myFormat.setMaximumFractionDigits(0);
myFormat.setMinimumFractionDigits(0);
for (int i=0; i<n1; i++)
{
// First handle cols for labels, QLT, PDS, INR:
String myString = labs[i];
myString = getSpaces(4 - myString.length()) + myString;
outext.append("|" + myString + "|");
for (int j = 0; j < 3; j++) {
String valString = myFormat.format(
scaling*m[i][j], new StringBuffer(), fp).toString();
// With a max field width of w, we pack spaces before val.
valString = getSpaces(4 - fp.getEndIndex()) + valString;
outext.append(valString);
}
// Print each row, elements separated by spaces
for (int j = 3; j < n2; j++)
{
// Scaling is in thousandths; but note if +ve only.
w = 4; // All cntr and corr are positive.
if (j/3 == (double)j/3.0) { // Here, will handle proj.
outext.append("|");
w = 5; // Allow for -ve vals.
}
String valString = myFormat.format(
scaling*m[i][j], new StringBuffer(), fp).toString();
// With max field width of w, we pack spaces before val.
valString = getSpaces(w - fp.getEndIndex()) + valString;
outext.append(valString);
}
outext.append("|");
// Start a new line at the end of a row
outext.append("\n");
}
}

Yes, you can do this function using PHP. There is no built-in function that does this, so you must code it yourself
I suggest you start breaking the function down into pieces and try using some PHP code, then if you get stuck search for that specific question before you post.

Related

How to print out the odd index elements from a two dimensional array (java)? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
For any given dimension (here I just set it to 8 to make it easy) I want to print out the letters with odd indexes. So I am trying to get an output like: B D F H... and other letters depending on the dimension). I put a while loop to make the row 0 since I only want to print out the the odd letters on the first row and then inside the while loop I added a for loop to print out the columns (letters) with odd n. However I am getting a not an error:
error: not a statement
for (n = 1; n<dimension; n +2){
^
I am also unsure of where to put the loops to print out the odd letters.
This is my code so far:
public static void main(String[] args) {
int dimension = 8; // normally any given dimension (int dimension = Integer.parseInt(args[0]))
int n = dimension - 1;
int m = dimension -1;
char [] alphabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int [] nums = new int [dimension];
for (int i = 0; i < dimension; i ++) {
nums [i] = i + 1;
}
int [] [] position = new int [dimension] [dimension];
for (int row = 0; row < dimension; row ++) {
for (int col = 0; col < dimension; col ++) {
position [row] [col] = alphabet[col] + nums[row];
}
}
char p = (char)(position[m][n] - nums[n]);
while (m == 0) {
for (n = 1; n<dimension; n +2){
System.out.println(p); //odd letters on the first row
}
}
}
}
Edit: the program is compiling but the loop is not working so I am not getting any output. How can I fix it?
This is a simple syntax error.
for (n = 1; n<dimension; n +2){
Should be:
for (n = 1; n<dimension; n += 2){
The final part of the for statement is an operation that can be used to change the iterator (or do other operations). If you consider the following line of code:
n +2;
This is not a valid statement by itself. However, the following statement is valid:
n += 2;

How to rotate 2-D Array in Java

[SOLVED]
The title of this question is vague but hopefully this will clear things up.
Basically, what I am looking for is a solution to rotating this set of data. This data is set up in a specific way.
Here is an example of how the input and output would look like:
Input:
3
987
654
321
Output:
123
456
789
The '3' represents the number of columns and rows that will be used. If you input the number '4', you will be allowed to input 4 sets of 4 integers.
Input:
4
4567
3456
2345
1234
Output:
1234
2345
3456
4567
The goal is to find a way to rotate the data only if needed. You have to make sure the smallest corner number is at the top left. For example, for the code above, you rotated it so 1 is at the top left.
The problem I have is that I don't know how to rotate the data. I am only able to rotate the corners but not the sides. This is what my code does so far:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
I just do not know how to compare those characters and in the end rotate the data.
Any help would be appreciated! Any questions will be answered.
A detailed description of the problem is here(problem J4).
This is just a challenge I assigned myself for practice for next year's contest, so giving me the answer won't "spoil" the question, but actually help me learn.
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = kb.nextInt();
int maxSqrt = (max * max);
int num[] = new int[max];
String num_string[] = new String[max];
char num_char[] = new char[maxSqrt];
int counter = 0;
int counter_char = 0;
for (counter = 0; counter < max; counter++) {
num[counter] = kb.nextInt();
}
for (counter = 0; counter < max; counter++) {
num_string[counter] = Integer.toString(num[counter]);
}
int varPos = 0, rowPos = 0, charPos = 0, i = 0;
for (counter = 0; counter < maxSqrt; counter++) {
num_char[varPos] = num_string[rowPos].charAt(charPos);
i++;
if (i == max) {
rowPos++;
i = 0;
}
varPos++;
if (charPos == (max - 1)) {
charPos = 0;
} else {
charPos++;
}
}
//
for(int a = 0 ; a < max ; a++){
for(int b = 0 ; b < max ; b++)
{
num_char[counter_char] = num_string[a].charAt(b);
counter_char++;
}
}
//here is where the code should rotate the data
}
}
This is a standard 90 degree clockwise rotation for a 2D array.
I have provided the solution below, but first a few comments.
You said that you're doing this:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
Firstly youre essentially turning a int matrix into a character matrix. I do not think you need to do this, since even if you do want to compare values, you can use the ints provided.
Secondly, there is no need to compare any 2 data elements in the matrix, since the rotation does not depend on any value.
Here is an adapted solution for java, originally written in C# by Nick Berardi on this question
private int[][] rotateClockWise(int[][] matrix) {
int size = matrix.length;
int[][] ret = new int[size][size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
ret[i][j] = matrix[size - j - 1][i]; //***
return ret;
}
If you wanted to do a counterCW rotation, replace the starred line with
ret[i][j] = matrix[j][size - i - 1]

Making a binary to decimal converter [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
EDIT: Since there are claims that this is a duplicate question, I will state my stance on why it is not.
The other question had posed a problem regarding the conversion of a string input to an integer (the answer deemed correct). This is irrelevant here, as the problem in my case is one of logic.
The solutions on the other question cannot correct the problem this question presents (finding the syntactical "charAt" error).
Frankly, the context of the other question is beyond the scope of my knowledge in Java.
I have successfully created a program that converts binary numbers to decimal numbers.
import java.util.Scanner;
public class ProblemThree // to convert binary to decimal
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
int[] number = new int[length];
int[] powerTwo = new int[length];
// To list every digit separately //
for (int n = 0; n <= length - 1; n++)
{
number[n] = (int) (binary / Math.pow(10, n)) % 10;
}
// To set the values in powerTwo to 2 //
for (int n = 0; n <= length - 1; n++)
{
powerTwo[n] = 2;
}
// To update the values in powerTwo //
for (int n = 0; n <= length - 1; n++)
{
if (n == 0)
powerTwo[0] = 1;
else if (n == 1)
powerTwo[1] = 2;
else
powerTwo[n] *= powerTwo[n-1];
}
// To add if current value is 1 //
for (int n = 0; n <= length - 1; n++)
{
if (number[n] == 1)
answer += powerTwo[n];
}
System.out.println(powerTwo[0]); // for testing
System.out.println(number[0]); // for testing
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
Seeing how some of the steps were redundant, I tried to simplify the code.
import java.util.Scanner;
public class ProblemThreeTestFunction
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
String number = String.valueOf(binary);
for (int n = 0; n <= length - 1; n++)
{
if (number.charAt(n) == 1)
answer += (int)Math.pow(2, n);
}
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
I actually have no idea why the simplified code logic does not work. It uses the same concept as my original.
Thanks in advanced!
Why don't you just use:
int decimalValue = Integer.parseInt(binary, 2);
But if you use this you Need to use scan.nextLine() not scan.nextInt().
This will just convert your binary number to decimal using base 10 like seen here.
You need to test against the character '1':
if (number.charAt(n) == '1')
not the number 1 that you are currently doing:
if (number.charAt(n) == 1) // WRONG!
Also, since charAt counts from the left, and binary expansion counts from the right, you need to reverse the sense. Change
Math.pow(2, n)
to
Math.pow(2, length - 1 - n)
You are comparing with digit 1, it should be character 1 i.e. '1'.
for (int n = 0; n <= length - 1; n++) {
if (number.charAt(n) == '1') {
answer += (int)Math.pow(2, length - n - 1);
}
}
Also you need to correct the exponent part.

Junit Testing error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an assignment on arrays I'm working on and one of the questions is to write a code for a histogram.
The method histogram takes a positive number n indicating the number of divisions in which the span of the data is divided, and returns an array of integers of length n, where each element of the array contains the count of the elements that fall into this
division.
For example, if the data is (0:5; 1:2; 2:4; 9:8; 5:1; 10:5), then its span is
10:0 (from 0:5 to 10:5).
histogram(4) would divide this range into four segments:
0.5—3.0, 3.0—5.5, 5.5—8.0, and 8.0—10.5.
Inspecting the data, we see that 3 values fall in the first segment, 1 value in the second, 0 values in the third, and 2 values in the fourth. Therefore, the returned value is an array of length 4 containing the values (3; 1; 0; 2) in that order.
Note that the sum of the elements in the returned array is equal to the number of
elements in the data array.
here is my code:
#Override
public int[] histogram(int divisions) {
int[] range = new int[divisions];
double segment = span() / divisions;
for (int i = 0; i < data.length; i++) {
if (data[i] <= (smallestElement() + segment)) {
range[0] += 1;
}
if (data[i] <= (smallestElement() + (2 * segment))) {
range[1] += 1;
}
if (data[i] <= (smallestElement() + (3 * segment))) {
range[2] += 1;
}
if (data[i] <= (smallestElement() + (4 * segment))) {
range[3] += 1;
}
}
return range;
}
and here is my Junit test for my method:
#Test
public void testHistogram() {
double[] data = new double[3];
data = new double[]{0.5, 1.2, 2.4, 9.8, 5.1, 10.5};
int[] dat = new int[4];
dat = new int[]{3, 1, 0, 2};
DoubleArrayStatisticalOutcomes x = new DoubleArrayStatisticalOutcomes(data);
assertArrayEquals(dat, x.histogram(4));
}
the test is not passing. can someone tell me what I did wrong ?
You are incrementing all the histogram bins for each value. In your for loop, if a value is less than smallestValue() + segment, all the conditional statements are executed, not just the smallest it matches.
This makes your histogram cumulative. There are four elements total in the first two bins.
Add a continue statement in each if or make if 2-4 into else ifs.
Your function also breaks down the moment you pass a value not equal to 4 as the tests are hardcoded. Try something like (untested):
double lowerBound = smallestElement();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < divisions; j++) {
if (data[i] <= (lowerBound + (j+1) * segment)) {
range[j] += 1;
continue;
}
}
}

Adding Elements in an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
items_arr = 4;
System.out.println("The elements in the array are: ");
for (int x = 0; x < items_arr; x++)
System.out.println("Array[" + x + "]=" + array[x]);
System.out.print("\n");
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
for (s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
for (s = 0; s < items_arr; s++)
System.out.println("Array[" + s + "]=" + array[s]);
break;
The output is. The elements are
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Enter an element to Insert: 5
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Array [4]= 0
when I insert 5 it posts 0
any suggestions please.. thanks!
To insert in to the array you shuould be doing follwoing operation
array[s]=input
Two notes here
Arrays are fixed length, and you should be checking the array length before inserting values in to that,other wise you will get ArrayIndexOBException. Safer to sue List/Set
As better coding practise, and to improve the readablity, you should be enclosing the conditional/loop statements (such as if or for) - see eg below
eg: 1
for (int x = 0;x<items_arr;x++) {
System.out.println("Array["+x+"]="+array[x]);
}
eg 2:
for(int s = 0; s < items_arr; s++) {
if (array[s] == input) {
break;
}
}
You have not inserted 5 in your array,
do something after items_arr++
array[ items_arr] = input;
If you do not insert any thing then by default every element is 0
You should be using a Collection type; I would recommend an ArrayList - that is -
List<Integer> al = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
al.add(i);
}
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
al.add(input); // And so on...
You are not updating/inserting the array with the new input.
for(s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
just replace the above code with
array[ items_arr] = input;
items_arr++;

Categories

Resources