Connecting a variable in the main method with another method Java - java

The method should return true if the argument is even, or
false otherwise. The program’s main method should use a loop to generate 100 random integers. It should use the isEven method to determine whether each random number is even, or odd. All this is done!!!
This is the part where I can't figure it out!
When the loop is finished, the program should display the number of even numbers that were generated, and the number of odd numbers.
This is my code:
import java.util.Random;
public class EvenOdd
{
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
EvenOdd(randomInteger);
}
}
public static void EvenOdd(int x)
{
int oddNumbers = 0;
int evenNumbers = 0;
if ((x % 2) == 0)
{
System.out.println("Even");
evenNumbers++;
}
else
{
System.out.println("Odd");
oddNumbers++;
}
}
}

Try with this:
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
int oddNumbers = 0;
int evenNumbers = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
if(evenOdd(randomInteger)) evenNumbers++;
else oddNumbers++;
}
System.out.printf("Even numbers: %d - Odd numbers: %d", evenNumbers, oddNumbers);
}
public static boolean evenOdd(int x)
{
if ((x % 2) == 0)
{
System.out.println("Even");
return true;
}
else
{
System.out.println("Odd");
return false;
}
}
Your original approach doesn't work because you initialize to 0 the oddNumbers and evenNumbers variables everytime you call the method.

Define oddNumbers, evenNumbers variables as static class variables and after the loop you can print these 2 value.

Java is not JavaScript. Also, it does not have the ability of C++ as "Static variables in functions".
Variables declared inside a method are local. Variables initialization occurs every time your code reaches a variable definition inside the method and destroyed after exiting from the method.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
So you have such variants:
1) Count numbers inside your main method and return indicator from the utility method.
1.1) boolean
public static boolean isEven(int x){
return (x % 2) == 0;
};
1.2) enum
private enum NumberType {
EVEN,
ODD
}
public static NumberType getNumberType (int x) {
if ((x % 2) == 0) {
return NumberType.EVEN;
} else {
return NumberType.ODD;
}
};
2) Make your variables static:
public class EvenOdd {
private static int evenNumbersCount = 0;
private static int oddNumbersCount = 0;
public static void main(String[] args) {
// your code
}
public static void countNumberType (int x) {
if ((x % 2) == 0) {
++evenNumbersCount;
} else {
++oddNumbersCount;
}
}
}
3) In some sophisticated situations you will need to pass container to your method:
public class EvenOdd {
private static final String EVEN = "even";
private static final String ODD = "odd";
public static void main(String[] args) {
// initialize container
Map<String, Integer> evenOddCounts = new HashMap<>(2, 1);
evenOddCounts.put(EVEN, 0);
evenOddCounts.put(ODD, 0);
Random random = new Random();
int randomInteger = 0;
for (int i = 0; i < 100; i++) {
randomInteger = random.nextInt();
countNumberType(evenOddCounts, randomInteger);
}
System.out.println(evenOddCounts.toString());
}
public static void countNumberType(Map<String, Integer> counts, int x) {
if ((x % 2) == 0) {
counts.compute(EVEN, (numberType, count) -> ++count);
} else {
counts.compute(ODD, (numberType, count) -> ++count);
}
}
}

Related

Palindrome Numbers

I am writing Java code in which I have to create a method that returns boolean with one parameter. The code has to identify in true or false if the number (parameter) provided to it is palindrome or not. This is my code but the outcome is false all the time. Can someone identify what is wrong here?
public class NumberPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome(121));
}
public static boolean isPalindrome(int number) {
int reverse = 0;
boolean variable = true;
while (number > 0) {
int lastdigit = number % 10;
reverse *= 10;
reverse += lastdigit;
number = number / 10;
}
if (reverse==number) {
variable = true;
} else variable = false;
return variable;
}
}
You must keep in memory the initial value of number given in parameter to be able to compare it later with reverse. The code will look like this.
public class NumberPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome(121));
}
public static boolean isPalindrome(int number) {
int initialNumber = number;
int reverse = 0;
boolean variable = true;
while (number > 0) {
int lastdigit = number % 10;
reverse *= 10;
reverse += lastdigit;
number = number / 10;
}
if (reverse==initialNumber) {
variable = true;
} else variable = false;
return variable;
}
}

