Stuck with Pascal's Triangle in Java - java

Ok, I need to have a class that re-creates the Pascal Triangle. We are using BlueJ and I can't get my arrays to access each other.
Here's the code:
public class PascalTriangle {
private int currentLineNumber;
private int[] previousLineArray;
private int[] nextLineArray;
public void firstLine()
{
currentLineNumber = 1;
System.out.println("1");
}
public void nextLine()
{
if (currentLineNumber == 1) {
int [] previousLineArray = new int [(currentLineNumber+1)];
previousLineArray[0] = 1;
previousLineArray[1] = 1;
System.out.println("1 1");
currentLineNumber = 2;
}
else if(currentLineNumber >= 2) {
for (int lineCount = currentLineNumber; lineCount <= currentLineNumber; lineCount++) {
int [] nextLineArray = new int [(lineCount+1)];
nextLineArray[0] = 1;
System.out.print(nextLineArray[0] + " ");
for (int nextLineCount = 1; nextLineCount < lineCount; nextLineCount++) {
// The next line is the line with the NullPointerException
nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1)
+ previousLineArray[(nextLineCount)]]);
System.out.print(nextLineArray[(nextLineCount)] + " ");
}
nextLineArray[(lineCount)] = 1;
System.out.print(nextLineArray[(lineCount)] + "\n");
previousLineArray = nextLineArray;
}
currentLineNumber = currentLineNumber+1;
}
}
}
The class will compile but as I get to the third line, which should read 1 2 1, I get a java.lang.NullPointerException at PascalTriangle.nextLine(PascalTriangle.java:29) it highlists the nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) line. Why will the nextLineArray take the information from previousLineArray which is set when the nextLine() method is called for the first time?
Any help would be appreciated :) Thanks.

the problem is the following:
in the line where int [] previousLineArray = new int [(currentLineNumber+1)]; - you create a local array that shadows your member and only visible inside of if statement. Then when you come to this line: nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) it uses your member array that was not init.

Related

Code to check same variable names in recursive For loops in eScript

I've written a Java code to validate if a (javascript based) code uses same variable name for two "for loops" (only applicable to the variable initialized inside for statement). For example: this is a correct code
for(var a=0;a<b;a++)
{
for(var b=0;b<c;b++)
{
TheApplication().Trace("ciclo for a2: " + a);
}
}
This code isn't correct:
for(var a=0;a<b;a++)
{
for(var a=0;a<c;a++)
{
TheApplication().Trace("ciclo for a2: " + a);
}
}
Please note that: this isn't actually a javaScript but it's called eScript (it's in Oracle based packaged product called Siebel), hence I cannot use javaScript compilers for evaluation.
Below is the code I've written, but I see a problem, that incase if there are two independent loops inside first "for loop" and they use same variable names in the FOR statement, still my code throws error.
for(var a=0;a<b;a++)
{
for(var b=0;b<c;b++)
{//First loop
}
for(var b=0;b<c;b++)
{//this is not a problem
}
}
Here's my code:
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> ScriptList = new ArrayList<String>();
ScriptList.add("function ForLoop(){try{var b = 20;var c = 10; TheApplication().TraceOn(\"//sbsiebASLog//logs//FedeGestioneNP.log\",\"Allocation\",\"All\");for(var a=0;a<b;a++){TheApplication().Trace(\"ciclo for a1: \" + a);for(var a=0;a<c;a++){TheApplication().Trace(\"ciclo for a2: \" + a);}} }catch(e){}finally{}}");
ScriptList.add("function ForLoop(){try{var b = 20;var c = 10; TheApplication().TraceOn(\"//sbsiebASLog//logs//FedeGestioneNP.log\",\"Allocation\",\"All\");for(var a=0;a<b;a++){TheApplication().Trace(\"ciclo for a1: \" + a);for(var b=0;a<c;a++){TheApplication().Trace(\"ciclo for a2: \" + a);}} }catch(e){}finally{}}");
for(int i =0;i<ScriptList.size();i++)
{
CheckPattern(ScriptList.get(i))
}
}
private static CheckPattern(String Script)
{
boolean bAllVerified = false;
Script = Script.replaceAll("for( var", "for(var");
Script = Script.replaceAll("for ( var", "for(var");
Script = Script.replaceAll("for (var", "for(var");
String sRemaining = Script;
while(!bAllVerified)
{
if(!sRemaining.contains("For(int"))
bAllVerified = true;
else
sRemaining = CheckForLoop(sRemaining);
}
}
private static String CheckForLoop(String string)
{
String rstring = "";
int iFirst = string.indexOf("for(var");
int iCheckIndex = CheckCloseCurlBracket(string,iFirst-("for(var").length());
rstring = string.substring(iCheckIndex);
return rstring;
}
private static int CheckCloseCurlBracket(String string,int iFirst)
{
int iRet=string.length();
ArrayList<Integer> iForIndex = new ArrayList<Integer>();
if(iRet==0)
return iRet;
int iOpen = 0;
int iClose = 0;
int iCloseIndex=0;
int iCountFor=1;
for(int i=iFirst;i<string.length();i++)
{
if(string.charAt(i)=='{')
iOpen++;
else if(string.charAt(i)=='}')
{
iClose++;
iRet = i;
if(iOpen == iClose)
break;
}
if("for(var".equals(string.substring(i,i+("for(var").length())))
{
iCountFor++;
iForIndex.add(i);
}
}
fProcessPattern(string, iFirst,iRet,iCountFor,iForIndex);
return iRet;
}
private static void fProcessPattern(String string, int iFirst, int iLast, int iCountFor, ArrayList<Integer> iForIndex)
{
String sActualString = string.substring(iFirst,iLast);
ArrayList<String> ForList = new ArrayList<String>();
for(int i=0; i<iCountFor;i++)
{
String temp = sActualString.substring(iForIndex.get(i),("for(var").length()+sActualString.indexOf("="));
ForList.add(temp);
}
for(int i = 0; i < ForList.size(); i++)
{
for(int j = i + 1; j < ForList.size(); j++)
{
if(j != i && (ForList.get(j) == null ? ForList.get(i) == null : ForList.get(j).equals(ForList.get(i)))) {
messagebox("Duplicate");
}
}
}
}

