Issue with Java Contructor not working as expected [duplicate] - java

This question already has answers here:
Are fields initialized before constructor code is run in Java?
(5 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 26 days ago.
The constructor is not working in class CheckForDuplicate. this.input=input is not working. So this.input gets null. The code in the subsequent line throws null pointer exception char[] arr = input.toCharArray(); as input could not be set in the constructor. Since I am relatively new to Java, any help on this is appreciated.
main class:
import java.util.*;
public class BalancedParanthesis {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
CheckForDuplicate chk = new CheckForDuplicate(input);
chk.checkForDup();
}
}
import java.util.Stack;
public class CheckForDuplicate{
String input;
Stack<Character> stack = new Stack<>();
public CheckForDuplicate(String input) {
this.input = input;
}
char[] arr = input.toCharArray();
boolean checkForDup(){
boolean isDuplicate = false;
for (char c : arr) {
if (c == '(') {
stack.push(c);
} else if (c == ')') {
isDuplicate = popElements();
if (isDuplicate) {
System.out.println("Duplicate Paranthesis exists");
break;
}
}
}
return isDuplicate;
}
boolean popElements(){
for (int j=0;j<stack.size();j++){
if (stack.peek()=='(' && j==0){
return true;
}
stack.pop();
}
return false;
}
}
I am creating an object of CheckForDuplicate class and setting String input by calling the contructor CheckForDuplicate, but this constructor is not working.

Related