Function value always getting multiplied by 2

I have created a function "m7" in my class but this function is always returning value getting multiplied by 2.
If I am running this function in "psvm" it is printing the right value.
In my Alice class, the method m7() is returning 10 which is incorrect but if I am running this method in psvm then it is returning 5 which is correct.
package com.math.functions;
import java.util.*;
public class Alice {
Integer[] rank= new Integer[7];
Integer n=65;
int count=0;
public Alice() {
rank[0]=100;
rank[1]=100;
rank[2]=90;
rank[3]=80;
rank[4]=75;
rank[5]=60;
rank[6]=n;
//rank[6]=20;
//rank[7]=10;
//rank[8]=n;
Arrays.sort(rank, Collections.reverseOrder());
}
public void print() {
for (Integer a : rank) {
System.out.println(a);
}
}
public int m7() {
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}
public void res(){
int s = m7();
System.out.println("this is the value of s here :"+s);
Set<Integer> hash_Set = new HashSet<>();
for(int i=0;i<=s/2;i++){
System.out.println("hii");
hash_Set.add(rank[i]);
}
for(Integer o:hash_Set){
System.out.println(o);
System.out.println("rank:"+hash_Set.size());
}
}
public static void main(String[] args) {
Alice a=new Alice();
a.print();
System.out.println("this is: "+a.m7());
a.res();
}
}
You are reusing the value of count from the previous time you run it.
Don't declare count as a member variable, make it a local variable.
public int m7() {
int count = 0; // HERE
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}

How to generate a random number without a repeat in Java

I am using this to generate a random number inside a method and return it:
int randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
How can I make sure there are not two random numbers in a row? I don't care if I get a 3, then a 5, then a 3 again. Only if I get a 3 and then a 3.
int temp = -1; // This will be your value to be compared to random value
for(int i = 0; i < 10; i++) { // assuming your filteredArraylist is size 10
int randomValue = ThreadLocalRandom.current().nextInt(0, 10);
if(randomValue == temp) {
i--; // it will repeat the generation of random value if temp and randomValue is same
} else {
temp = randomValue; // you will put here the ne random value to be compared to next value
System.out.println(randomValue);
}
Try following sample
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("####### " + RandomUtil.getRandomInt(10));
}
}
}
class RandomUtil {
private static int lastInt = -1;
private static Random random = new Random();
public synchronized static int getRandomInt(int upperBound) {
return getRandomInt(0, upperBound);
}
public synchronized static int getRandomInt(int lowerBound, int upperBound) {
int newInt = -1;
while( (newInt = lowerBound + random.nextInt(upperBound - lowerBound)) == lastInt) {
//Keep looping
}
lastInt = newInt;
return newInt;
}
}
As Scary Wombat said, you'll want to compare the previous value to the newly randomized value in a loop (which I assume you are using, since we only see the one line.
Something like this...
int prevRandomNumber, currRandomNumber;
while (notFinished) {
currRandomNumber = getRandom(); // your random number generator
if (prevRandomNumber == currRandomNumber) { // if there would be two in a row
continue; // try again
} else { // otherwise, add to array
addNumberToArray(currRandomNumber);
prevRandomNumber = currRandomNumber;
}
}
Just remember the last generated value and if equals then reject. Here is an example:
int lastRandomValue = -1;
boolean stop = false;
int attempts = 0;
final int maxAttempts = 100_000;
while (!stop) {
int currentRandomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
if (currentRandomValue != lastRandomValue) {
// Use the value
...
// Reset the counter
attempts = 0;
...
// Stop the generation process if generated enough values
if (...) {
stop = true;
}
} else {
// Increment a counter
attempts++;
}
if (attempts >= maxAttempts) {
stop = true;
}
}
Edited:
I'd do something like this: (requires the last random value/a non-reachable number for the first time, e.g. -1)
private int notPreviousRandom(int previousRandomValue) {
int randomValue;
do {
randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
} while (randomValue == previousRandomValue);
return randomValue;
}
Alternatively you could define previousRandomValue as an attribute:
// class
private int previousRandomValue = -1;
// ...
private int notPreviousRandom() {
int randomValue;
do {
randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
} while (randomValue == previousRandomValue);
previousRandomValue = randomValue; // for the next time you're using the
// method
return randomValue;
}