Creating triple-ended queue with efficient random access

I have been tasked to solve a question concerning the creation of a triple-ended queue with efficient random access, as outlined in this: https://open.kattis.com/problems/teque. I created a program based around using 2 very large arrays, one containing the front half of all stored integers so far and the other the back half, with both being of the same size or the front half containing at most 1 more element than the back half after every insertion operation. This should allow all insertion and retrieval operations to be of O(1) time complexity, but the code just keeps exceeding the given time limit. Can anyone tell me what is wrong with my code? Here it is:
import java.util.*;
import java.io.*;
public class Teque3 {
static int[] front = new int[1_000_000];
static int[] back = new int[1_000_000];
static int frontHead = 499_999;
static int backHead = 499_999;
static int frontSize = 0;
static int backSize = 0;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
String[] line = br.readLine().split(" ");
if (line[0].equals("get")) {
int index = Integer.parseInt(line[1]);
if (index >= frontSize) System.out.println(back[backHead + index - frontSize]);
else System.out.println(front[frontHead + index]);
continue;
}
if (frontSize == backSize) {
if (line[0].equals("push_front")) {
frontHead--;
front[frontHead] = Integer.parseInt(line[1]);
frontSize++;
} else if (line[0].equals("push_back")) {
back[backHead + backSize] = Integer.parseInt(line[1]);
front[frontHead + frontSize] = back[backHead];
frontSize++;
backHead++;
} else if (line[0].equals("push_middle")) {
front[frontHead + frontSize] = Integer.parseInt(line[1]);
frontSize++;
}
} else {
if (line[0].equals("push_front")) {
frontHead--;
front[frontHead] = Integer.parseInt(line[1]);
backHead--;
back[backHead] = front[frontHead + frontSize];
backSize++;
} else if (line[0].equals("push_back")) {
back[backHead + backSize] = Integer.parseInt(line[1]);
backSize++;
} else if (line[0].equals("push_middle")) {
backHead--;
back[backHead] = Integer.parseInt(line[1]);
backSize++;
}
}
}
}
}
You could try to minimze IO-Operations: Collect your programm output. Instead of writing System.out.println better create a new StringBuilder to collect everything. In the end write all at once.
static StringBuilder result = new StringBuilder();
...
private static void result(int value) {
result.append(value).append("\n");
}
...
if (index >= frontSize) result(back[backHead + index - frontSize]);
else result(front[frontHead + index]);
...
System.out.println(result);
Decouple read from parse and process: Create one thread for reading the operations. But the operations in a Queue. Start another thread for the process.

Issue Reading from text file