While checking for null value by comparing it to null, getting null pointer exception on the statement itself [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have written a condition in code where if the value of Object is null, it should initialize a new object, but I am getting null pointer exception at the comparison statement itself. as per my knowlwdge we van compare two null values.
Not sure what a I missing. Below is my code
public class TrieNode
{
static final int Alphabet_Size = 26;
class Tried
{
Tried children[] = new Tried[Alphabet_Size];
boolean isEndofWord;
Tried()
{
isEndofWord = false;
/*for(int i=0; i<Alphabet_Size; i++)
children[i] = null; */
}
};
static Tried root;
public void insert(String key)
{
Tried note = root;
int index;
int itr;
for(itr=0; itr<key.length(); itr++)
{
index = key.charAt(itr)-'a';
if(note.children[index]==null) // Getting Null pointer Exception here
{
note.children[index] = new Tried();
}
note = note.children[index];
}
note.isEndofWord = true;
}
public boolean search(String key)
{
Tried note = root;
int index;
int itr;
for(itr=0; itr<key.length(); itr++)
{
index = key.charAt(itr)-'a';
if(note.children[index]==null)
return false;
note = note.children[index];
}
return (note!=null && note.isEndofWord);
}
public static void main(String[] args)
{
TrieNode tr = new TrieNode();
String keys[] = {"the", "their", "Aakash", "Aayush"};
for(int i=0; i<keys.length; i++)
{
tr.insert(keys[i]);
}
}
}
I Have tried adding null values for all the indexes in array(see the commented part of code) but even that is not helping
if note itself is null you cannot perform note.children[index] try something like if(note==null) then initialize object

"team_name" cannot be resolved to a variable

I am having an unusual error with trying to return a string in my code. I am very new to java so I don't sometimes understand the ins and outs of how classes and returning values/assignment of values works. Any advice would be very helpful! Thank you :)
package videogaem;
import java.util.Scanner;
public class TeamName {
public String getTeamName() {
boolean valid_name = false;
Scanner reader = new Scanner(System.in);
while (valid_name == false) {
System.out.println("Enter team name here: ");
String team_name = reader.nextLine();
int name_length = team_name.length();
if (name_length >= 3 && name_length < 10) {
System.out.println(team_name + "... Sweet as name!");
valid_name = true;
return team_name;
}
else {
System.out.println("Name must be within 2 - 10 characters! :^)");
valid_name = false;
}
}
reader.close();
return team_name; /// <<< team_name is underlined red with the error
}
public static void main(String[] args) {
TeamName team = new TeamName();
team.getTeamName();
}
}
You need to declare the variable name outside the while condition. You have declared the variable name inside the while loop, so it's scope lies inside the while loop.Make sure the scanner is closed. In if statement you simply returning the team_name you have not closed the reader. It's opened, so first close the reader and then return the team_name.
import java.util.Scanner;
public class TeamName {
public String getTeamName() {
String team_name = null;
boolean valid_name = false;
Scanner reader = new Scanner(System.in);
while (valid_name == false) {
System.out.println("Enter team name here: ");
team_name = reader.nextLine();
int name_length = team_name.length();
if (name_length >= 3 && name_length < 10) {
System.out.println(team_name + "... Sweet as name!");
valid_name = true;
}
else {
System.out.println("Name must be within 2 - 10 characters! :^)");
valid_name = false;
}
}
reader.close();
return team_name;
}
public static void main(String[] args) {
TeamName team = new TeamName();
team.getTeamName();
}
}
in the getTeamName() method declear the String team_name ..
remove from the inner scope and right just before this scope.😊

Working with methods

I'm pretty new to coding Java. Below are codes for a program that is supposed to use several methods to ask for a string, reverse the string, test for palindrome and output the result of the test. I'm trying to debug my many errors.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original, String reverse) {
if (original.equals(getString(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String original, Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original,reverse);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
}
return reverse
}
public static void main(String[] args) {
System.out.print(promptForPalindrome);
}
}
For a start in main
you are calling
System.out.print(promptForPalindrome);
but if you look at the method promptForPalindrome you will see that it takes the parameters String original, Scanner Keyboard
BUT
These parameters are not even used, so maybe just delete them and change the main code to be
System.out.print(promptForPalindrome ());
Consider reading a basic java tutorial as well.
edit
Similar problems exist for isPalindrome - I suggest you change to
public static boolean isPalindrome(String original) {
return original.equals(getReverse(original));
}
and call it in as
boolean answer = isPalindrome(original);
But then your answer in
while (answer == false) {
will never change - so many bugs
The method signatures for the isPalindrome needs to be changed to only accept 1 string argument because you don't have the reversed string when it is called. Also there is no reason to pass in a scanner object for the prompt method because you instantiate it in the method. Also I changed your .equals to .equalsIgnoreCase so you don't get messed up by capitals. Also you need to update your boolean after each loop.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equalsIgnoreCase(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
answer = isPalindrome(original);
}
return getReverse(original);
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
Hope this helps I may have made some typos so let me know.
Your code has lot of errors. Check the below working code with comments in it.
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length() - 1; i > -1; i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) { // Two args are not required
// use equals if you need a case sensitive match
if (original.equalsIgnoreCase(getReverse(original))) { // Call getReverse() to reverse the string
return true;
} else {
return false;
}
}
public static String promptForPalindrome() { // Arguments are not required
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = null;
boolean answer = false;
do { // Use a do-while loop since you need to continue till it is success
original = keyboard.nextLine();
answer = isPalindrome(original);
if (!answer) {
System.out
.printf("Error: %s is not a palindrome. Please enter a palindrome.",
original);
}
} while (!answer);
keyboard.close(); // Close the Scanner
return original;
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
}
Thanks guys for all your help,
I was finally able to debug the code.
package osu.cse1223;
import java.util.Scanner;
public class Homework08a {
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equals(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String msg, Scanner keyboard) {
System.out.print(msg);
String userInput = keyboard.nextLine();
return userInput;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String msg ="Please enter a Palindrome";
String userInput = promptForPalindrome(msg, keyboard);
while (isPalindrome(userInput) == false) {
userInput = promptForPalindrome(msg, keyboard);
}
System.out.printf("%s is a palindrome", userInput);
}
}

Getting wrong answer from Uva judge for the 3n+1problem

