Error when using parseInt() and other errors - java

package practiceapplication;
import static java.lang.Integer.parseInt;
class Practiceapplication{
static int calculate(String arguments[]){
int sum = 0;
if (arguments[0] == "+") //How do I use .equals() method at this point?
for(int x = 0; x < arguments.length; x++){
arguments = Integer.parseInt(arguments);
sum += arguments[x];
}
return sum;
if (arguments[0] == "*") {
for(int x =0; x < arguments.length; x++){
arguments =Integer.parseInt(arguments[]);
sum *= arguments[x];
}
} return sum;
if (arguments[0] == "-"){
for(int x = 0; x< arguments.length; x++){
arguments = Integer.parseInt(arguments);
sum -= arguments[x];
}
} return sum;
if(arguments[0] == "/"){
for(int x =0; x< arguments.length; x++){
arguments = Integer.parseInt(arguments);
sum /= arguments[x];
}
} return sum;
}
public static void main(String[] arguments){
if(arguments.length > 0)
Practiceapplication.calculate(arguments);
System.out.print("The answer is: " + sum); //Why was there an err at "sum"?
}
}
I just started learning java, so I don't know much.
I apologize if I frustrate you, but hey, no one starts out from knowing everything.
Anyways, I think you get the idea what kind of application I was trying to make.
I wanted to sum up everything I know into this thing, so it might look messy.
Anyways, could someone tell me what's wrong, and possibly edit the parts where
I made mistakes, please?
Thank you!

if (arguments[0] == "+") //How do I use .equals() method at this point?
Use this:
if ("+".equals(arguments[0]))
Learn more about string comparision, from this related post : Java String.equals versus ==
And for errors related to parseInt:
You just need to make sure, you are passing a valid number string(with digits) to the parseInt method. If you don't do it then it will throw a numberformatexception.

You've got several problems in your code. Most probably you should read into some Java tutorials first!
(1) You can compare Strings using arguments[0].equals("+") source
(2) Code in your calculate() method does not execute after a return statement.
(3) Familiarize yourself with arrays and methods in Java
Still, here is the working code, hoping you can learn something from it:
static int calculate(String arguments[]) {
int sum = 0;
if (arguments[0].equals("+")) {
for (int x = 0; x < arguments.length; x++) {
int arg = Integer.parseInt(arguments[x]);
sum += arg;
}
} else if (arguments[0].equals("*")) {
for (int x = 0; x < arguments.length; x++) {
int arg = Integer.parseInt(arguments[x]);
sum *= arg;
}
} else if (arguments[0].equals("-")) {
for (int x = 0; x < arguments.length; x++) {
int arg = Integer.parseInt(arguments[x]);
sum -= arg;
}
} else if (arguments[0].equals("/")) {
for (int x = 0; x < arguments.length; x++) {
int arg = Integer.parseInt(arguments[x]);
sum /= arg;
}
}
return sum;
}
public static void main(String[] arguments) {
int result = 0;
if (arguments.length > 0)
result = Practiceapplication.calculate(arguments);
System.out.print("The answer is: " + result);
}

//Why was there an err at "sum"?
Take return value in some variable
public static void main(String[] arguments){
if(arguments.length > 0)
System.out.print("The answer is: " + Practiceapplication.calculate(arguments););
}

Related

Method that outputs figure

