I want the output from the code that 5=0101 if 1 occur double and add and if 0 occur only double from the algo
Step 1: randomly select an integer s
Step 2: compute the bit length Ls of s
Step 3: compute L=n/Ls, Lr = n%Ls, Sr= s>> (Ls-Lr)
Step 4: if (Lr=0) then compute M=sP Else compute M=sP and Mr=SrP
Step 5: Q= Mr
Step 6: for i=0 to L
6.1 Q=2LsQ
6.2 Q=Q+M
Step 7: return Q
but this program doesn't return any output.
whats wrong with the code, please rectify the error.
Thanks in advance
package main;
import java.awt.Point;
import java.util.Random;
import java.util.Scanner;
public class a {
private static final double M = 0;
static Object Q;
public static double a() {
//public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("enter the no.:");
int k = reader.nextInt();
String str = java.lang.integer.toBinaryString(k);
int n = str.length();
Point P = new Point();
Random r = new Random();
int s = r.nextInt(50) + 1;
int Ls = Integer.toBinaryString(s).length();
int L = n/Ls;
int Lr = n%Ls;
int Sr = s>>(Ls-Lr);
int Mr = 0;
double Q = Mr;
for (int i = 0; i<L; i++) {
Q = (Math.pow(2, Ls)*Q);
//int M;
Q = Q + M;
}
return Q;
}
public void Q() {
// TODO Auto-generated method stub
}
}
Main method
package main;
import main.a;
public class newmeth {
//private static final int Q = 0;
//private static final String SrP = null;
//private static final int M = 0;
//public int Q() {
public static void main(String [] args) {
System.out.println("enter the no.:");
a myjava = new a();
myjava.Q();
Object Q = null;
a(Q);
}
public static int ya(Object Q) {
//System.out.println("enter the no.:");
return 0;
}
}
If I will simplify your code and remove all unused variables - I will get something like that. and as you can see - you are not execute a() method from main()
package main;
import java.util.Random;
import java.util.Scanner;
import static java.lang.Integer.toBinaryString;
public class newmeth {
private static final double M = 0;
public static void main(String[] args) {
System.out.println("enter the no.:");
}
private static double a() {
Scanner reader = new Scanner(System.in);
System.out.println("enter the no.:");
int k = reader.nextInt();
int n = toBinaryString(k).length();
int s = new Random().nextInt(50) + 1;
int Ls = toBinaryString(s).length();
int L = n / Ls;
double Q = 0;
for (int i = 0; i < L; i++)
Q = (Math.pow(2, Ls) * Q) + M;
return Q;
}
}
And minimal useful changes is change main method like below
public static void main(String[] args) {
System.out.print(a());
}
And also please, check this out, and start calculate M based on your step 4 from your step by step guide
double Q = 0
into loop Q = <...> * Q what always return 0
Q = Q + M Q and M equal 0 so result still 0
Related
class Compound {
public static void main(String args[]) {
int P = Integer.parseInt(args[0]);
int R = Integer.parseInt(args[1]);
int T = Integer.parseInt(args[2]);
int Ci, i, A = 1, Pa = P;
for (i = 1; i <= T; i++) {
Ci = P * R / 100;
P = P + Ci;
A = P + Ci;
}
Ci = A - Pa;
System.out.println(Ci + " is the Ci\nAmount=" + A);
return 1;
}
}
It throws the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Compound.main(JavaApplication1.java:3)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)
this is what happened Please tell the reason for the error and a suitable code to avoid it. Above was a simple program for Compound Interest
Your program is crashing because you're calling it without 3 arguments and just assuming they are there.
You need to ensure that you actually have all three arguments before processing them. Put the code you have in main now in a function and call it when you have 3 args.
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter P");
int P = in.nextInt();
System.out.println("Enter R");
int R = in.nextInt();
System.out.println("Enter T");
int T = in.nextInt();
getCi(P, R, T);
}
public static void getCi(int P, int R, int T) {
int Ci, i, A=1, Pa=P;
for(i=1;i<=T;i++){
Ci=P*R/100;
P=P+Ci;
A=P+Ci;
}
Ci=A-Pa;
System.out.println(Ci+" is the Ci\nAmount="+A);
}
Here is my code:
It is not working for greater numbers to find factorial using recursion
import java.util.*;
import java.lang.*;
class Main
{
static String fib(int f)
{
if(f!=1)
return ""+(f*(Integer.parseInt(fib(f-1))));
else
return "1";
}
public static void main(String[] args) throws java.lang.Exception
{
Scanner sc= new Scanner(System.in);
int f= sc.nextInt();
int a[]=new int[f];
int i;
for( i=0;i<f;i++)
a[i]=sc.nextInt();
for( i=0;i<f;i++)
System.out.println(fib(a[i]));
}
}
It's a problem of the range of the type integer (2147483647). If you just replace int with long (range 9223372036854775807) like this
import java.util.*;
class Main
{
static String fib(long f)
{
if(f!=1)
return ""+(f*(Long.parseLong(fib(f-1))));
else
return "1";
}
public static void main(String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int f = sc.nextInt();
long a[] = new long[f];
int i;
for(i = 0; i<f; i++)
a[i] = sc.nextLong();
for(i = 0; i<f; i++)
System.out.println(fib(a[i]));
}
}
then the program can already calculate everything under 21!. But if you use double then it should work with higher numbers, because double has a range of 1.7976931348623157E308. With double the max working factorial calculation is 170!.
PS: I'm German so if i wrote incorrect english i'm sorry
There is no error in the logic of your code. Since you use int, whose range is shorter than the factorial of numbers beyond 25, you get faulty output. Instead, use long or, more preferably, BigInteger.
NOTE: You have to import the java.math package that contains the BigInteger class to use this type.
static BigInteger fib(BigInteger f) {
if (!f.equals(BigInteger.ONE))
return f.multiply(fib(f.subtract(BigInteger.ONE)));
else
return BigInteger.ONE;
}
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int f = sc.nextInt();
int a[] = new int[f];
int i;
for (i = 0; i < f; i++)
a[i] = sc.nextInt();
for (i = 0; i < f; i++)
System.out.println(fib(new BigInteger(String.valueOf(a[i]))));
}
}
My team is making a project that displays big digits in hash codes.
We imported a local library: ScoreboardNumbers
Example, if the user enters 4, the output is:
#
# #
# #
# #
# # # # #
#
#
So the program is here below and we can't seem to find out what the problem is with one of the lines. I posted the whole code just in case we messed up somewhere else.
Thanks for helping guys!
//Main class
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
System.out.print("Digit: ");
int dig = scanIn.nextInt();
Score digit = new Score(dig);
digit.getScoreArray();
String strDigit = ScoreboardNumbers.get(Digit.getScoreArray()); //Red squiggly under the '.getScoreArray()'
Scanner scanStr = new Scanner(strDigit);
int col = 0;
while (scanStr.hasNextInt()) {
System.out.print(scanStr.nextInt() == 1 ? " #" : " ");
col++;
if (col % 5 == 0) {
System.out.println();
}
}
}
//Instantiable class Digit
public class Digit {
private int digit;
private final int ROWS = 7;
private final int COLS = 5;
public Digit(int digit) {
this.digit = digit;
}
public boolean[][] getDigitArray() {
boolean[][] arr = new boolean[ROWS][COLS];
String strDigit = ScoreboardNumbers.get(digit);
Scanner scanStr = new Scanner(strDigit);
int col = 0;
int row = 0;
while (scanStr.hasNextInt()) {
arr[ROWS][COLS] = (scanStr.nextInt() == 1);
col++;
if (col % 5 == 0) {
col = 0;
row++;
}
}
return arr;
}
}
//Class: Score
public class Score {
private int score;
public Score(int score) {
this.score = score;
}
public boolean[][][] getScoreArray() {
int digit1 = score / 10;
int digit2 = score % 10;
Digit d1 = new Digit(digit1);
Digit d2 = new Digit(digit2);
boolean[][][] scoreArray = {
d1.getDigitArray(),
d2.getDigitArray()
};
return scoreArray;
}
}
First you have to know the difference between instance method and static method.
A. Static Method
Static method are those which are declared with the static keyword.
Static method can be called by using the instance, instance variable or the class name.
Example :
public class MyCalculator{
public static int powerOf(int number, int power){
.... some code here...
}
public static void main(String[] args){
MyCalculator x = new MyCalculator();
int answer1, answer2, answer3;
answer1 = x.powerOf(3, 6); //Correct
answer2 = MyCalculator.powerOf(4, 2); //Correct
answer3 = new MyCalculator().powerOf(4, 2); //Correct
}
}
B. Instance Method
Instance method is declared without the static keyword.
Can be called by an instance or instance variable.
Example :
public class MyCalculator{
public int powerOf(int number, int power){
.... some code here...
}
public static void main(String[] args){
MyCalculator x = new MyCalculator();
int answer1, answer2, answer3;
answer1 = x.powerOf(3, 6); //Correct
answer2 = MyCalculator.powerOf(4, 2); //FALSE
answer3 = new MyCalculator().powerOf(4, 2); //Correct
}
}
The line String strDigit = ScoreboardNumbers.get(Digit.getScoreArray()); on your code calls the static method getScoreArray() from the class Digit which does not exist, thus, generates an error.
It looks like you might be trying to access a method that's not static as if it were a static method. You need to call the getScoreArray() function on an actual Score instance, not on the class itself. Perhaps you want the 'digit' object? In which case it would be digit.getScoreArray(), rather than Score.getScoreArray().
1 getScoreArray() belongs to Score class not digit class
2 getScoreArray() is not static method.
Here's my code:
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
}
What do I need to add in order to generate a random string from the list and print it in the console?
You can randomly select a value from the list with something like:
int index = new java.util.Random().nextInt(eMinor.size());
String value = eMinor.get(index);
and then print it to the console with:
System.out.println(value);
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
Random rand = new Random()
int random = rand.nextInt(eMinor.size());
String note = eMinor.get(random);
System.out.println(note);
}
e minor is one of my favorite keys, so I'll answer. You need a random number generator:
Random ran = new Random();
int x = ran.nextInt(eMinor.size() - 1)
System.out.println(eMinor.get(x));
You could generate multiple notes with a loop:
Random ran = new Random();
for (int i = 0, i < 10; i++) {
int x = ran.nextInt(7)
System.out.println(eMinor.get(x));
}
You could do something like this:
int min = 3;
int range = 3;
Random random = new Random();
int length = min + random.nextInt(range);
String randomString = "";
for (int i = 0; i < length; ++i)
{
randomString += eMinor.get(random.nextInt(eMinor.size() - 1));
}
System.out.println(randomString);
You can use a simple model, but to complex application is necessary more attention with Random class;
enter code here
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int f = 0; f < 3; f++) {
System.out.printf("------------ list %s ------------\n",f);
for (String value : generateList(eMinor)) {
System.out.println(value);
}
}
}
private static List<String> generateList(ArrayList<String> eMinor) {
List<String> tempList = new ArrayList<>();
Random random = new Random();
while (tempList.size() != eMinor.size()) {
String value = eMinor.get(random.nextInt(eMinor.size()));
if (!tempList.contains(value)) {
tempList.add(value);
}
}
return tempList;
}
}
You may use the below complete example:
/*
* Created by Mohammed.Kharma on 2/9/2016.
*/
import java.util.Random;
import java.util.ArrayList;
public class Scrambler {
public static int[] Scramble(final int key, final int elementsCount) throws NegativeArraySizeException {
if (elementsCount < 0) {
NegativeArraySizeException ex = new NegativeArraySizeException("scrambler elementCount");
throw ex;
}
Random rand = new Random(key);
int[] order = new int[elementsCount];
for (int i = 0; i < elementsCount; i++) {
order[i] = i;
}
int count = elementsCount;
while (--count > 0) {
int nextRandom = rand.nextInt(count + 1); // 0 <= k <= count (!)
int temp = order[count];
order[count] = order[nextRandom];
order[nextRandom] = temp;
}
return order;
}
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int numOFRandoStrings = 0; numOFRandoStrings < 10; numOFRandoStrings++) {
int[] randomList = Scramble(new Long(System.currentTimeMillis()).intValue() * numOFRandoStrings, 7); //numOFRandoStrings or any seed,7 means give me 7 random numbers from zero to 6
StringBuffer randomString = new StringBuffer();
for (int ind = 0; ind < randomList.length; ind++) {
randomString.append(eMinor.get(randomList[ind] ));
}
System.out.println("New Random String: " + randomString);
}
}
}
The numThrows Variable is inciting an error of variable not found when used in the main method. even though i declare it in one of the methods.
I use the declare the variable in the void prompt method. This program is designed to calculate Pi using random coordinates then uses a formula to estimate pie over a user given amount of tries.
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts
public static void prompt()
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
}
public static double[] randomX( int numThrows)
{
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts <= numThrows)
{
cordX[i] = Math.random();
i++;
}
return cordX;
}
public static double[]randomY(int numThrows)
{
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts <= numThrows)
{
cordY[i] = Math.random();
i++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY)
{
int ii = 0;
int i = 0;
double hits = 0;
double misses = 0;
for(i = 0; i <= numThrows; i++)
{
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1)
{
hits++;
ii++;
}
else{
misses++;
}
}
}
public static double calcPi(int misses, int hits)
{
int total = hits + misses;
double pi = 4 * (hits / total);
}
// public static void print(double pi, int numThrows)
// {
// System.out.printf(" %-7s %3.1f %7s\n", "Trial[//numtrial]: pi = "
// }
public static void main(String[] args)throws IOException
{
prompt();
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
gethits();
double pi = calcPi(misses, hits);
}
}
If numThrows is declared within another function, then its scope does not extend to the main method.
Instead, if you want to use it in both the main method and the other one, make it a class instance.
For example:
class SomeClass {
public static int numThrows = 2;
public static void test() {
numThrows = 4; // it works!
}
public static void main(String[] args) {
System.out.println(numThrows); // it works!
}
}
Therefore, its scope will be extended to all the members of the class, not just the method.
numThrows is an instance variable to your prompt method. If you want to do what I think you want to do, make numThrows a static variable outside any methods.
It will look like this:
public class Darts {
public static int numThrows
public static int numTrials
These variables can be referenced from any method. This should fix it.
Try to remove the method prompt() it's unused, and put his block in the main method.
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
double[] cordX = randomX(numThrows);
...