I tried to submit the 3n+1 problem several time but failed to get it accepted on the Uva judge.I wrote the program in java.Can anyone point out the mistake in my program.
Problem statement:-
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=29&page=show_problem&problem=36
My program:-
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
while((input=Main.ReadLn(255))!=null){
StringTokenizer str=new StringTokenizer(input);
int n1=Integer.parseInt(str.nextToken());
int n2=Integer.parseInt(str.nextToken());
int max=0;
for(int i=n1;i<=n2;i++)
{
int no=calculate(i,0);
if(max<no){
max=no;
}
}
System.out.println(n1+" "+n2+" "+max);
}
}
static int calculate(int a,int sum){
if(a==1)
{
return sum+1;
}
else if(a%2==0)
{
sum+=1;
return calculate(a/2,sum);
}
else
{
sum+=1;
return calculate((3*a+1),sum);
}
}
}
I am very sorry for bad indentation of my code.
I think the problem is with the input/output. The code in your question reads one line and then prints one line. The input/ouput on the UVa page specifies to use a "series" for input and use "for each" as ouput. In other words: read all the input lines, calculate, and then write all the output lines.
Here is some code to help you read all the input-lines (the ReadLn method in your question looks overly complicated):
public static List<int[]> readCycleRanges() throws Exception {
List<int[]> cycleRanges = new ArrayList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while (!(line == null || line.trim().length() == 0)) {
StringTokenizer st = new StringTokenizer(line, " ");
int i = Integer.valueOf(st.nextToken());
int j = Integer.valueOf(st.nextToken());
cycleRanges.add(new int[] { i, j, 0 });
line = br.readLine();
}
return cycleRanges;
}
I got it accepted by UVa judge. The problem was didn't considered that the second number can be smaller than the first number. You have to consider that case in which the second number is the starting of the series.

How to solve "Cannot Make Static Reference to Non-Static Method" in a Java mastermind game? [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 7 years ago.
This question is based on my former question. How to add a "cheat" function to a Java mastermind game
I added the cheat function to my program, but it cannot compile because of "Cannot Make Static Reference to Non-Static Method"(the old codes works, you can check it through the link I post). Here are my new codes:
import java.util.*;
public class mm {
static int[] random;
public static void main(String[] args) {
System.out.println("I'm thinking of a 4 digit code.");
//update
mm m1 = new mm();
random = m1.numberGenerator();
int exact=0, close=0;
while(exact!=4){
int[] guess= m1.userinput(); //update
exact=0;
close=0;
for(int i=0;i<guess.length;i++){
if(guess[i]==random[i]){
exact++;
}
else if (random[i]==guess[0] || random[i]==guess[1] || random[i]==guess[2] || random[i]==guess[3]) {
close++;
}
}
if(exact==4){
System.out.println("YOU GOT IT!");
}
else{
System.out.println("Exact: "+exact+" Close: "+close);
}
}
}
public int[] userinput() {
System.out.print("Your guess: ");
Scanner user = new Scanner(System.in);
String input = user.nextLine();
//cheater
if (input.equals("*")) {
System.out.format("Cheater!Secret code is:");
for(int i=0;i<random.length;i++){
System.out.print(random[i]);
}
}
int[] guess = new int[4];
for (int i = 0; i < 4; i++) {
guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
}
return guess;
}
public int[] numberGenerator() {
Random rnd = new Random();
int[] randArray = {10,10,10,10};
for(int i=0;i<randArray.length;i++){
int temp = rnd.nextInt(9);
while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
temp=rnd.nextInt(9);
}
randArray[i]=temp;
}
return randArray;
}
}
How to solve this?
You can't call a non-static method directly from a static method. in public static main(String [] args)
To do so, you should first create an object of the class.
try this at main method:
mm m1 = new mm();
random = m1.numberGenerator();
int [] guess = m1.userInput();
this should work
The other option would be to make userinput method static as well

Categories

Resources