I am trying to write a method that outputs the following figure:
*
**
***
****
*****
I tried everything but my code always outputs this instead:
*****
****
***
**
*
Here is my code:
public void outputFigure(int y) {
count1 = y;
count2 = y;
int spaces = 0;
int x = y;
int x2 = y;
boolean s = false;
while (s != true) {
for (int i = spaces; i > 0; i--) {
System.out.print(" ");
}
spaces++;
if (spaces == y - 1) {
s = true;
}
for (count2 = 0; count2 < x; count2++) {
for (count1 = 0; count1 < x2; count1++) {
System.out.print("*");
}
x2--;
System.out.println();
}
}
}
Any help will be appreciated.
Too many loops; you need an outer loop i from 0 to y (the # of lines). Then a loop from i to y - 1 for spaces and another one from y - i - 1 to y for stars. Then a new-line. Also, no need for an instance here; so we can make the method static. Like,
public static void outputFigure(int y) {
for (int i = 0; i < y; i++) {
for (int j = i; j < y - 1; j++) {
System.out.print(" ");
}
for (int j = (y - i - 1); j < y; j++) {
System.out.print("*");
}
System.out.println();
}
}
There is repetitious code here though, which violates the DRY (don't repeat yourself) principle; let's refactor that - first a method to repeat a String an arbitrary count, there are many ways to do that. One (using Java 8+) would be
private static String repeat(String str, int count) {
return Stream.generate(() -> str).limit(count).collect(Collectors.joining());
}
Then we can use that to generate the figure. Like,
public static void outputFigure(int y) {
IntStream.range(0, y).forEachOrdered(i -> System.out.printf(
"%s%s%n", repeat(" ", y - i - 1), repeat("*", i + 1)));
}
In addition to what #Elliott Frisch pointed out, here's another version:
for (int i = 1; i <= 5; i++)
{
for (int j = 5; j >= 1; j--)
{
if (j <= i)
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
You only actually need to do two loops.
Also, one quick stylistic point: don't explicitly compare to true and false.
while (s != true)
can be simplified to
while (!s)
which is much "cleaner" and more concise.
Edit: As pointed out in the comments, you may also want to consider using a more meaningful variable name than s - names like this can be very confusing for debugging (or if you or someone else has to modify the code later).

I am getting a StackOverflow error in a hashfunction code but I cannot determine , can someone help me fix it/

I am creating a hash function by myself for my university assignment. My hash function works something like this ... It will take a string as input and add the ASCII values of every character into a integer variable named sum. This is done in the function named hash_func. Then in the function named MYHashfunc I have used recursion to decrease the value of sum such that it can be a value lesser than the size of the array in which I will store data in using my hash function. Since I am using seperate chaining method to resolve collisions , I used a LinkedList array.
But I am getting a stack overflow error when the function hash_func is called inside MYhashfunc. The code is given below:-
package hashfunction;
import java.util.LinkedList;
import java.util.Scanner;
public class Hashfunction {
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A));
}
}
public static int hash_func(String str) {
int sum = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
sum += (int) str.charAt(i);
} else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z' ||
str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
sum += (int) str.charAt(i);
}
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
int z;
N = sc.nextInt();
String[] str_array = new String[N];
LinkedList<String>[] l_list = new LinkedList[N];
for (int i = 0; i < N; i++) {
l_list[i] = new LinkedList<String>();
}
for (int i = 0; i < N; i++) {
str_array[i] = sc.next();
}
for (int i = 0; i < N; i++) {
z = MyhashFUNC(str_array[i],N);
if(l_list[z].peek()!="-1"){
l_list[z].set(z, str_array[i]);
}
else{
l_list[z].add(str_array[i]);
}
}
for (int i = 0; i < N; i++) {
int size = l_list[i].size();
for (int j = 0; j < size; j++) {
System.out.println(l_list[i].get(j));
}
}
}
}
In the method
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A)); // Call again MyhashFUNC with same parameters
}
}
if sum >= a you enter the else block and you call again the same method with the same parameters. This will generate the StackOverFlow.
Here's the problem: Look at the return for your function:
return(MyhashFUNC(str, A));
It calls itself again and again and again, without anything to stop it. You keep adding stack frames to the call stack until you get - wait for it - a stack overflow.
This is the hallmark of recursion without a stopping condition.
The Problem is,
This is recursive function, So on every recursive call your input parameter should be change/different/updated.
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A));//you are not updating any value and calling same function recursively. this will cause StackOverflowError.
}
}

Summing up products from java loop

I am having problems with summing up the products produced from my java loop.
public class ArtificialNeuron {
public ArtificialNeuron(double[] weightings) {
weights = weightings;
inputs = new double[6];
inputs[0] = 1;
}
public void setInput(int index, double newValue) {
inputs[index] = newValue;
}
public int activate(double threshold) {
double x = 0;
for(int i=0; i<inputs.length;i++)
x = inputs[i]*weights[i];
double sum = x+x+x+x+x+x;
if(sum >= threshold) {
return 1;
} else {
return -1;
}
}
}
I ran several Junit test and it always seem to fail on the if else statement. I believe it probably my summation method, but I don't know how I would sum up the products.
Based on your code, I think you wanted to add all of the products together. Instead, you are multiplying the last product by 6 (effectively). It's unclear why you have the temporary x, you can add each product to a default sum of 0. Also, I think a test for sum < threshold is a little easier to read (likewise, always use braces with your loops - it's easier to read and reason about). Like,
public int activate(double threshold) {
double sum = 0;
for (int i = 0; i < inputs.length; i++) {
sum += inputs[i] * weights[i]; // sum = sum + (inputs[i] * weights[i])
}
if (sum < threshold) {
return -1;
}
return 1;
}

Is it possible to condense my code into less than 3 lines?

