Converting a 2d String array to a 2d double array - java

I am making a project in which I need to put a certain precision(0.00 or 0.000) on values in a 2d array. The 2d array is a String and i want to convert it to double. But when I try, I get a NullPointerException, I don't know why.
Afterwards I want to again convert it to a String array.
print-method code:
public void printSheet() {
int start = 'a';
char letter = (char) start;
//kolomnamen
for (int i = 0; i < COLUMNS + 1; i++) {
if (i == 0) {
System.out.print(" ");
} else if (WIDTH != 0) {
String s = "";
for (int j = 0; j < WIDTH / 2; j++) {
s += "-";
}
s += (char) (letter + i - 1);
for (int j = 0; j < WIDTH / 2; j++) {
s += "-";
}
System.out.print(s + "\t");
}
}
System.out.println("\n");
for (int i = 0; i < sheet.length; i++) {
System.out.print(1 + i + "." + " ");
for (int j = 0; j < sheet[i].length; j++) {
double[][] voorlopig = null;
voorlopig[i][j] = Double.parseDouble(sheet[i][j]); //<-- problem
double d = voorlopig[i][j];
// String s = " " + sheet[i][j];
System.out.println(voorlopig);
double thaprez = (precision / precision) + (Math.pow(precision, 10)) - 1;
d = Math.floor(d * thaprez + .5) / thaprez;
String s = " " + voorlopig[i][j];
if (sheet[i][j] == null) {
System.out.print(s + "\t\t");
} else if (sheet[i][j].length() < 10) {
System.out.print(s + "\t");
} else {
System.out.print(s);
}
}
System.out.println("\n");
}
}
Thanks in advance.

Try to initialize your array double[][] voorlopig maybe like this:
double[][] voorlopig = new double[sheet.length][sheet.length];
You get NullPointerException because the array voorlopig was double[][] voorlopig = null;

double[][] voorlopig = null;
voorlopig[i][j] = Double.parseDouble(sheet[i][j]);
voorlopig is set to null, you'll get a NullPointerException.Initialize voorlopig before using it.

Related

Writing a static method in Java to return a string using loops

The full assignment is:
Write two public classes (named exactly), TextBox and TextBoxTester. TextBox contains the following overloaded static methods called textBoxString. This method returns a String value.
public static String textBoxString (int side)
The returned String value, when printed, displays as the outline of a square of side characters. The character you use is up to you. Don't forget that '\n' will force a newline character into the returned String. For example, let's assume I want to use * as the character for my box:
String s = textBoxString(3);
System.out.println(s);
will print
xxx
x x
xxx
public static String textBoxString(int side, char bChar)
The returned String value, when printed, displays the outline of a square of side characters using bChar as the box character. For example,
String s = textBoxString(4, '+');
System.out.println(s);
will print
++++
+ +
+ +
++++
So far, this is what I have:
public class TextBox {
public static String textBoxString(int side) {
int n = side;
String string = "";
for (int i = 0; i < n; i++) {
if (i == 0 || i == n - 1) {
string = "***";
}
else {
string = "* *";
}
}
return string;
}
public static String textBoxString(int side, char bChar) {
int n = side;
char c = bChar;
String string = "";
for (int i = 0; i < n; i++) {
if (i == 0 || i == n -1) {
string = c + " " + c + " " + c + " " + c;
}
else {
string = c + " " + c;
}
}
return string;
}
}
My issue is returning the result. I don't know how to return the result that I need, that I would get from running this in a main method (for the first method):
int n = 3;
for (int i = 0; i < n; i++) {
if (i == 0 || i == n - 1) {
System.out.println("***");
}
else {
System.out.println("* *");
}
}
You can use nested loops to achieve this.
public static String textBoxString(int n, char c) {
String output = "";
for(int i = 0; i < n; i++) { // constructing all rows
output += c;
for(int j = 1; j < n-1; j++) { // constructing a single row
if(i == 0 || i == n - 1)
output += " " + c; // use character to fill up each element in the row
else
output += " "; // use space to fill up
}
output += " " + c +"\n";
}
return output;
}
Run and print
x x x x x
x x
x x
x x
x x x x x
Welcome to StackOverflow!
To make textBoxString work for varying values for side, you cannot use the hardcoded string "***" because that will only work when side equals 3.
You'll need to use nested loops to accomplish this.
I'm not gonna write the complete code for you, but I'm gonna give you a hint.
if (i == 0 || i == n - 1) {
// Use a for loop here to construct the top and bottom rows
}
else {
string = "* *";
}
You could add "\n" to your string, it will start a new line.
for (int i = 0; i < n; i++) {
if (i == 0 || i == n -1) {
string += c + " " + c + " " + c + " " + c + "\n";
}
else {
string += c + " " + c + "\n";
}
}
}
After adding that in, return string
public static String textBoxString(int side) {
int n = side;
String string = "";
for (int i = 0; i < n; i++) {
if (i == 0 || i == n - 1) {
for (int j = 0; j < n; j++) {
string += "*";
}
string += "\n";
} else {
string += "*";
for (int j = 1; j < n - 1; j++) {
string += " ";
}
string += "*\n";
}
}
return string;
}

