How to fix '<identifier> expected' error in HackerRank - java

I'm new to Java coding, and I'm stuck with a simple ArrayList sum code. I believe that my method is correct, but I don't understand the main method. I tried to run it many times, but it keeps saying that my input, ArrayList ar, is not 'identified'. Help needed!
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the simpleArraySum function below.
*/
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = Integer.parseInt(scanner.nextLine().trim());
int[] ar = new int[arCount];
String[] arItems = scanner.nextLine().split(" ");
for (int arItr = 0; arItr < arCount; arItr++) {
int arItem = Integer.parseInt(arItems[arItr].trim());
ar[arItr] = arItem;
}
int result = simpleArraySum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
}
// Below is my code
public static int simpleArraySum(int n, ar) {
/** It says that 'ar' is not identified. I tried
'Arraylist<Integer>
* ar but it still won't work
int sum = 0;
for (int i = 0; i < ar.size(); i++) {
sum += ar.get(i);
}
return sum;
}
}
This is what it returns:
Compile Message:
Solution.java:39: error: <identifier> expected
public static int simpleArraySum(int n, ar) {
^
1 error

The declaration of type of parameters for the method simpleArraySum is missing.
Try the following signature, it should work
public static int simpleArraySum(int n,int[] ar) {

Related

why isn't the rest of my method being called? (loop being ignored)

i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();

Creating a list with input, however nothing shows up after compiling

I wish to create a list, and the list has a input as length, however after I put in the preferable length as input, the list won't show up;
import java.util.ArrayList;
import java.util.Scanner;
public class JJ {
public static void main(String args[]) {
JJ.getalist();
}
public static ArrayList<Integer> getalist(){
ArrayList<Integer> JJ = new ArrayList<Integer>();
System.out.println("Oh, How long would you want your list to be?");
Scanner in = new Scanner(System.in);
int length = in.nextInt();
for (int i=0; i<length; i++) {
int point = (int) (Math.random()*9);
JJ.add(new Integer(point));
}
return JJ;
}
}
You didn't use System.out.println() in the main method when invoking JJ.getalist(). You can pass JJ.getalist() return value as the argument of the method printing to the console like this:
System.out.println(JJ.getalist()).

My code for finding factorial is not working. Please somebody find the error

Here is my code:
It is not working for greater numbers to find factorial using recursion
import java.util.*;
import java.lang.*;
class Main
{
static String fib(int f)
{
if(f!=1)
return ""+(f*(Integer.parseInt(fib(f-1))));
else
return "1";
}
public static void main(String[] args) throws java.lang.Exception
{
Scanner sc= new Scanner(System.in);
int f= sc.nextInt();
int a[]=new int[f];
int i;
for( i=0;i<f;i++)
a[i]=sc.nextInt();
for( i=0;i<f;i++)
System.out.println(fib(a[i]));
}
}
It's a problem of the range of the type integer (2147483647). If you just replace int with long (range 9223372036854775807) like this
import java.util.*;
class Main
{
static String fib(long f)
{
if(f!=1)
return ""+(f*(Long.parseLong(fib(f-1))));
else
return "1";
}
public static void main(String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int f = sc.nextInt();
long a[] = new long[f];
int i;
for(i = 0; i<f; i++)
a[i] = sc.nextLong();
for(i = 0; i<f; i++)
System.out.println(fib(a[i]));
}
}
then the program can already calculate everything under 21!. But if you use double then it should work with higher numbers, because double has a range of 1.7976931348623157E308. With double the max working factorial calculation is 170!.
PS: I'm German so if i wrote incorrect english i'm sorry
There is no error in the logic of your code. Since you use int, whose range is shorter than the factorial of numbers beyond 25, you get faulty output. Instead, use long or, more preferably, BigInteger.
NOTE: You have to import the java.math package that contains the BigInteger class to use this type.
static BigInteger fib(BigInteger f) {
if (!f.equals(BigInteger.ONE))
return f.multiply(fib(f.subtract(BigInteger.ONE)));
else
return BigInteger.ONE;
}
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int f = sc.nextInt();
int a[] = new int[f];
int i;
for (i = 0; i < f; i++)
a[i] = sc.nextInt();
for (i = 0; i < f; i++)
System.out.println(fib(new BigInteger(String.valueOf(a[i]))));
}
}

Cannot find Symbol - Variable, despite the variable being declared

The numThrows Variable is inciting an error of variable not found when used in the main method. even though i declare it in one of the methods.
I use the declare the variable in the void prompt method. This program is designed to calculate Pi using random coordinates then uses a formula to estimate pie over a user given amount of tries.
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts
public static void prompt()
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
}
public static double[] randomX( int numThrows)
{
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts <= numThrows)
{
cordX[i] = Math.random();
i++;
}
return cordX;
}
public static double[]randomY(int numThrows)
{
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts <= numThrows)
{
cordY[i] = Math.random();
i++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY)
{
int ii = 0;
int i = 0;
double hits = 0;
double misses = 0;
for(i = 0; i <= numThrows; i++)
{
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1)
{
hits++;
ii++;
}
else{
misses++;
}
}
}
public static double calcPi(int misses, int hits)
{
int total = hits + misses;
double pi = 4 * (hits / total);
}
// public static void print(double pi, int numThrows)
// {
// System.out.printf(" %-7s %3.1f %7s\n", "Trial[//numtrial]: pi = "
// }
public static void main(String[] args)throws IOException
{
prompt();
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
gethits();
double pi = calcPi(misses, hits);
}
}
If numThrows is declared within another function, then its scope does not extend to the main method.
Instead, if you want to use it in both the main method and the other one, make it a class instance.
For example:
class SomeClass {
public static int numThrows = 2;
public static void test() {
numThrows = 4; // it works!
}
public static void main(String[] args) {
System.out.println(numThrows); // it works!
}
}
Therefore, its scope will be extended to all the members of the class, not just the method.
numThrows is an instance variable to your prompt method. If you want to do what I think you want to do, make numThrows a static variable outside any methods.
It will look like this:
public class Darts {
public static int numThrows
public static int numTrials
These variables can be referenced from any method. This should fix it.
Try to remove the method prompt() it's unused, and put his block in the main method.
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
double[] cordX = randomX(numThrows);
...

Sum of elements of an Integer ArrayList without looping

I have gone through a few web resources and links, however, I am unable to find the sum of elements of an Integer ArrayList without looping. I am looking for a function which will allow me to do this in a single line.
I was able to find the same for a normal array as follows
import java.util.ArrayList;
import java.util.stream.IntStream;
public class sumArray
{
public static void main(String[] args)
{
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
}
}
I can write a user-defined function as follows
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(sum(al));
}
static int sum(ArrayList<Integer> al)
{
int value = 0;
for(int i : al)
{
value += i;
}
return value;
}
}
However, I'm looking for something in-built.
Please advise.
EDIT : I have tried the following but I get build errors
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
System.out.println(getVersion());
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(al.stream().mapToInt(Integer::intValue).sum());
}
static double getVersion () {
String version = System.getProperty("java.version");
int pos = version.indexOf('.');
pos = version.indexOf('.', pos+1);
return Double.parseDouble (version.substring (0, pos));
}
}
Errors
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Integer cannot be resolved to a variable
Syntax error on tokens, delete these tokens
You can easily map a Stream<Integer> to an IntStream and then calculate the sum :
a1.stream().mapToInt(Integer::intValue).sum();
al.stream().reduce(0, (x,y) -> x+y)

Categories

Resources