so I want to create a program that prints out a factorable quadratic equation when the user enters a value, c, and a = 1,. The program should determine all the possible Integer values of b so that the trinomial prints out in the form x^2 + bx + c
An example would be if the user entered -4 for c the program should print out:
x^2 - 4
x^2 - 3x - 4
So far this is what I have done with my code, I am trying to figure out how to execute the program but I really am having trouble of where to go from here. If anyone can offer some help that would be much appreciated!
public class FactorableTrinomials
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("A trinomial in standard form is ax^2 + bx +
c. \nIf a = 1, this program will output all factorable trinomials
given the entered c value.");
System.out.print("\nEnter an integer “c” value: ");
int numC = scan.nextInt();
final int NUMA= 1;
int numB;
if (numC > 0)
{
int factors;
System.out.print("\nThe factors of " + numC + " are: ");
for(factors = 1; factors <= numC; factors++) //determines
factors and how many there are
{
if(numC % factors == 0)
{
System.out.print(factors + " ");
}
}
First, find the pairs of integer which multiplies to c.
all possible values of b will then be the sum of the pair of integer.
A simple way to find the pairs of integer is to loop 2 variables from -c to c and check if the product is c. eg:
for(int i = -1 * numC; i <= numC; i++) {
for(int j = -1* numC; j<= numC;j++) {
if(i * j == numC) {
int b = i + j;
//print solution, if b == 0 then don't print the second term
}
}
}
Related
import java.util.Scanner;
class FloatDigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextDouble();
int x = (int) n;
int count = 0;
do {
count++;
x = x / 10;
} while (x != 0);
System.out.println("Before Decimal Digits: " + count);
//it gets stuck from here only
do {
count++;
n = n * 10;
} while (n != (int) n);
System.out.println(count + " total digits present in there in number.");
}
}
This goes in an infinite loop for the value: 58.2354/58.234. It is working fine with other values too and longer values too.
If some debug logging is added to the second loop, it can be seen, that when multiplying a double number by 10, there is a tiny error which does not allow the comparison n == (int) n ever become true.
It is actually a known issue that floating-point arithmetics has a certain computation error, so it should be taken into account when comparing the double n to its counterpart with the decimal point shifted right:
do {
count++;
n = n * 10;
System.out.println(count + " - " + n);
} while (Math.abs(n - (int) n) > 1E-7);
System.out.println(count + " total digits present in the number.");
Output:
58.234
Before Decimal Digits: 2
3 - 582.34
4 - 5823.400000000001
5 - 58234.00000000001
5 total digits present in the number.
it's my first post so DO stomp me if I wrote something stupid.
I've just started IT classes, and today on "while" loops class my tutor gave us the following homework:
Write a program which reads a natural number n and displays in one graphical box all its divisors from the interval [2; n-1].
So far I came up with a code that works but the result is a bit wrong:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[x] = x;
x = x + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(dvr));
}
}
The problem is that the loop fills the array with a lot of zeroes, and the screenshot of tutor's results shows a window listing only the divisors.
I tried to do this with ArrayList, but that's black magic for me right now and my tutor didn't teach us yet how to use anything beyond stuff used in my code anyway.
Any help highly appreciated.
The main problem you're having is that you're going to have an unknown number of values you want to print, but you're using an array to store them, and arrays have a fixed size. Since you have an array of int, it's going to be entirely populated with the default value of zero.
Ideally, you'd only print the first bunch of non-zero values of your array, but you're storing the divisors scattered throughout your array.
dvr[x] = x; stores each value at an index of that value, when really you should just store each new value into the next open spot in the array.
Create a separate index variable, and store each value using it instead:
int index = 0;
while (x >= 2 && x <= d) {
...
if (y == 0) {
dvr[index++] = x;
...
Then when your main loop is done, you can create a new "display array" that holds only the divisors, and not the zeros. At this point, index tells you exactly how large it needs to be:
int[] display = Arrays.copyOf(dvr, index);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(display));
In Java the default value of an int is zero. So that is why you see a lot of zeros.
Since you define the size of the array to be i which is more than what is required as the no of divisors would always be less than i.
So instead of printing the entire array you should only print it up to the total no of divisors for which you should a separate variable instead of using x.
Here is the modified version where I am using a separate index variable to keep track of number of divisors which start from 0. In the end you can just print the array up to the index
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int index = 0;
int x=2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[index] = x;
x = x + 1;
index= index + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.copyOfRange(drv, 0, index));
}
}
Set datastructure avoids duplicates, you can use that to overcome the problem of duplicate divisors getting added into the data structure.
import java.util.*;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
Set<Integer> divisors = new HashSet<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
divisors.add(x);
x = x + 1;
} else {
x = x + 1;
}
}
List<Integer> l = new ArrayList<>(divisors);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + l);
}
}
Use ArrayList to create Dynamic Array.
Below Code will help you.
Things to change In your Program.
import java.util.*;
take an ArrayList varible
call toString method on Arraylist Object
import java.util.*;
import javax.swing.JOptionPane;
public class NewClass3 {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
List<Integer> dvr = new ArrayList<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr.add(x);
x=x+1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + dvr.toString());
}
}
The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}
import java.util.Scanner;
public class PowersOf2
{
public static void main(String[] args)
{
int inputPowersOf2;
int PowerOf2 = 1;
int exponent;
int exponent2;
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
inputPowersOf2 = scan.nextInt();
System.out.println("\n\n");
if(inputPowersOf2 >= 2)
{
System.out.println("Here are the first " + inputPowersOf2 + " powers of 2:");
System.out.println();
}
else
{
System.out.println("Here is the first power of 2:");
System.out.println();
}
exponent2 = 0;
exponent = 0;
while(exponent <= inputPowersOf2)
{
System.out.print("2^" + exponent2 + " = ");
exponent2++;
System.out.println((PowerOf2 = 2 * PowerOf2) / 2);
exponent++;
}
}
}
why is it when i say give me 1 power of two it prints
2^0
2^1
and when i say give me 2 powers of two it prints
2^0
2^1
2^2
and so on...
Replace
while(exponent <= inputPowersOf2)
with
while(exponent < inputPowersOf2)
As others said in comments, this is very, very easy to solve using the debugger.
Hope that helps,
You could retrace the steps manually on a paper using small inputs and then proceed to larger inputs.
just replace the code while(exponent <= inputPowersOf2) because it runs one extra time becuase of the "=" sign.
I am trying to write a code that prompts the user for three numbers and the program is supposed to say what number is the greatest. I didn't want to do a bunch of "System.out.print" in the if and else if statements. The error according to the debugger is that "greatest" and "greatest1" have not been initialized.
import java.util.Scanner;
public class number1
{
public static void main(String[] args)
{
double a, b, c;
double greatest, greatest1;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter one number :");
a = keyboard.nextDouble();
System.out.print("Enter another number :");
b = keyboard.nextDouble();
System.out.print("Enter a third number :");
c = keyboard.nextDouble();
if(a > b && a > c) {
greatest = a;
} //end of if statement
else if(b > a && b > c){
greatest = b;
}
else if(c > a && c > b) {
greatest = c;
}
else if(a==b && c < a) {
greatest = a;
greatest1 = b;
}
else if(a==c && b < a) {
greatest = a;
greatest1 = c;
}
else if(b==c && a < b) {
greatest = b;
greatest1 = c;
}
else {
System.out.print("All of the numbers are greatest");
}
System.out.print("The greatest number is: " +greatest+ "and" +greatest1);
}
}
Since, the others have already point out the problem. I am going to point out that you can find the biggest number out of three number by just doing :
biggest = Math.max(a, Math.max(b,c));
You can replace all the conditionals in your code.
Imagine that you want the max of a set of integers (e.g., an array of ints). You can do something like:
biggest = array[0]; // initialize max to the first number of the set
iterate over the set and checking the max:
for(int i = 1; i < array.size; i++)
biggest = Math.max(biggest,array[i]);
or with Java Streams:
Arrays.stream(array).max().getAsDouble()
You can also make your own max function, for your case can the following:
public double maxDouble (double a, double b){
if(a > b) return a;
else return b;
}
You can read here more detailed information about the Math class and their methods (such as public static double max(double a,double b).
To fix this, you need to make sure greatest and greatest1 are always assigned to a value. What would happen if it went into this code block:
if (a > b && a > c) {
greatest = a;
} //end of if statement
greatest1 would not be assigned so when it printed it out in the last statement that says
System.out.print("The greatest number is: " + greatest + "and" + greatest1);
It's giving you an error.
Another tip: If you press enter after entering each number, you should read the newline \n after you read each number.
E.g.
a = keyboard.nextDouble();
Should be changed to
a = keyboard.nextDouble();
keyboard.nextLine();
etc.
Take input from keyboard and create a double array and then try below code.
double dblArray[] = {24.0,40.2,38.9};
Arrays.sort(dblArray);
System.out.print("The greatest number is: " +dblArray[dblArray.length-1]+ " and " +dblArray[dblArray.length-2]);
You can print n greatest numbers.
As a general hint: Initialize with 0:
double greatest = 0;
double greatest1 = 0;
But be warned, in your case this indicates an error in your code logic.
Fix that logic, otherwise the result will be 0, which can be wrong.