Reverse and sum the number occurrence in string - java

I would like to write a function that will be reverse a number and then sum it up.
For example, the input string is
We have 55 guests in room 38
So the expected output should be
83 + 55 = 138
I have face a question is that I can't read the last number
example:
input string is '8 people'
output is 0
Here's the code I've written :
int total = 0;
String num = "";
String a = input.nextLine();
for (int i = a.length() - 1; i > 0; i--) {
if (Character.isDigit(a.charAt(i))) {
num += a.charAt(i);
if (!Character.isDigit(a.charAt(i - 1))) {
total += Integer.valueOf(num);
num = "";
}
}
}
All you really need to do is :
String input = "We have 55 guests in room 38";
int sum = 0;
String[] split = input.split(" "); // split based on space
for (int i = 0; i < split.length; i++) {
if (split[i].matches("[0-9]+")) {
sum = sum + Integer.parseInt(new StringBuffer(split[i]).reverse().toString());
}
}
System.out.println(sum);
Explanation:
Here we use regex to check if the String split contains only
digits.
Now we reverse the String and then parse it to an int before
summing.
Try this and works for any input in the form "We have x guests in room y". For your program however, instead if the for loop > 0 do > -1 I think:
Scanner scan = new Scanner(System.in);
scan.next(); scan.next();
String numberOne = "" + scan.nextInt();
scan.next(); scan.next(); scan.next();
String numberTwo = "" + scan.nextInt();
// String numberOne = "" + scan.nextInt(), numberTwo = "" + scan.nextInt();
String numberOneReversed = "", numberTwoReversed = "";
for(int k = numberOne.length() - 1; k > -1; k--)
numberOneReversed += numberOne.charAt(k);
for(int k = numberTwo.length() - 1; k > -1; k--)
numberTwoReversed += numberTwo.charAt(k);
int sum = Integer.parseInt(numberOneReversed) + Integer.parseInt(numberTwoReversed);
System.out.println("" + numberOneReversed + " + " + numberTwoReversed + " = " + sum);
scan.close();
Note for your program as defined in your question:
for (int i = a.length() - 1; i > -1; i--) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
and
if (i != 0 && !Character.isDigit(a.charAt(i - 1))) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
Will return the sum correctly.
Okay here is what I created using BigIntegers instead of ints:
public static BigInteger nameOfFunctionGoesHere(String input) {
BigInteger total = new BigInteger(new byte[] {0});
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total.add(new BigInteger(new String(flipped)));
i = j;
} else {
i++;
}
}
return total;
}
You can of course use ints as well like this:
public static int nameOfFunctionGoesHere(String input) {
int total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Integer.parseInt(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}
With longs too:
public static long nameOfFunctionGoesHere(String input) {
long total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Long.parseLong(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}

I can't figure out why my program throws "String Index Out of Range" error (Java)

My program is a rough plan for a basic way to encrypt a password, by choosing random numbers and random mathematical operators that are used with the numbers in the "key" string to encrypt the password. But the program throws an error whenever I run it, and after looking through it for a while I can't tell what's causing the problem.
public static void main(String[] args) {
String pass = "Password";
String pwE = "";
String key = "";
String keyop = "";
for (int i = 0; i < pass.length(); i++) {
key += (int) (Math.random() * 9 + 1);
}
for (int i = 0; i < pass.length(); i++) {
keyop += (int) (Math.random() * 4 + 1);
}
System.out.println(keyop);
System.out.println(key);
for (int i = 0; i < pass.length(); i++) {
for (int j = 0; j < pass.length(); j++) {
if (keyop.charAt(i) == '1') {
pwE += " " + (char) (pass.charAt(i) + (key.charAt(j)));
} else if (keyop.charAt(i) == '2') {
pwE += (char) (pass.charAt(i) - key.charAt(j));
} else if (keyop.charAt(i) == '3') {
pwE += (char) (pass.charAt(i) * key.charAt(j));
} else if (keyop.charAt(i) == '4') {
pwE += " " + ((double) (pass.charAt(i) / key.charAt(j))) + " ";
}
}
pass = pwE;
pwE = "";
}
System.out.println(pass);
}
Above written code has a logic error, you are changing the value of pass at the end of j loop.
for (int j = 0; j < pass.length(); j++) {} pass = pwE;
Now of value of pass changes , and exceeds 7, you will get the error "String index out of range 8" at
key.charAt(j)

How to fix array printing multiple times

When I run this method and set the text on the countLabel it prints it 26 times. Could anyone explain why this happens and how to fix this problem?
void updateCounts() {
int[] letterCounts = new int[26];
for (int i = 0; i < 26; i++) {
letterCounts[i] = 0;
}
String s = encrypted.getText();
s = s.toUpperCase();
for (int i = 0; i < s.length(); i++) {
int j = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(s.charAt(i));
if (j >= 0) {
letterCounts[j] += 1;
}
}
String countString = "";
for (int i = 0; i < 26; i++) {
String n = Arrays.toString(letterCounts);
if (n.equals("0")) {
countString = countString + " ";
} else if (n.length() == 1) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
String noCommas = countString.replace(',', ' ');
countLabel.setText(noCommas.replace('0', ' '));
System.out.println(noCommas.replace(',', ' '));
}
Hi ExtremelyAverageProgrammer,
In the method you have provided, the output only occurs once right at the end:
System.out.println(noCommas.replace(',', ' '));
What this means is that in your main method, you are calling the method "updateCounts()" 26 times, which would explain the irregular output.
Hopefully this helps!

How to get out of for loop at the end of the loop and enter in a new without making the sum

Here is my code. I have to count the frequency of letters in my text.
I got as output:
a 21
b 28(should be 7)
c 34(should be 6)
I think my problem is it makes the sum and i dont want it.
int[] alphabetArray = new int[26];
// char varA = 'a';
alphabetArray[0] = A;``
int count = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == A) {
count++;
}
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");
alphabetArray[1] = B;
for (int i = 0; i < text.length; i++) {
if (text[i] == B) {
count++;
}
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
for (int i = 0; i < text.length; i++) {
if (text[i] == C) {
count++;
}
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");
return null;
Although you could fix your problem by zeroing out the count after printing, your program would not be ideal with the loop itself repeated three times. When you see a pattern like this, it's an indication that you need another loop.
Make a loop outside your current loop going through the letters from 'A' to 'Z'. Since letters' code points in UNICODE are consecutive, you can find the index of a letter by subtracting 'A' from it:
for (char letter = 'A' ; letter <= 'Z' ; letter++) {
int letterIndex = letter - 'A';
for (int i = 0; i < text.length; i++) {
if (text[i] == letter) {
alphabetArray[letterIndex]++;
}
}
}
Note that since you are accumulating counts for all letters, you do not need a separate count variable, because alphabetArray[letterIndex] replaces it. If you want to print letter frequency as you go, print alphabetArray[letterIndex] after the nested loop.
You initialized count=0 once and you are increasing it without re-initalizing it to 0.
int[] alphabetArray = new int[26];
// char varA = 'a';
alphabetArray[0] = A;``
int count = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == A) {
count++;
}
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");
alphabetArray[1] = B;
count=0;
for (int i = 0; i < text.length; i++) {
if (text[i] == B) {
count++;
}
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
count=0;
for (int i = 0; i < text.length; i++) {
if (text[i] == C) {
count++;
}
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");
return null;

Categories