I am trying to create a program in Java that calculates the average cost of winning the lottery and saves that average to reference when it runs again (my goal is to be able to create a more accurate outcome every time i run it). The average successfully saves to my txt file, but when I run the program it uses 0 as the previous average every time. Any help is greatly appreciated! Thanks!
(Number of times it runs can be changed by changing the 'runs' variable)
public class WinningTheLottery
{
public static final int SIZE = 5;
public static void main(String[] args)
{
int[] winningNums = new int[SIZE];
int[] guessNums = new int[SIZE];
int spent, runs = 1;
double oldAvg = 0;
double newAvg;
int totalSpent = 0;
NumberFormat currency = NumberFormat.getCurrencyInstance();
try
{
Scanner fileScanner = new Scanner(new File("average.txt"));
PrintWriter fileWriter = new PrintWriter(new File("average.txt"));
while (fileScanner.hasNextDouble())
{
oldAvg = fileScanner.nextDouble();
}
for (int i = 0; i < runs; i++)
{
spent = 0;
randomlyAssignedNumbers(winningNums);
// Arrays.toString(nameOfArray) => built in method to print an array
System.out.println("\n[" + (i+1) + "] Todays winning numbers:\n" + Arrays.toString(winningNums).replace("[", "").replace("]", ""));
do
{
randomlyAssignedNumbers(guessNums);
spent++;
} while (howManyCorrect(winningNums, guessNums) < 5);
System.out.println("After spending " + currency.format(spent) + ", you won the Fantasy 5 lottery $75,000 prize!");
totalSpent += spent;
}
newAvg = ((totalSpent/runs) +oldAvg)/2;
fileWriter.println(newAvg);
System.out.println("\nAverage Cost to win the Lottery: " + currency.format(newAvg)
+ "\n(Previous Average: " + currency.format(oldAvg) + ")");
fileScanner.close();
fileWriter.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
public static void randomlyAssignedNumbers(int[] anyArray)
{
Random rng = new Random();
for (int i = 0; i < anyArray.length; i++)
{
anyArray[i] = rng.nextInt(36) + 1;
}
}
public static int howManyCorrect(int[] a1, int[] a2)
{
if (a1.length != a2.length)
return -1;
int count = 0;
for (int i = 0; i < a1.length; i++)
{
if (a1[i] == a2[i])
count++;
}
return count;
}
}
Your code is opening the file in overwrite mode, default of many programming languages, before scanner can read the content, thus deleting the content before fileScanner.hasNextDouble() read. Move your PrintWriter instantiation after Scanner read, and it will work.
Note: To open the file in append mode, which I don't think you need here. But in Java you use new FileWriter("average.txt", true) and then wrap a PrintWriter around it.
Try not constructing the PrintWriter until after you read the previous value. As noted in the Javadoc the file will be truncated by creating the PrintWriter.

Unchecked or unsafe operations when compiled, exception when atempted to run

When I attempt to compile my code, this error occurs:
Note: GoFishEdited.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
When I tried to run it, this error message occurs:
Exception in thread "main" java.lang.NullPointerException
at Habitat.stockUp(Habitat.java:20)
at GoFishEdited.main(GoFishEdited.java:14)
I'm pretty sure the error is in the stoockUp method, but I don't understand what could be wrong with it.
Here is my code:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
int[] fishArray;
ArrayList<Fish> catchF = new ArrayList<Fish>();
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
fishArray = h1.stockUp();
System.out.println("Start with some weights:");
for (int i : fishArray) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishArray.length]; // array of Fish
for (int i=0; i < fishArray.length; i++) {
fishGroup[i] = new Fish(fishArray[i]); // make fish
}
System.out.println("Fish are made. Now put them in a habitat:\n");
for (Fish f : fishGroup) {
h1.addFish(f);
}
System.out.println("\nAll in. The habitat displays them:\n");
h1.printFish();
System.out.println("\nMove some fish to the second habitat.\n");
for(Fish f : fishGroup){
h2.addFish(f);
}
System.out.println("\nPrint both habitats:\n");
h1.printFish();
h2.printFish();
System.out.println("\nCatch some fish.\n");
for(Fish f : fishGroup){
catchF = h1.catchFish(f);
}
}
}
And:
public class Habitat {
ArrayList<Fish> stringer = new ArrayList<Fish>();
int[] fishArr;
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public ArrayList<Fish> catches = new ArrayList<Fish>();
public int[] stockUp(){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
return fishArr;
}
public Habitat(){
int[] hab;
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
public ArrayList catchFish(Fish f){
int caught = 0 + (int)(Math.random() * ((100 - 0) + 1));
if(caught < catchProbability){
catches.add(f);
stringer.remove(f);
}
return catches;
}
public void printGrid(int[][] twoD){
int i, j;
for ( i = 0 ; i < twoD.length ; i++ ){
for ( j = 0 ; j < twoD[i].length ; j++ ){
System.out.print( twoD[i][j] + " " );
}
System.out.println();
}
}
public void toGrid(String[] oneD){
int cols = (int) Math.floor(Math.sqrt(oneD.length));
int currentCol = 0;
for(String element : oneD) {
System.out.print(element + "\t");
if(currentCol >= cols) {
System.out.println("");
currentCol = 0;
}
else {
currentCol++;
}
}
}
}
I would appreciate an explanation, because I am thoroughly confused, and just want to see if it'll work properly.
The problem is that you never initialize fishArr in Habitat
And the unchecked operation warning might come from public ArrayList catchFish(Fish f){, you should parameterize your return type

Exception in thread "main" java.lang.NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am a beginner in java programming. I am trying to recreate a simplified version of the card game war. I ran my program which is posted below and it came back with this error:
Exception in thread "main" java.lang.NullPointerException
at cardgame.BuildDeck(cardgame.java:36)
at cardgame.main(cardgame.java:60)
I have been trying to solve this issue on my own through research, but I could not solve it. I was wondering if anyone can help me. If you do need any other information about my program, please just ask. Thanks in advance!
-FGxMatta
public class cardgame
{
static class TheCard
{
// Java getter & setter
private String CardName;
private int CardRank;
private int Chosen;
public TheCard(int rank, String name)
{
this.CardName = name;
this.CardRank = rank;
this.Chosen = 0;
}
}
#SuppressWarnings("null")
private static TheCard[] BuildDeck()
{
TheCard[] TheDeck = null;
String[] Cards = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
String[] Suits = {"Spades","Hearts","Diamonds","Clubs"};
int[] Rank = {2,3,4,5,6,7,8,9,10,11,12,13,14};
int cardnumber = 0;
for (int i = 0; i < Cards.length; i++)
{
for (int j = 0; j < Suits.length; j++)
{
String deckcard = Cards[i];
String suitcard = Suits[j];
String cardname = deckcard + "-" + suitcard;
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
cardnumber++;
}
}
return TheDeck;
}
private static TheCard GetRandomCard(TheCard[] OrderedDeck)
{
TheCard thecard;
int random = (int) (51*Math.random ());
thecard = OrderedDeck[random];
if (thecard.Chosen == 0 ) // if available...
{
thecard.Chosen = 1; // mark it taken...
return thecard;
}
else
{
return GetRandomCard(OrderedDeck);
}
}
public static void main(String args[])
{
TheCard[] OrderedDeck = BuildDeck();
System.out.println ("Welcome, Prepare for War!");
int decksize = OrderedDeck.length;
int player1wincount = 0;
int player2wincount = 0;
int tiecount = 0;
for (int cardcount = 0; cardcount < decksize;)
{
TheCard Player1 = GetRandomCard(OrderedDeck);
cardcount++;
TheCard Player2 = GetRandomCard(OrderedDeck);
cardcount++;
System.out.println ("Player 1's card is: " + Player1.CardName);
System.out.println ("Player 2's card is: " + Player2.CardName);
if (Player1.CardRank > Player2.CardRank)
{
System.out.println("Player 1 wins this hand");
player1wincount++;
}
if (Player1.CardRank < Player2.CardRank)
{
System.out.println("Player 2 wins this hand");
player2wincount++;
}
if (Player1.CardRank == Player2.CardRank)
{
System.out.println("Player 1 and Player 2 played the same valued card");
tiecount++;
}
}
System.out.println ("Player 1 won " + String.valueOf(player1wincount) + " hands");
System.out.println ("Player 1 won " + String.valueOf(player2wincount) + " hands");
System.out.println ("There were " + String.valueOf(tiecount) + " ties");
}
}
Replace:
TheCard[] theDeck = null;
with:
TheCard[] theDeck = new TheCard[Cards.length * Suits.length];
and move it to below the declarations for Cards and Suits.
Null Pointer Exception is a situation in code where you try to access/ modify an object which has not been initialized yet. It essentially means that object reference variable is not pointing anywhere and refers to nothing or ‘null’. A simple example can be:
package au.com.copl;
public class Demo{
public static void main(String[] args) {
String d = null;
System.out.println(d.toString()); // d is un-initialized and is null
}
}
right here
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
you never initialized TheDeck. You probably want something like
TheDeck = new TheCard[52];
before you start putting things in the array.
as a note, java convention is that variable names be camel cased. So "CardName" should be cardName. Just a convention.
TheCard[] theDeck = null; ?
dont you need to inialize it?
You should also use new in main method:
TheCard[] OrderedDeck = BuildDeck();
should be replaced by:
TheCard[] OrderedDeck = new BuildDeck();

Categories