Removing NullPointerException in Java - java

public class leftrec {
static int isleft(String[] left,String[] right)
{
int f=0;
for(int i=0;i<left.length;i++)
{
for(int j=0;j<right.length;j++)
{
if(left[i].charAt(0)==right[j].charAt(0))
{
System.out.println("Grammar is left recursive");
f=1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
String[] left=new String[10];
String[] right=new String[10];
Scanner sc=new Scanner(System.in);
System.out.println("enter no of prod");
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("enter left prod");
left[i]=sc.next();
System.out.println("enter right prod");
right[i]=sc.next();
}
System.out.println("the productions are");
for(int i=0;i<n;i++)
{
System.out.println(left[i]+"->"+right[i]);
}
int flag=0;
flag=isleft(left,right);
if(flag==1)
{
System.out.println("Removing left recursion");
}
else
{
System.out.println("No left recursion");
}
}
}
I've written this code to find out if the given grammar is left recursive or not. When i compile the program it gives me NullPointerException in lines
if(left[i].charAt(0)==right[j].charAt(0))
and
isleft(left,right);
How do i remove the exception ?

I Guess the problem with your inputs , You are just taking the String Array lengths as 10.
String[] left=new String[10];
String[] right=new String[10];
Dont HardCode the String Array length
int n=sc.nextInt();
String[] left=new String[n];
String[] right=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter left prod");
left[i]=sc.next();
System.out.println("enter right prod");
right[i]=sc.next();
}
Might ,this would be the problem

You need to change the code as follows::
package com.cgi.ie2.common;
import java.util.Scanner;
public class LeftRecursive {
static int isleft(String[] left, String[] right)
{
int f = 0;
for (int i = 0; i < left.length; i++) {
for (int j = 0; j < right.length; j++)
{
if (left[i].charAt(0) == right[j].charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
//Changes done here::::
String[] left = new String[n];
String[] right = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
left[i] = sc.next();
System.out.println("enter right prod");
right[i] = sc.next();
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left[i] + "->" + right[i]);
}
int flag = 0;
flag = isleft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}
}
This code will eliminate the NullpointerExceptions
If you getting the no. of prod from the console, the String arrays need to set accordingly,for that the changes i have done are::
System.out.println("enter no of prod");
int n = sc.nextInt();
//Changes done here::::
String[] left = new String[n];
String[] right = new String[n];
And for better codes what i can suggest you is you need to follow basic coding conventions,which makes your codes readable,codes are not perfect only if it runs corectly,codes are perfect if a coding conventions are follow,so please go through the following links to undestand basic idea of coding conventions::
http://www.javacodegeeks.com/2012/10/java-coding-conventions-considered-harmful.html
http://java.about.com/od/javasyntax/a/nameconventions.htm

you can`t initialize an array without size. You have already given the array sizes as 10 and if you enter products which bigger than 10 or smaller than 10 you will get errors. There fore if you want to use dynamic size , you should use a java collection. best approach for this is array list
static int isLeft(ArrayList left, ArrayList right)
{
int f = 0;
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++)
{
if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
String leftText = sc.next();
left.add(leftText);
System.out.println("enter right prod");
String rightText = sc.next();
right.add(rightText);
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left.get(i) + "->" + right.get(i));
}
int flag;
flag = isLeft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}

Related

Java Deque (Finding the max number of unique integers from subarrays.)

I was trying to solve a HackerRank problem on Java Deque. My code passed all the cases apart from the ones which have 100,000 inputs.
Problem: In this problem, you are given N integers. You need to find the maximum number of unique integers among all the possible contiguous subarrays of size M.
--->So we wre given N integers, and need to find the number of "unique integers" in each contagious subarray(of size M). And then print the maximum number of those "unique Integers".
link: https://www.hackerrank.com/challenges/java-dequeue/problem
My Code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque<>();
HashSet<Integer> set = new HashSet<>();
int n = in.nextInt();
int m = in.nextInt();
int max=0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
set.add(num);
if(i>=m-1){
if(set.size()>max)max=set.size();
Integer removed=(Integer)deque.removeFirst();
set.remove(removed);
set.add((Integer)deque.peek());
}
}
System.out.println(max);
}
Please tell me where my code went wrong.
What is the point of this line?
set.add((Integer)deque.peek());
I don't see anything in your code that is slow. I just wonder how you can keep track of unique numbers by using a set, given that a set only tells you if there is such a number (but not how many occurrences of the same number there are). And you don't want to keep scanning the deque to see if the number being removed is the last one.
I don't think this is great/fast code, but it seems to pass the test-cases. I keep a count of how many of each integer there is in the window by using a map (and use some of your code).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque<Integer> deque = new ArrayDeque<>();
HashMap<Integer, Integer> counts = new HashMap<>();
int n = in.nextInt();
int m = in.nextInt();
int max = 0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
int count = counts.getOrDefault(num, 0);
counts.put(num, ++count);
if (i >= m - 1) {
if (counts.size() > max) max = counts.size();
Integer removed = deque.removeFirst();
int removing = counts.get(removed);
removing--;
if (removing == 0) {
counts.remove(removed);
} else {
counts.put(removed, removing);
}
}
}
System.out.println(max);
}
}
Just wanted to share how I solved it in case it helps.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque();
Set<Integer> integers = new HashSet<>();
int n = in.nextInt();
int m = in.nextInt();
long result = 0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
integers.add(num);
if (deque.size() == m) {
long currentSize = integers.size();
if (currentSize > result) {
result = currentSize;
}
Integer removed = (Integer) deque.pollFirst();
if (!deque.contains(removed)) {
integers.remove(removed);
}
}
}
System.out.println(result);
}
We can optimize the space a little bit by avoiding the hashmap all together, but it seems like Hackerrank does not care about that. Any how I am putting my solution here which can solve this problem by using using a map.
private int countUniqueNumsInSubarrays(int[] nums, int m) {
Deque<Integer> deque = new LinkedList<>();
int maxUniqueCount = 0;
for (int i = 0; i < nums.length; i++) {
// if deque's left entry is outside the window then pop it out
while (!deque.isEmpty() && i - deque.peekFirst() >= m) {
deque.removeFirst();
}
// this will make sure that the deque only contains unique numbers,
// this is essentially helps us avoid that extra hash map
while (!deque.isEmpty() && nums[deque.peekLast()] == nums[i]) {
deque.removeLast();
}
deque.addLast(i);
if (i >= m - 1) {
maxUniqueCount = Math.max(maxUniqueCount, deque.size());
}
}
return maxUniqueCount;
}
import java.io.*;
import java.util.*;
import java.util.stream.Stream;
public class Solution {
public static void main(String[] args) {
var sc = new Scanner(System.in);
var split = sc.nextLine().split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
if (!(1 <= n && n <= 100_000)) {
System.exit(0);
}
if (!(1 <= m && m <= 100_000)) {
System.exit(0);
}
if (!(m <= n)) {
System.exit(0);
}
split = sc.nextLine().split(" ");
sc.close();
int maxNumUniqueInt = 0;
HashSet<Integer> dist = new HashSet<>();
Deque<Integer> deque = new ArrayDeque<>();
int[] arr = Stream.of(split).mapToInt(Integer::parseInt).toArray();
for (int i = 0; i < m; i++) {
deque.addLast(arr[i]);
dist.add(arr[i]);
}
int num = dist.size();
if (maxNumUniqueInt < num) {
maxNumUniqueInt = num;
}
for (int i = m; i < n; i++) {
deque.addLast(arr[i]);
dist.add(arr[i]);
int remove = deque.removeFirst();
if (!deque.contains(remove)) {
dist.remove(remove);
}
num = dist.size();
if (maxNumUniqueInt < num) {
maxNumUniqueInt = num;
}
// System.out.println(i + " | " + deque + " | " + dist + " | " + maxNumUniqueInt);
}
System.out.println(maxNumUniqueInt);
}
}
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque<Integer> deque = new ArrayDeque<>();
int n = in.nextInt();
int m = in.nextInt();
int maxUnique = 0;
Map<Integer, Boolean> uniqSet = new HashMap<>();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.addLast(num);
uniqSet.put(num, true);
if(deque.size() == m){
// int uniqueSize = new HashSet<>(deque).size();
int uniqueSize = uniqSet.size();
maxUnique = Math.max(maxUnique, uniqueSize);
int x = deque.removeFirst();
if(!deque.contains(x)){
uniqSet.remove(x);
}
}
}
in.close();
System.out.println(maxUnique);
}
}

how to insert in two dimensional array?

i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}

How to solve error: type Integer is not visible

I have created an ArrayList but when I try to access an element in it, I keep getting the error type Integer is not visible. With a Scanner named in, I read input from a file and create an array, then an ArrayList:
int n = in.nextInt();
int[] curr = new int[n];
for (int i = 0; i < n; i++) {
curr[i] = in.nextInt();
}
ArrayList<Integer> order = new ArrayList<>();
for (int item: curr) order.add(item);
However, when I try to access elements in order by creating an int variable called idx and running order.get(idx), I keep getting the above error. How do I fix this?
Thanks,
Satya
You can try with this code:
private static Scanner in = new Scanner(System.in);
public static void main(String args[]) {
System.out.print("array length = ");
int n = in.nextInt();
int[] curr = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("item"+i+" = ");
curr[i] = in.nextInt();
}
ArrayList<Integer> order = new ArrayList<>();
for (int item: curr) order.add(item);
System.out.print("idx = ");
int idx = in.nextInt();
if (idx<order.size()){
System.out.println(order.get(idx));
} else {
System.out.println("idm out of bounds...\n" +
"result with modulo length of list:");
System.out.println(order.get(idx%order.size()));
}
}
You can also try with this code.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] curr = new int[n];
for (int i = 0; i < n; i++) {
curr[i] = in.nextInt();
}
ArrayList<Integer> order = new ArrayList<>();
for (int item : curr)
order.add(item);
int size = order.size();
while (true) {
System.out.print("index= ");
int idx = in.nextInt();
if (idx < size) {
System.out.println(order.get(idx));
break;
}
System.out.println("Error : indexOutofBoundException");
System.out.println("Try again!");
}
}

Matching array values with variables

In this code I have an array with 5 elements and each element contains a value. Below in the while loop, I'm trying to give the user 3 attempts to guess what number is contained in the array (the user enters their guesses). My problem is that I don't know how to make match the user's guess (stored in a variable choose) with the array values caja[i] to print whether the user won or lost depending on a correct or incorrect guess respectively.
public static void main(String[] args)
{
int[] caja = new int [5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++)
{
System.out.println(caja[i]);
}
System.out.println();
int electionGame = 3;
int o = 0;
while(electionGame > 0)
{
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length; i++)
{
o = o + 1;
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
}
electionGame--;
}
}
}
Your problem is that you break out of your loop in every case:
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
Instead of doing this (and printing the result after only the first comparison), you should have a Boolean indicating whether the number was found in the array:
int electionGame = 3;
boolean found = false; //indicates whether user has found right number
while (electionGame > 0 && !found) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length && !found; i++) {
if (choose == caja[i]) {
found = true;
}
}
electionGame--;
if (found) {
System.out.println("you won");
} else {
System.out.println("nope");
}
}
This way, you can check the variable and tell the user whether he won or lost.
Here are some additional suggestions. The answer by Alex (https://stackoverflow.com/a/36133864/6077352) is good. Please note the comments in the code.
import java.util.Scanner;
/** https://stackoverflow.com/q/36133524/6077352 */
public class GuessNumber {
public static void main(String[] args) {
int[] caja = new int[5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++) {
System.out.println(caja[i]);
}
System.out.println();
int tries = 3;
Scanner sc = new Scanner(System.in);// no need to create scanners in loop
while (tries-- > 0) {// count down tries
System.out.print("Please guess a number... ");
int guess = sc.nextInt();
boolean win = false;// flag to determine if won
for (int i : caja) {// iterate through array and check if guess is inside
win |= (i == guess);// when inside: win=true
}
System.out.println("Answer right? " + win);
System.out.println();
}
}
}
So if the user can attempt to get any of the values of the array you might to change your while loop to this one:
while (electionGame > 0) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
boolean ganaste = false;
for (int i = 0; i < caja.length; i++) {
o = o + 1;
if (choose == caja[i]) {
ganaste = true;
break;
}
}
if (ganaste)
System.out.println("Ganastes");
else
System.out.println("Perdiestes");
electionGame--;
}

How to read values into 2 dimensional array in java

5
1,0,1,1,1
1,1,1,1,1
0,0,0,1,1
0,1,0,1,0
1,0,0,1,1
I am trying to store the above values into 2-d array. My code is for this problem is given below. I don't know why it doesn't stores the values.
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
System.out.println(n);
String[][] multi = new String[n][n];
int i=0;
int t=n;
while(t>0){
String s=scan.nextLine();
String b[]=s.split(",");
for(int j=0;j<b.length;j++){
//System.out.print(b[j]+" ");
multi[i][j]=b[j];
}
//System.out.println();
i++;
t--;
}
System.out.println(multi[0][0]);
for(int k=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
System.out.println();
}
}
}
But it doesn't stores.Can any one help me to solve my problem.
Tell me how to do this.
Change
> for(int k=0;i<n;i++)
to
> for(int k=0;k<n;k++)
EDIT:
Change final for loop to:
for(int k=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
}
System.out.println();
}
And your final code looks like:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=Integer.parseInt(scan.nextLine());
String[][] multi = new String[n][n];
int i=0;
int t=0;
while(t<n){
String s=scan.nextLine();
String b[]=s.split("\\,");
for(int j=0;j<b.length;j++){
multi[i][j]=b[j];
}
i++;
t++;
}
System.out.println(multi[0][0]);
for(int k=0;k<n;k++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
}
System.out.println();
}
}
Good Luck.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String[][] multi = new String[n][n];
int i = 0;
int t = n;
while (t > 0) {
String s = scan.nextLine();
String b[] = s.split(",");
for (int j = 0; j < b.length; j++) {
multi[i][j] = b[j];
}
i++;
t--;
}
for (int k = 0; k < n; k++) {
for (int j = 0; j < n; j++) {
System.out.print(multi[k][j] + " ");
System.out.println();
}
}
}
Please replace
int n=scan.nextInt()
by int n=scan.nextLine()

Categories

Resources