How to efficiently implement Eratosphenes method to generate prime numbers?

I use the following components in my code:
A byte array, each bit representing whether the correspondent number is prime(0) or not(1)
A recursion of Filtering.filter()
I want to ascertain whether these parts make it more efficient or actually slow it down. Any other advices also appreciated.
Code:
import java.lang.Math;
import java.util.*;
class Container{
public final byte[] binary_array;
private final int bit_length;
public Container(int nominal_bit_length){
int byte_length = (int)Math.ceil(nominal_bit_length / 8.0);
this.binary_array = new byte[byte_length];
this.bit_length = 8 * byte_length;
}
private String toBinaryString(int index){//convert into a binary string the byte value on which the bit number refered by the index exists
int byte_index = index / 8;
//System.out.println(index);
String str = Integer.toBinaryString(this.binary_array[byte_index]);
String formatted = ("00000000" + str).substring(str.length());
return formatted;
}
public char get(int index){
String str = this.toBinaryString(index);
return str.charAt(index % 8);//
}
public char set(int index, char value){
StringBuilder str = new StringBuilder(this.toBinaryString(index));
char temp = str.charAt(index % 8);//
str.setCharAt(index % 8, value);//
int byte_index = index / 8;
this.binary_array[byte_index] = (byte)Integer.parseUnsignedInt(str.toString(), 2);
return temp;
}
public int length(){
return this.bit_length;
}
public static Container preset(){
Container c = new Container(8);
c.set(1-1, '1');
c.set(4-1, '1');
c.set(6-1, '1');
c.set(8-1, '1');
return c;
}
}
class Screener{
private static void filterMultiplesOf(int num, Container container){
if (num == 1){
return;
}
int i = 2;
while ((i * num - 1) < container.length()){
container.set(i * num - 1, '1');
i++;
}
}
public static void filter(Container c){
int num = c.length();
if (num <= 8){
c = Container.preset();
} else{
Container base = new Container((int)Math.floor(Math.sqrt(num)));
filter(base);
for (int i = 0; i < base.length(); i++){
if (base.get(i) == '0'){
filterMultiplesOf(i+1, c);
}
}
}
}
}
public class Prime2{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
Container c = new Container(num);
Screener.filter(c);
for (int i = 1; i < c.length(); i++){
if (c.get(i) == '0'){
System.out.print((i + 1) + " ");
}
}
}
}
Edit at 12-03-2014:
What about this segment code?
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class PrimeGenerator {
public static Set<Integer> prime(int num){
if (num <= 2){
Set<Integer> foo = new HashSet<>();
foo.add(2);
return foo;
}
IntStream stream = IntStream.rangeClosed(1, num);
Set<Integer> base = prime((int)Math.ceil(Math.sqrt(num)));
IntStream multiples = base.stream().flatMapToInt((factor) -> (IntStream.rangeClosed(2, (int)Math.floorDiv(num, factor)).map(n -> n * factor)));
Set<Integer> primeset = stream.collect(HashSet::new, HashSet::add, HashSet::addAll);
Set<Integer> nonprimeset = multiples.collect(HashSet::new, HashSet::add, HashSet::addAll);
primeset.removeAll(nonprimeset);
primeset.remove(1);
return primeset;
}
public static void main(String[] args) {
// TODO code application logic here
prime(100000).stream().map(num -> num + " ").forEach(System.out::print);
}
}
as well as this:
import java.lang.Math;
import java.util.*;
/**
* Variation of BitSet which does NOT interpret the highest bit synonymous with
* its length.
*
* #author casper.bang#gmail.com
*/
class FixedBitSet extends BitSet{
int fixedLength;
public FixedBitSet(int fixedLength){
super(fixedLength);
this.fixedLength = fixedLength;
}
#Override
public int length() {
return fixedLength;
}
}
class Screener{
private static FixedBitSet preset;
static{
preset = new FixedBitSet(4);
preset.set(1-1, true);
preset.set(4-1, true);
}
private static void filterMultiplesOf(int num, FixedBitSet bitset){
//System.out.println("--------");
if (num == 1){
return;
}
int i = 2;
while ((i * num - 1) < bitset.length()){
bitset.set(i * num - 1, true);
i++;
}
}
public static void filter(FixedBitSet bitset){
//System.out.println("--------");
int num = bitset.length();
if (num <= 4){
//System.out.println("--------");
bitset = preset;
} else{
FixedBitSet base = new FixedBitSet((int)Math.floor(Math.sqrt(num)));
filter(base);
for (int i = 0; i < base.length(); i++){
if(!base.get(i)){
filterMultiplesOf(i + 1, bitset);
}
}
}
}
}
public class Prime3{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
FixedBitSet bs = new FixedBitSet(num);
// System.out.println(bs.length());
Screener.filter(bs);
for (int i = 1; i < bs.length(); i++){
if(!bs.get(i)){
System.out.print((i + 1) + " ");
}
}
}
}
Your "efficient" usage of a byte array is immaterial to the bad performance of your code, which uses string building to implement getting and setting.
Instead write code which uses low-level bit-manipulation operators (such as ~, &, and |) to implement get and set.
If you're not up to that, then consider using BitSet, a JDK-provided class which serves the same purpose.
If you want to learn how it's done, then simply open BitSet's source code.

