Just for fun, i wanted to see whether i could employ a code to display twin primes as practice for learning Constructors. I though i had used a good logic but for some reason i couldnt make it work.
This program is to print all twin primes(primes with 1 gap between them) till a given number as input by the user.
package X;
import java.io.*;
import java.util.*;
class TwinPrimeWithConstructor {
int limit;
public void Twin() {
limit = 0;
}
public static void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
int limit = input.nextInt();
}
public void display() {
for (int k = 1; k <= (limit - 2); k++) {
int a = prime(k);
int b = prime(k + 2);
if (a == 1 && b == 1) {
System.out.println(k + "," + k + 2);
}
}
}
public int prime(int n) {
int c = 0;
int d = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c = c + 1;
}
}
if (c == 2) {
d = 1;
return d;
} else {
return d;
}
}
void main() {
TwinPrimeWithConstructor ob = new TwinPrimeWithConstructor();
ob.input();
ob.display();
}
}
This program manages to correctly detect primes and asks for input,but does not give any output. Can someone make it clear to me? I'm still learning java so any help would be appreciated.
Also since im new, if you find any bad habits in my code, please feel free to tell me so i can become a better programmer.
You are not getting any output because this.limit is always 0:
int limit = Input.nextInt();
You should assign the input to your instance field rather than to a new local variable. To do this, the input method must not be static:
public void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
limit = input.nextInt();
}
Related
I am trying to make a match game where random numbers will show on the console then you have to type back the same numbers. I am having a problem with the if statement where it shows incorrect even when I input the right numbers. Here is my code so far:
package MatchGame;
import java.util.Random;
import java.util.Scanner;
public class match2 {
int a;
int b;
int c;
int d;
String countdown[] = {
"3...",
"2...",
"1..."
};
public match2() throws InterruptedException {
set1();
}
public void set1() throws InterruptedException {
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
for (int i = 0; i < countdown.length; i++) {
Thread.sleep(1000);
System.out.println(countdown[i]);
}
a = number();
b = number();
c = number();
d = number();
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);
int set = a + b + c + d;
int guess = s.nextInt();
{
if(set == guess) {
System.out.println("Nice bruh +1");
}
else {
System.out.println("Nope");
}
}
}
public static int number(){
Random r = new Random();
int match = r.nextInt(9) + 1;
//rv = rv + match;
return match;
}
}
Also the variable 'set' doesn't seem to include the variables a, b, c, and d in it.
An easy method would be to store your values and input to two arrays two separate arrays and compare both instead.
My code works fine in my compiler and I even tried another few online compilers but still not able to find the issue, can someone help!
Question
https://www.codechef.com/JUNE18B/problems/NAICHEF
Once, after a stressful day, Chef decided to relax and visit a casino near his house to gamble. He feels lucky and he's going to bet almost all of his money.
The game Chef is going to play in the casino consists of tossing a die with N
faces twice. There is a number written on each face of the die (these numbers are not necessarily distinct). In order to win, Chef must get the number A
on the first toss and the number B
on the second toss of the die.
The excited viewers want to know the probability that Chef will win the game. Can you help them find that number? Assume that Chef gets each face of the die with the same probability on each toss and that tosses are mutually independent.
My submission
import static java.lang.System.exit;
import java.util.*;
import java.lang.*;
/**
*
* #author williamscott
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean status = true;
int T = Integer.parseInt(in.nextLine());
//Original Constraint
if (T < 1 || T > 10) {
// System.out.println("Please follow original constraint for T");
// exit(0);
status = false;
}
int N[] = new int[T], A[] = new int[T], B[] = new int[T];
float Probability[] = new float[T];
for (int t = 0; t < T; t++) {
String[] input = in.nextLine().split(" ");
N[t] = Integer.parseInt(input[0]);
A[t] = Integer.parseInt(input[1]);
B[t] = Integer.parseInt(input[2]);
if (N[t] < 1 || N[t] > 100) {
// System.out.println("Please follow original constraint for N");
// exit(0);
status = false;
}
if (A[t] < 1 || A[t] > N[t]) {
// System.out.println("Please follow original constraint for A");
// exit(0);
status = false;
}
if (B[t] < 1 || B[t] > N[t]) {
// System.out.println("Please follow original constraint for B");
// exit(0);
status = false;
}
float pn, pa = 0, pb = 0;
String[] f = in.nextLine().split(" ");
pn = f.length;
if (pn != N[t]) {
// System.out.println("Inputs Invalid");
// exit(0);
status = false;
}
for (String f1 : f) {
if (Integer.parseInt(f1) < 1 || Integer.parseInt(f1) > N[t]) {
// System.out.println("Please follow original constraint for x (input)");
// exit(0);
status = false;
}
if (Integer.parseInt(f1) == A[0]) {
pa++;
}
if (Integer.parseInt(f1) == B[0]) {
pb++;
}
}
Probability[t] = (pa / pn) * (pb / pn);
}
if (status) {
for (float d : Probability) {
System.out.println(String.format("%.10f", d));
}
}
}
}
Error:
First of all, you should use double rather then float (precision matters)!
Secondly, you should update your conditions for status because you take in consideration only the first sub-task with (T less than 10, and N less than 100) which will give you only 20 points! the second sub-task (that rewards 80 points) takes a T less than 70 and a N less than 1000.
Finally, the issue with the code comes from the condition of updating pa & pb, you use :
Integer.parseInt(f1) == A[0] // same for B[0]
instead of
Integer.parseInt(f1) == A[t] // same for B[t]
Here is the complete code and submission results
import java.util.*;
import java.lang.*;
/**
*
* #author aoubidar
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// number of test cases
int T = Integer.parseInt(in.nextLine());
int[] N = new int[T];
int[] A = new int[T];
int[] B = new int[T];
double[] Probability = new double[T];
for (int t = 0; t < T; t++) {
String[] input = in.nextLine().split(" ");
N[t] = Integer.parseInt(input[0]);
A[t] = Integer.parseInt(input[1]);
B[t] = Integer.parseInt(input[2]);
int total, pa = 0, pb = 0 ;
String[] faces = in.nextLine().split(" ");
total = faces.length;
for (String f : faces) {
if (Integer.parseInt(f) == A[t]) {
pa++;
}
if (Integer.parseInt(f) == B[t]) {
pb++;
}
}
double pn = (double) (total * total);
Probability[t] = (pa * pb) / pn ;
}
for (double d : Probability) {
System.out.println(d);
}
}
}
submission success:
Never compare floating point numbers using == or !=. Digital computers cannot represent floating point numbers with absolute precision, and so these tests will often fail.
Never use float when double will work. You gain little by using float and lose a much precision.
Leave your integer input as ints, and convert to double only when needed, here cast to double when doing probability calculations
Don't over-complicate your code as you're doing, and use testable methods to help simplify as well. No need to use arrays for example. The constraints mentioned above likely do not need to be tested in your program but rather assumed to be true.
Use variable names that comply with Java naming standards, and that make sense.
For example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// get number of trys
String line = scanner.nextLine();
int trys = Integer.parseInt(line.trim());
for (int i = 0; i < trys; i++) {
// for each try, calc probability
double probability = processTry(scanner);
System.out.println(probability);
}
scanner.close();
}
private static double processTry(Scanner scanner) {
String line;
// get first line
line = scanner.nextLine();
// use Scanner to get ints from line
Scanner lineScan = new Scanner(line);
//number of faces
int numberOfFaces = lineScan.nextInt();
int a = lineScan.nextInt();
int b = lineScan.nextInt();
lineScan.close();
// scanner to get face values
line = scanner.nextLine();
lineScan = new Scanner(line);
// count of how many faces match a and b values
int aMatch = 0;
int bMatch = 0;
for (int i = 0; i < numberOfFaces; i++) {
int face = lineScan.nextInt();
if (a == face) {
aMatch++;
}
if (b == face) {
bMatch++;
}
}
lineScan.close();
// only cast to double when need for calc
double probability = ((double) (aMatch * bMatch) / (numberOfFaces * numberOfFaces));
return probability;
}
}
Let's suppose there is n(A) is the number of occurrence of A on the dice and n(B) is the number of occurrence of B on the dice. In this, the probability that A will be thrown at a given time is
P(A) = n(A) / N
and the probability that B will be thrown at a given time is
P(B) = n(B) / N
The probability that A will be thrown first and B will be thrown second is
P(A) ^ P(B) = P(A) * P(B)
since the experiments are independent.
P(A) * P(B) = n(A) * n(B) / N^2
since this is precisely in your code, you have implemented a correct algorithm for the calculation, so the problem must consist in something else than the algorithm.
Usage of float
The usage of float might be causing slight differences between your result and the expected result. Change it to double.
I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}
I have the following question for Homework
If a number is equal to the sum of all of its factors except itself, it is a perfect number. For example, 6 is a perfect number since 6 = 1 + 2 + 3.
Write a program that takes an input number and displays all perfect numbers up to and including that number.
and this is what I have so far
import java.util.*;
public class perfectnumbers
{
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int externalNumber;
int internalNumber;
int internalTotal = 0;
System.out.println("Input Number");
externalNumber = console.nextInt();
while (externalNumber > 0) {
internalNumber = externalNumber;
while (internalNumber > 0) {
internalNumber = internalNumber - 1;
internalTotal = internalNumber + internalTotal;
}
if (internalTotal == externalNumber) {
System.out.println(internalTotal);
}
externalNumber = externalNumber - 1;
internalTotal = 0;
}
}
}
But for some Reason when ever I enter a number only 3 gets outputted... Can anyone help?
Perfect numbers (like other perfect things) are very scarce ones
https://oeis.org/A000396
they are (within the int range):
6, 28, 496, 8128, 33550336
(only three more 8589869056, 137438691328, 2305843008139952128 when working with long).
So you can implement it like that:
private static int[] perfectNumbers = new int[] {
6, 28, 496, 8128, 33550336
};
private static void displayPerfects(int upTo) {
for (int item : perfectNumbers)
if (item > upTo)
break;
else {
System.out.print(item);
System.out.println();
}
}
...
public static void main(String[] args) {
...
System.out.println("Input Number");
...
externalNumber = console.nextInt();
...
displayPerfects(externalNumber);
}
Please note, that efficiency really matters in your case, e.g. how much time does it take if your're given, say, 2000000000? All you have to do is to test at most five values.
You never check for a factor. Do something like this:
while (externalNumber > 0) {
internalNumber = externalNumber-1; //Make sure to subtract one here
while (internalNumber > 1) { //Change this to 1 so you don't divide by 0
internalNumber = internalNumber - 1;
if (externalNumber%internalNumber==0){ //Check for factor
internalTotal = internalNumber + internalTotal;
}
}
if (internalTotal == externalNumber) {
System.out.println(internalTotal);
}
externalNumber = externalNumber - 1;
internalTotal = 0;
}
I'm having trouble in getting the binary. I do not know what's wrong. The binary number always ends up in gibberish. Also some parts like the new int[31] thing was from HW but I can't get around to make print the actual binary.
public class DectoBinary {
public static void main(String[]args) {
Scanner CONSOLE = new Scanner(System.in);
System.out.print("Please enter a nonnegative integer: ");
int value = CONSOLE.nextInt();
while (value < 0) {
System.out.print("number outside range.");
System.out.print
("Please enter a nonnegative interger more than 0: ");
value = CONSOLE.nextInt();
}
int[] intArray = new int[31];
decimalToBinary(value, intArray);
System.out.println(value + "" + intArray);
}
public static int[] decimalToBinary(int value, int[]intArray) {
int i = 0;
while (value != 0) {
if (value % 2 == 1)
intArray[i] = 1;
else
intArray[i] = 0;
value /= 2;
i++;
}
return intArray;
}
}
I think the error is on this line:
System.out.println(value + "" + intArray);
You cannot print an array of integers like this: you should either convert it to string, or write a loop that prints the array digit by digit:
for (int i : inrArray) {
System.out.print(intArray[i]);
}
System.out.println();
You do not need to pass in the output array as well: you can create it inside the function.
public static int[] decimalToBinary(int value) {
int count = 1;
int tmp = value;
while (tmp != 0) {
tmp /= 2;
count++;
}
int[] intArray = new int[count];
// Do the conversion here...
return intArray;
}
You can simply use Integer.toBinaryString(int).
Actually the is a very simple way to get binary numbers in java using BigInteger
public String dectoBin(int num){
String s = ""+num;
BigInteger bi = new BigInteger(s);
String bin = bi.toString(2);
return bin
}
BigInteger.toString(2) returns the number stored on the numerical base specified inside the parenthesis. Is a very easy way to get arround this problems.
System.out.println(value + "" + intArray);
the 'intArray' is a arrays's address, so, if you want to get actual binary you can use Arrays.toString(intArray)
As dasblinkenlight you need to print the array item by item. If you want a nice alternative, you can use a recursive printing of value mod 2 (modulo 2 gives you 1 or 0)
/** print directly*/
public static void decimalToBinary(int value) {
if(value > 1){
System.out.print(decimalToBinary(value/2) + "" + (value%2));
/**recursion with implicit cast to string*/
} else {
System.out.print( (value==0)?"":"1");
}
}
It works with any Base
Well actually to print the array, because all the slots in the array are initialized at 0 you need to detect where the first one begins, so.
you need to replace
System.out.println(value + "" + intArray);
with something like this;
System.out.println(vale + " ");
boolean sw = false;
for(int i=0;i<intArray.length;i++){
if(!sw)
sw = (intArray[i]==1);//This will detect when the first 1 appears
if(sw)
System.out.println(intArray[1]); //This will print when the sw changes to true everything that comes after
}
Here is a program to convert Decimal nos. into Binary.
import java.util.Scanner;
public class decimalToBinary {
static int howManyTerms (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String revArrayofBin2Str (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter any no.: ");
int num = sc.nextInt();
int[] bin = new int[howManyTerms (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = revArrayofBin2Str(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
}
This is simple java code for decimal to binary using only primitive type int, hopefully it should help beginners.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DtoB {
public static void main(String[] args) {
try { // for Exception handling of taking input from user.
System.out.println("Please enter a number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int x = Integer.parseInt(input);
int bin = 0;
int p = 1;
while (x > 0) {
int r = x % 2;
bin = (r * p) + bin;
x = x / 2;
p *= 10;
}
System.out.println("Binary of " + input + " is = " + bin);
} catch (Exception e) {
System.out.println("Please enter a valid decimal number.");
System.exit(1);
e.printStackTrace();
}
}
}