public class MagicSquare
{
public static int[][] grid = new int[3][3];
public static int i = 0;
public static int j = 0;
public static void main(String[] args) {
int x = 1;
int y = 2;
int z = 0;
while(z < 9)
{
int holdx = x;
int holdy = y;
z++;
x++;
y--;
if(x == 3)
{
x = 0;
}
if(y == -1)
{
y = 2;
}
if(y == 3)
{
y = 0;
}
if(grid[x][y] == 0)
{
grid[x][y] = z;
}
else
{
holdy++;
if(holdy == 3)
{
holdy = 0;
}
grid[holdx][holdy] = z;
x = holdx;
y = holdy;
}
}
for(int i = 0; i < 3; i++)
{
System.out.print(grid[i][0]+", ");
}
System.out.println(" ");
for(int i = 0; i < 3; i++)
{
System.out.print(grid[i][1]+", ");
}
System.out.println(" ");
for(int i = 0; i < 3; i++)
{
System.out.print(grid[i][2]+", ");
}
}
THE OUTPUT LOOKS LIKE THIS:
2, 4, 9,
6, 8, 1,
7, 3, 5,
Hello,
I wrote a Black Magic code that is able to fill in the grids of the square up and the right of it, but if it is filled with a number then the next number would be put in the square that is below its current spot.
Then, go one square up and to the right and put the next integer there, and if I also go off the grid, then the next number will wrap around to the bottom and/or left. This program run until all the squares are filled.
I was wondering if it is possible to condense my code starting at my while loop to the end of my for loop into a shorter code?
Someone said that I would be able to code this USING JUST 2 lines, and I think that is bizarre... but they said it's doable!
Any hints, help, or pointer would be appreciated!
Thank you so much!
Not sure about less than 3 lines (at least without sacrificing readability), but you can condense these if statements for sure.
if(x == 3) {
x = 0;
}
if(y == -1) {
y = 2;
}
if(y == 3) {
y = 0;
}
Down into simply
x = x % 3;
y = (y + 3) % 3;
And you could pull those into the previous x++ and y--
x = (x + 1) % 3;
y = ((y - 1) + 3) % 3;
Similarly with holdy (if you actually need that value, I do not know).
Then, if you just want to print the array, the for loops can be shortened.
for(int[] row : grid) {
System.out.println(Arrays.toString(row));
}
About 10 years ago, I wrote the following code for computing the entries of a magic square. This, in some sense, boils down to a single line of code, and works for arbitrary odd edge lengths:
class M
{
public static void main(String args[])
{
int n = 5;
int a[][] = new int[n][n];
f(n,1,n/2,n-1,a);
print(a);
}
static int f(int j,int i,int k,int l,int I[][])
{
return i>j*j?i-1:(I[k][l]=f(j,i+1,(k+(i%j==0?0:1))%j,(l+(i%j==0?-1:1))%j,I))-1;
}
public static void print(int a[][])
{
for (int i=0; i<a.length; i++)
{
for (int j=0; j<a[i].length; j++)
{
System.out.print((a[j][i]<10?" ":"")+a[j][i]+" ");
}
System.out.println();
}
}
}
Of course, it is somehow inspired by the IOCCC and would be better suited for Programming Puzzles & Code Golf, but might show how much you can press into a single line of code when you (ab)use the ternary operator and recursion appropriately...

Sigmoid function of a 2D array

Is there a way to find the sigmoid of a 2D array without using an external library like JAMA?
I have tried the following code, but in failure.
public static double[][] sigmoid(double[][] x, boolean deriv){
for (int i = 0; i <x.length ; i++)
{
for (int j = 0; j < x[1].length; j++){
if(deriv == false){
return sigmoid(x[i][j], false) * (1 - sigmoid(x[i][j], false));
}
return (1/(1 + Math.pow(Math.E, (-1 * x[i][j]))));
}
}
}
It says, cannot convert double to double[][]. Any method to solve this would be appreciated. thank you!
This is the function of an element-wise sigmoid operation on your array x:
public static double sigmoid(double t) {
return 1 / (1 + Math.pow(Math.E, (-1 * t)));
}
public static double[][] sigmoid(double[][] x, boolean deriv) {
double[][] = result = new double[x.length][x[0].length];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
double sigmoidCell = sigmoid(x[i][j]);
if (deriv == true) {
result[i][j] = sigmoidCell * (1 - sigmoidCell);
} else {
result[i][j] = sigmoidCell;
}
}
}
return result;
}
In your method, there are some syntax errors, as well as a recursive statement which will never end because deriv is always false. Also the recursive statement calculates a double, not return any 2d array.
If you're doing more than this, I suggest you create methods for subtraction, dot-multiplication and creating ones matrices.

Categories