How to create main class for public static int method in java?

I'm sorry for this noob question but I'm not really familiar with this method. This method generates check digit for ean 8 barcodes. How can I create the main class for this method? Are there any other ways of generating check digit for ean 8 barcodes?
public class CheckDigit {
public static int checkdigit(String idWithoutCheckdigit) {
String validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVYWXZ_";
idWithoutCheckdigit = idWithoutCheckdigit.trim().toUpperCase();
int sum = 0;
for (int i = 0; i < idWithoutCheckdigit.length(); i++) {
char ch = idWithoutCheckdigit.charAt(idWithoutCheckdigit.length() - i - 1);
if (validChars.indexOf(ch) == -1)
throw new RuntimeException("\"" + ch + "\" is an invalid character");
int digit = ch - 48;
int weight;
if (i % 2 == 0) {
weight = (2 * digit) - (digit / 5) * 9;
} else {
weight = digit;
}
sum += weight;
}
sum = Math.abs(sum) + 10;
return (10 - (sum % 10)) % 10;
}
}
Just add another method in your class:
public class CheckDigit {
public static int checkdigit(String idWithoutCheckdigit) {
/*
Good looking implementation of your method
*/
}
public static void main(String[] args) {
//fill the String with a expected value
String idWithoutCheckdigit = "...";
//evaluate the String with your method
int useAGoodNameForThisVar = checkdigit(idWithoutCheckdigit);
//print the results
System.out.println("checkdigit(" + idWithoutCheckdigit + ") = " + useAGoodNameForThisVar);
}
}
Main methods in java look like this (having a main method makes a class the main class).
public static void main(String[] args)
{
//code...
}
Perhaps then you want to then call your method
public static void main(String[] args)
{
// print the results of your method
System.out.println(checkdigit("This is the string i'm giving to my method."));
}
public static void main(String[] args){
for(String each : args){
System.out.println(CheckDigit.checkdigit(each));
}
}
Like this:
public class CheckDigit {
public static void main(String[] args) {
if (args.length > 0) {
for (String arg : args) {
System.out.println(CheckDigit.checkdigit(arg));
}
} else {
System.out.println("Please give some values on the command line");
}
}
public static int checkdigit(String idWithoutCheckdigit) {
String validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVYWXZ_";
idWithoutCheckdigit = idWithoutCheckdigit.trim().toUpperCase();
int sum = 0;
for (int i = 0; i < idWithoutCheckdigit.length(); i++) {
char ch = idWithoutCheckdigit.charAt(idWithoutCheckdigit.length() - i - 1);
if (validChars.indexOf(ch) == -1)
throw new RuntimeException("\"" + ch + "\" is an invalid character");
int digit = ch - 48;
int weight;
if (i % 2 == 0) {
weight = (2 * digit) - (digit / 5) * 9;
} else {
weight = digit;
}
sum += weight;
}
sum = Math.abs(sum) + 10;
return (10 - (sum % 10)) % 10;
}
}

Categories

Resources