Hello i got a little problem with my program here is a code
public class zad1
{
static public class WTP
{
int[] wiersz;
int silnia(int a)
{
if (a < 1)
{
return 1;
}
else
{
return a * silnia(a - 1);
}
}
WTP(int n)
{
int wiersz[] = new int[n+1];
for(int i = 0; i<=n; i++)
{
wiersz[i] = silnia(n) / ( silnia(n - i) * silnia(i) );
}
}
}
public static void main(String args[])
{
int a1 = Integer.parseInt(args[0]);
WTP tablica = new WTP(a1);
for(int i = 1; i<=args.length; i++)
{
System.out.println(tablica.wiersz[i]);
}
}
}
And i getting an error after runing it:
Exception in thread main java.lang.nullpointerexpception at
zad1.java:58.
The 58 line is : System.out.println(tablica.wiersz[i]);
The point of program is to create an line of pascal triangle put a values into it. After that when runing it on console with arguments for example java zad1 4 0 1 its should count values in 4 line of triangle and print the values of positions which is given after 4.
Any idea whats wrong? :/
Thanks for help its runing now but there is one problem its counting posistion + 1 instead of posistion for example in 4 line the values should be for 0-1 , 1-4 , 2-6, 3-4 but its show 0-4 , 1-6, 2-4 i changed for(int i = 1; i<=args.length; i++) to i=0 but its didnt help :/
You are creating a local variable called wiersz inside the WTP constructor.
Change the line to this.wiersz = new int[n+1]; in the WTP constructor.
Related
I am trying to solve a problem:-
A point is at an initial position X. It can be shifted either left or right. If it is moved either left or right with equal probability 10 times, what is the probability of it ending up in its initial position X?
I used the following java program:-
import java.util.Random;
public class ProbMain {
int left;
int right;
int error;
double middle;
public ProbMain() {
left = right = error = 0;
middle = 0.0;
}
void pushLeft() {
++left;
}
void pushRight() {
++right;
}
void push() {
int whichWay;
Random rand = new Random();
whichWay = rand.nextInt(2);
if (whichWay == 0)
pushLeft();
else if (whichWay == 1)
pushRight();
else
++error;
}
public static void main(String[] args) {
ProbMain obj = new ProbMain();
for (int b = 0; b < 10000; b++) {
for (int a = 0; a < 10000; a++) {
for (int i = 0; i < 10; i++)
obj.push();
if (obj.left == obj.right)
++obj.middle;
obj.left = obj.right = 0;
}
}
System.out.println("Error: " + obj.error);
System.out.println("Probability of middle: " + obj.middle / (10000*10000));
}
}
Weird thing is that when I run this on Eclipse I get result around 0.05 but when I run from command line I get result around 0.24. Why so? And which one is correct?
You are creating a new Random object each time you want to retrieve a random number (in the push() method) - this can lead to very poor entropy and create strange results when the program is run with different timings - usually running from eclipse will be much slower due to the attached debugger, which will yield better random results when the RNG is initialized with a time value as seed.
You should change your program to use only ONE Random instance, for example by declaring a new Random member variable and initializing it once in your ProbMain constructor.
I am having an issue with a dice rolling program that I'm trying to create (just uses console).
Here is the dice rolling class file itself:
import java.util.Random;
public class rtd
{
public static int[] rollthedice(int numSides, int numRolls)
{
int[] rollCounter = new int[numSides];
for (int counter = 0; counter < numRolls; counter++)
{
Random randRoll = new Random();
int die = randRoll.nextInt(numSides) + 1;
if ((counter + 1) == die)
{
rollCounter[counter] = die;
}
}
return rollCounter;
}
}
The problem with the class is that for some reason, the for loop refuses to function when I am testing the class to see if it works with the following class in the same folder:
public class tester
{
public static void main(String[] args)
{
rtd roller = new rtd();
int[] results = new int[6];
results = rtd.rollthedice(6, 20);
int rollNumber = 1;
for (int counter = 0; counter < results.length; counter++)
{
System.out.println(rollNumber + " " + results[counter]);
rollNumber++;
}
}
}
When I run the "tester" class, the results show that only one roll was completed, meaning that the for loop did not repeat the code for the specified number of rolls. Can anyone offer me a possible solution or explanation? If you see other flaws, let me know.
I believe the issue may be in my IDE (BlueJ).
First of all, you should follow the naming conventions of the language. I know you just started. Please find time to read.
I modified your code without changing the class and method names even though I wanted to. I will leave it to you as an exercise.
Here's the modified version of rtd class. Please see the comments in source code.
public class rtd
{
public static int[] rollthedice(int numSides, int numRolls)
{
// An array of total number of rolls (NOT sides) to save the result of all rolls
int[] rollCounter = new int[numRolls];
// Let's roll n-th times where n is numRolls
for (int counter = 0; counter < numRolls; counter++)
{
// Let's get a random number between 1 to numSides (A die usually has 6 sides with 1 to 6 dots)
int randomSide = getRand(1, numSides);
// Let's store the current roll result in array
rollCounter[counter] = randomSide;
}
return rollCounter;
}
/**
* This method returns a number between a given range inclusive
*/
public static int getRand(int min, int max)
{
return min + (int)(Math.random() * ((max - min) + 1));
}
}
Also, you can improve your tester class like this-
public class tester
{
public static void main(String[] args)
{
int[] results = rtd.rollthedice(6, 20);
// Since counter starts with 0, we always add 1 so we can read from 1 to 20
for (int counter = 0; counter < results.length; counter++)
{
System.out.println("Roll Number: " + (counter + 1) + " Side Picked: " + results[counter]);
}
}
}
The comments in source should be pretty easy to understand. If you have questions, please ask.
The goal of this program is to run arguments such as "K6V3 20.2 17.4" and use the Weather class to calculate the windchill based on the last 2 numeric arguments and use the first argument as the shorthand name for the area. Im running into a problem when the program is given args in multiples of three, such as "K6V3 20.2 17.4 KCHO 40.0 10.0" Im not sure how to get the loop to restart after the third arg. My program will take the first three args and display the correct information, but it will just repeat that information for the second three args. Here is my code so far, HELP!?!?!
public class ChillMapper {
public static void main(String args[]) {
double ICAO;
double t;
double v;
double windChill;
for (int i = 0; i < args.length / 3; i++) {
if (args.length % 3 == 0) {
ICAO = Text.toDouble(args[0]);
t = Text.toDouble(args[1]);
v = Text.toDouble(args[2]);
windChill = Weather.windChillNA(t, v);
Map.setTemperature(args[i], windChill);
}
}
}
}
It is probably simpler to write the loop this way:
for (int i = 0; i < args.length; i+=3)
{
ICAO = Text.toDouble(args[i+0]);
t = Text.toDouble(args[i+1]);
v = Text.toDouble(args[i+2]);
windChill = Weather.windChillNA(t,v);
Map.setTemperature(ICAO,windChill);
}
Instead of checking every time if i%3==0, you jump by steps of 3. (You better have some checks that the argument length itself is multiple of 3, I leave that to you as an exercise). Then you take the arguments at index i, i+1, i+2 respectively.
You have the array indexes hardcoded. Use variable 'i' instead:
public class ChillMapper
{
public static void main(String args[])
{
double ICAO;
double t;
double v;
double windChill;
int i = 0;
if (args.length % 3 == 0)
{
while (i < args.length)
{
ICAO = Text.toDouble(args[i]);
t = Text.toDouble(args[++i]);
v = Text.toDouble(args[++i]);
windChill = Weather.windChillNA(t,v);
Map.setTemperature(args[i],windChill);
}
}
}
}
For the code below, it stops running when "n" gets around 100,000. I need it to run until 1 million. I dont know where its going wrong, I am still learning Java so there might be simple mistakes in the code as well.
public class Problem14{
public static void main(String[] args) {
int chainLength;
int longestChain = 0;
int startingNumber = 0;
for(int n =2; n<=1000000; n++)
{
chainLength = getChain(n);
if(chainLength > longestChain)
{
System.out.println("chainLength: "+chainLength+" start: "+n);
longestChain = chainLength;
startingNumber = n;
}
}
System.out.println("longest:"+longestChain +" "+"start:"+startingNumber);
}
public static int getChain(int y)
{
int count = 0;
while(y != 1)
{
if((y%2) == 0)
{
y = y/2;
}
else{
y = (3*y) + 1;
}
count = count + 1;
}
return count;
}
}
Please use long as the data type instead of int
I will want this to come into light, that the number does flung higher than 1000000, so variable y needs long to hold it.
It's the datatype for y. It should be long. Otherwise it wraps round to -2 billion.
I thought I recognised this - it's Euler problem 14. I've done this myself.
getChain() method is causing problem it gets to negative and then it hangs forever in the loop.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I keep getting an exception in thread "main":
java.lang.ArithmeticException: / by zero
at PersonalityTest.percentage(PersonalityTest.java:85)
at PersonalityTest.main(PersonalityTest.java:19)
And I want to add the count every time the scanner reads A or B and get the percentage of B.
import java.io.*;
import java.util.*;
public class PersonalityTest {
public static final int dimen = 4;
public static void main(String [] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("personality.txt"));
PrintStream out = new PrintStream(new File("output.txt"));
int[] a = new int[4];
int[] b = new int[4];
welcome();
while (input.hasNextLine()) {
String letter = letter(input, out);
countNum(a, b, out, letter);
int[] percentage = percentage(a, b, out);
type(out, percentage);
out.println("");
}
}
public static void welcome () {
System.out.println("The Keirsey Temperament Sorter is a test that measures four independent dimensions of your personality: ");
System.out.println("1. Extrovert versus Introvert (E vs. I): what energizes you");
System.out.println("2. Sensation versus iNtuition (S vs. N): what you focus on");
System.out.println("3. Thinking versus Feeling (T vs. F): how you interpret what you focus on");
System.out.println("4. Judging versus Perceiving (J vs. P): how you approach life");
System.out.println("");
}
public static String letter (Scanner input, PrintStream out) {
String name = input.nextLine();
out.println(name + ":");
String letter = input.nextLine();
return letter;
}
public static void countNum(int[] a, int[] b, PrintStream out, String letter) {
int[] countA = new int[7];
int[] countB = new int[7];
int n = 0;
out.print("answers: [");
for (int i = 0; i < letter.length(); i++) {
int type = i % 7;
if (letter.charAt(i) == 'A' || letter.charAt(i) == 'a') {
n = 1;
}
else if (letter.charAt(i) == 'B' || letter.charAt(i) == 'b') {
n = 1;
}
countA[type] += n;
countB[type] += n;
if (type == 2 || type == 4 || type == 6) {
a[type / 2] = countA[type - 1]+ countA[type];
b[type / 2] = countB[type - 1]+ countA[type];
} else if (type == 0) {
a[0] = countA[0];
b[0] = countB[0];
}
for (int j = 0; j < dimen; j++) {
out.print(a[j] + "A-" + b[j] + "B," + " ");
}
}
out.print("]");
}
public static int[] percentage (int[] a, int[] b, PrintStream out) {
int[] percentage = new int [4];
out.print("percent B: [");
double n = 0.0;
for (int i = 0; i < dimen; i++) {
n = b[i] * 100 / (a[i] + b[i]); // <--- This is where I get error
percentage [i] = (int) Math.round(n);
out.print(percentage[i]);
}
out.print("]");
return percentage;
}
public static void type (PrintStream out, int[] percentage) {
String[] type = new String [4];
out.print("type: ");
for (int i = 0; i <= dimen; i++) {
while (percentage[i] > 50) {
if (i == 0) {
type[1] = "I";
}
else if (i == 1) {
type[2] = "N";
}
else if (i == 2) {
type[3] = "F";
}
else {
type[4] = "P";
}
}
while (percentage[i] < 50) {
if (i == 0) {
type[1] = "E";
}
else if (i == 1) {
type[2] = "S";
}
else if (i == 2) {
type[3] = "T";
}
else {
type[4] = "J";
}
}
out.print(Arrays.toString(type));
}
}
}
Your logic is very difficult to follow with all the a, b, +1, -1, /2, etc. You should try to reduce it to the smallest amount of code that demonstrates your problem. Odds are that you'll find the problem while you're doing that. You might also provide some sample input. Without one or both of these, it's very difficult to help with your problem.
Update: I'm seeing a number of things that look like problems now that I see what you're trying to do. Unless I'm mistaken, your input file has a name on the first line followed by 70 lines, each with a single letter on them?
For one thing, when read a letter and send it into countNum(), you only have one variable called "n" that you increment whether you see an A or a B, and then you add "n" to both A and B. That's not adding one to either the number of A's or the number of B's. It will always add one to both of them.
Next, since you only send a single letter into countNum(), the outer for loop will only execute one time. That means you'll only ever put a value into a[0] and b[0]. Further, because of the "n" problem, both values will always be 1. Thus the one time you get to the inner for loop, it will always print "1A-1B, 0A-0B, 0A-0B, 0A-0B" for the first part of the answer.
After that, it should be obvious why your percentage() method doesn't work. All but the first position of the array have zeroes in them.
Additional stuff: You define a constant "dimen" equal to 4 but you sometimes use the constant and sometimes use a literal "4". Pick one and stick with it. I'd recommend the constant, and I'd recommend naming it something meaningful, like "NUMBER_OF_PERSONALITY_DIMENSIONS", if that's what it is. For that matter, give all of your variables better names, and it will make things easier for you and me both. Also, in your type() method, you say for ( int i = 0; i <= dimen; i++ ) { to iterate over an array which I think only has 4 elements. That's going to break. Finally, as you kind of mentioned elsewhere, don't pass arrays around, mutating them in multiple different methods. That's a good way to get lost. In general, make methods non-side-effecty. Instead of modifying the things you pass to them, return the important values from the method.
In general, I think you need to take a break and straighten out in your head what you're trying to do. The logic doesn't seem to make any sense.
I don't know if you've learned about this kind of thing yet, but you might consider splitting this into two classes: one to read in the data and one to tally it up. The tallying one might look something like:
class Tallier {
private int numberOfAs;
private int numberOfBs;
private int totalEntriesSoFar;
private int[] typeATotals;
private int[] typeBTotals;
public void gotNewA() {...}
public void gotNewB() {...}
}
You are dividing by zero, the problem is that. On the mentioned line, you have:
n = b[ i ] * 100 / ( a[ i ] + b[ i ] );
Sometimes, a[i]+b[i] is zero. Maybe the problem will be solved by a check like this:
for( int i = 0; i < dimen; i++ ) {
if (a[ i ] + b[ i ]!= 0)
n = b[ i ] * 100 / ( a[ i ] + b[ i ] );
else
//assign a number to n for this situation
percentage [ i ] = ( int ) Math.round( n );
out.print( percentage[ i ] );
}
But logically, you should not divide a number by zero. Then maybe you have to correct your algorithm.