Having trouble looping arguments with multiples of three. (newb) - java

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);
}
}
}
}

Related

Create a program that calculates the square root of a number without using Math.sqrt

This is the formula that can be used to calculate the square root of a number.
result=(guess+(number/guess))/2;
For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.
that makes...
result=(6+(9/6))/2 which is equal to 3.75.
To get the actual square root of 9, I need to make the result the new guess.The program should continue as...
result=(3.75+(9/3.75))/2 which is equal to 3.075.
This process should continue till difference between result and the result after it is equal to 0. For example
result=(3+(9/3))/2 is always equal to 3.
When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.
Here's my code:
package javaPackage;
public class SquareRoot {
public static void main(String[] args) {
calcRoot();
}
public static void calcRoot(){
double num=9;
double guess=6;
double result=0;
while(Math.abs(guess-ans)!=0){
result=(guess+(num/guess))/2;
guess=result;
}
System.out.print(result);
}
}
Output
3.75
My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?
Just exchange the two statements in the while loop (and the initializations to avoid a division by zero):
public static void calcRoot(){
double num=9;
double guess=0;
double result=6;
while(Math.abs(guess-result)!=0){
guess=result;
result=(guess+(num/guess))/2;
}
System.out.print(result);
}
The trick is to have the old value still in guess and the new one in result when the test is executed.
And you should not test for != 0, due to rounding errors this may not be achieved. Better test for some small value >= 1e-7
To compare the result with the previous result you need to keep both of them in a variable.
This does a binary chop.
public static double sqrt(double ans) {
if (ans < 1)
return 1.0 / sqrt(1.0 / ans);
double guess = 1;
double add = ans / 2;
while (add >= Math.ulp(guess)) {
double guess2 = guess + add;
double result = guess2 * guess2;
if (result < ans)
guess = guess2;
else if (result == ans)
return guess2;
add /= 2;
}
return guess;
}
public static void main(String[] args) {
for (int i = 0; i <= 10; i++)
System.out.println(sqrt(i) + " vs " + Math.sqrt(i));
}
prints
0.0 vs 0.0
1.0 vs 1.0
1.414213562373095 vs 1.4142135623730951
1.7320508075688772 vs 1.7320508075688772
2.0 vs 2.0
2.236067977499789 vs 2.23606797749979
2.449489742783178 vs 2.449489742783178
2.64575131106459 vs 2.6457513110645907
2.82842712474619 vs 2.8284271247461903
3.0 vs 3.0
3.162277660168379 vs 3.1622776601683795
and
for (int i = 0; i <= 10; i++)
System.out.println(i / 10.0 + ": " + sqrt(i / 10.0) + " vs " + Math.sqrt(i / 10.0));
prints
0.0: 0.0 vs 0.0
0.1: 0.31622776601683794 vs 0.31622776601683794
0.2: 0.4472135954999581 vs 0.4472135954999579
0.3: 0.5477225575051662 vs 0.5477225575051661
0.4: 0.6324555320336759 vs 0.6324555320336759
0.5: 0.7071067811865476 vs 0.7071067811865476
0.6: 0.7745966692414834 vs 0.7745966692414834
0.7: 0.8366600265340758 vs 0.8366600265340756
0.8: 0.894427190999916 vs 0.8944271909999159
0.9: 0.9486832980505138 vs 0.9486832980505138
1.0: 1.0 vs 1.0
Just create another variable to store the value of the previous guess.
This is the code:
package javaPackage;
public class SquareRoot {
public static void main(String[] args) {
calcRoot();
}
public static void calcRoot(){
double num=9;
double guess=6;
double prevGuess=0;
double result=0;
while(Math.abs(guess-prevGuess)!=0){
result=(guess+(num/guess))/2;
prevGuess = guess;
guess=result;
}
System.out.print(result);
}
}
For performance,following this code:
public static double sqrt(double num) {
double half = 0.5 * num;
long bit = Double.doubleToLongBits(num);
bit = 0x5fe6ec85e7de30daL - (bit >> 1);
num = Double.longBitsToDouble(bit);
for (int index = 0; index < 4; index++) {
num = num * (1.5f - half * num * num);
}
return 1 / num;
}
About the magic number 0x5fe6ec85e7de30daL,you can see the FAST INVERSE SQUARE ROOT
Let's see the performance,the test code:
double test = 123456;
//trigger the jit compiler
for (int index = 0; index < 100000000; index++) {
sqrt(test);
}
for (int index = 0; index < 100000000; index++) {
Math.sqrt(test);
}
//performance
long start = System.currentTimeMillis();
for (long index = 0; index < 10000000000L; index++) {
sqrt(test);
}
System.out.println("this:"+(System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (long index = 0; index < 10000000000L; index++) {
Math.sqrt(test);
}
System.out.println("system:"+(System.currentTimeMillis() - start));
System.out.println(sqrt(test));
System.out.println(Math.sqrt(test));
and the result is:
this:3327
system:3236
this result:351.363060095964
system result:351.363060095964
public static double sqrt(double number)
{
double dd=number, sqi, sqrt=0;
long i, b=0, e=0, c=1, z, d=(long)number, r=0, j;
for (i=1l, sqi=1; ; i*=100l, sqi*=10)
{
if (i>dd)
{
i/=100;
sqi/=10;
j=i;
break;
}
}
for (z=0l; z<16; dd=(dd-(double)(r*i))*100, j/=100l, sqi/=10, z++)
{
r=(long)(dd/i);
d=(e*100l)+r;
int a=9;
for (c=((b*10l)+a)*a; ; a--)
{
c=((b*10l)+a)*a;
if (c<=d)
break;
}
//if (a>=0)
// System.out.print(a);
e=d-c;
sqrt+=a*sqi;
if (number==sqrt*sqrt && j==1)
break;
//if (j==1)
// System.out.print('.');
b=b*10l+2l*(a);
}
return sqrt;
}
Sorry for the undefined variable names....but this program really works!
This program is based on long division method of finding square root

null pointer exception Pascal Triangle

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.

Java formula for if using

I have a code and I know that it isn't right. My task is "print all two-digit numbers which don't have two equal numbers". That means - program need to print numbers like 10, 12, 13 etc. Program didnt need to print 11 because there are 2 equal numbers. Hope that my program at least some is correct. (And sorry for my english).
public class k_darbs1 {
public static void main(String[] args) {
int a,b;
boolean notequal;
for(a = 10; a < 100; a++)
{
notequal = true;
for(b = 100; b < a; b++)
{
if(a != b)
{
notequal = false;
}
}
if(notequal == true)
{
System.out.println(a);
}
}
}
}
so why making things to much complex!?!!?!!!??
public static void main(String[] args) {
for(a = 10; a < 100; a++)
{
if(a%11==0){continue;}
System.out.println(a);
}
}
I think your making this slightly more complicated than it has to be. If n is a 2-digit number, then the leading digit is n/10 (integer division by 10) and the trailing digit is n%10 (modulo 10). You can just test if those two are unequal and print n as appropriate, there's no need for another for-loop.
For instance:
int n = 42;
System.out.println(n/10);
System.out.println(n%10);
4
2
Convert it to a string and check the characters.
for (int a = 10; a < 100; a++) {
String value = String.valueOf(a);
if (value.charAt(0) != value.charAt(1)) {
System.out.println(value);
}
}
You can parse Integer to String. Then compare the numbers with substring. For this process,
you need to know
Integer.toString(i);.
string.substring();
methods. This is not a very efficent way but it is a solution.

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */

How to solve exception in thread "main", java.lang.ArithmeticException: / by zero? [closed]

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.

Categories

Resources