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);
}
}
}
Simply not printing the same output as the line above and I can't figure out why this is happening, I've noticed that it's printing the last N numbers from the end backwards, whatever i input into the parameter it prints that amount a second time.
Here's the main
public class main {
public static void main(String args[]) {
ScalesSolution s1 = new ScalesSolution(11);
s1.println();
ScalesSolution s2 = new ScalesSolution(s1.GetSol());
s2.println();
}
}
Heres the ScalesSolution Class
import java.util.ArrayList;
import java.util.Random;
public class ScalesSolution {
private String scasol;
public void print() {
System.out.print(scasol);
}
// Display the string with a new line
public void println() {
print();
System.out.println();
}
public String GetSol()
{
return scasol;
}
}
Heres the randomOther Class
import java.util.*;
import java.io.*;
public class randomOther {
// Shared random object
static private Random rand;
// Create a uniformly distributed random integer between aa and bb inclusive
static public int UI(int aa, int bb) {
int a = Math.min(aa, bb);
int b = Math.max(aa, bb);
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
int d = b - a + 1;
int x = rand.nextInt(d) + a;
return (x);
}
// Create a uniformly distributed random double between a and b inclusive
static public double UR(double a, double b) {
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
return ((b - a) * rand.nextDouble() + a);
}
static public ArrayList<Double> ReadNumberFile(String filename) {
ArrayList<Double> res = new ArrayList<Double>();
Reader r;
try {
r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER) {
res.add(stok.nval);
}
stok.nextToken();
}
} catch (Exception E) {
System.out.println("+++ReadFile: " + E.getMessage());
}
return (res);
}
}
Here is the issue the Output:
00101001010101101011001011010101101001011010001011010010101101001001011010010
01011010010
I believe that both outputs should be the same and I see that there is a problem here, not sure why they aren't
I see that the way your are using System.out.print inside your RandomBinaryString(int n) is causing confusion. It is printing and appending to the String s. Try to avoid that. Replacing the System.out.print(s += '0'); and System.out.print(s += '1'); with s += '0'; and s += '1';in the RandomBinaryString will fix your output.
Use the snippet below in your code:
private static String RandomBinaryString(int n) {
String s = new String();
// Code goes here
// Create a random binary string of just ones and zeros of length n
for (int i = 0; i < n; i++) {
int y = randomOther.UI(0, 1);
if (y == 0) {
s += '0';// this line here was changed
} else {
s += '1';// and this line here was changed too
}
}
return (s);
}
Hope this helps!
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;
}
}
I started to learn java yesterday and I wrote the followind program which should print pairs of equal numbers, but when I run it I get
Exception in thread "main" java.lang.NullPointerException
at _aaaa.main(_aaaa.java:26)
Here is my program:
import java.util.*;
class pair {
int first, second;
pair() {
first = second = 0;
}
public void make_pair(int a, int b)
{
first = a;
second = b;
}
}
public class aaaa {
public static void main(String[] idontneedthis)
{
Scanner input = new Scanner(System.in);
int N = input.nextInt(), i, lg = 0;
int[] A = new int[5010];
pair[] B = new pair[5010];
for (N <<= 1, i = 1; i <= N; ++i)
{
int var = input.nextInt();
if (A[var] > 0)
{
B[++lg].make_pair(A[var], var);
A[var] = 0;
}
else
{
A[var] = i;
}
}
if (lg == 0) System.out.print("-1");
for (i = 1; i <= lg; ++i)
{
System.out.print(B[i].first + " " + B[i].second + "\n");
}
}
}
Please tell me what is wrong or why do I get this error. I mention that if I cut the line 26 ( B[++lg].make_pair(A[var], var); ) it will write -1.
Thank you!
You need to initialise the pairs in your array:
if (A[var] > 0) {
B[++lg] = new pair(); //here
B[lg].make_pair(A[var], var);
A[var] = 0;
}
This line:
pair[] B = new pair[5010];
creates an array of 5010 pairs but until you initialise them, they are all null.
Also note that since 5010 and N are not related, you could get an ArrayIndexOutOfBoundException depending on N.
This is how I would write it. The less said the better ;)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Pair {
final int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
#Override
public String toString() {
return first + " " + second;
}
}
public class Main {
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
int numOfPairs = input.nextInt();
List<Pair> pairs = new ArrayList<Pair>();
for(int i = 0; i < numOfPairs;i++) {
int first = input.nextInt();
int second = input.nextInt();
pairs.add(new Pair(first, second));
}
for (Pair pair : pairs)
System.out.println(pair);
}
}
pair[] B = new pair[5010];
Only allocates the space for 5010 B elements. You need to instantiate each element in that array.
for(int i = 0; i <B.length;i++)
{
B[i] = new pair();
}
Style things:
Class names start with upper case letters: AAAA not aaaa.
also star imports are bad:
import java.util.*;
replace with:
import java.util.Scanner;
import java.util.HashMap;
public class target
{
public static void hash(int []a,int sum)
{
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int i;
for (i = 0; i < a.length; ++i)
map.put(a[i], sum-a[i]);
for (i = 0; i < a.length; ++i)
if(map.containsValue(a[i]) && map.get(a[i])!=null)
{
System.out.println("("+a[i]+","+map.get(a[i])+")");
map.remove(a[i]);
}
}
public static void main(String[] args)
{
int []a={1, 2, 13, 34, 9, 3, 23, 45, 8, 7, 8, 3, 2};
hash(a,11);
}
}
I want to know if there is a better and more efficient solution that the above one. Complexity of this is n. Can I do better?
Your implementation misses duplicated pairs.
You could
sort the array
iterate from the start and for each element
calculate the required complement (sum - element)
do a reverse binary search (from the end of the sorted array) looking for that precise value
if found, remove both
It boils down to the observation that, with elements sorted:
n1 < n2 < n3 < n4 < n5 < n6
the most likely pairs are coming symmetrically from both ends to the middle. Now, the worst case is still bad, but at least you don't have the hashtable overhead
As I commented, your sollution is not O(N), because the containsValue make a search of all values stored at the HashMap. To solve it, I made a different approach using your solution:
public static void newVersion(int[] a, int sum){
HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
for (int i= 0; i< a.length; i++) {
map.put(sum - a[i], true);
}
for (int i = 0; i < a.length; i++) {
if (map.containsKey(a[i]) && map.get(a[i])) {
System.out.println("("+(sum-a[i])+","+a[i]+")");
map.put(a[i], false);
map.put(sum-a[i], false);
}
}
}
At the first step, it stores the "complement value" of each integer and at the second step it checks if the complement exists. If it exists, mark both pair as used.
This complexity is:
* O(N) for the first looping
* O(N) * (O(1) + O(1)) for the second loop and the containsValue and get.
* Finally: O(N) + O(N) .:. O(N) solution,
I have the following solution for this problem. The time complexity should be O(N) because the HashMap operations put, get and keySet are O(1).
import java.util.HashMap;
import java.util.Map;
/**
* Find a pair of numbers in an array given a target sum
*
*
*/
public class FindNums {
public static void findSumsForTarget(int[] input, int target)
{
// just print it instead of returning
Map<Integer, String> myMap = populateMap(input);
// iterate over key set
for (Integer currKey : myMap.keySet()) {
// find the diff
Integer diff = target - currKey;
// check if diff exists in the map
String diffMapValue = myMap.get(diff);
if(diffMapValue!=null)
{
// sum exists
String output = "Sum of parts for target " + target + " are " + currKey + " and " + diff;
System.out.println(output);
return; // exit; we're done - unless we wanted all the possible pairs and permutations
}
// else
// keep looking
}
System.out.println("No matches found!");
}
private static Map<Integer, String> populateMap(int[] input)
{
Map<Integer,String> myMap = new HashMap<Integer,String>();
for (int i = 0; i < input.length; i++) {
String currInputVal = myMap.get(input[i]);
if(currInputVal!=null) // value already exists
{
// append current index location to value
currInputVal = currInputVal + ", " + i;
// do a put with the updated value
myMap.put(input[i], currInputVal);
}
else
{
myMap.put(input[i], Integer.toString(i)); // first argument is autoboxed to Integer class
}
}
return myMap;
}
// test it out!
public static void main(String[] args)
{
int[] input1 = {2,3,8,12,1,4,7,3,8,22};
int[] input2 = {1,2,3,4,5,6,7,8,9,10};
int[] input3 = {2,-3,8,12,1,4,7,3,8,22};
int target1 = 19;
int target2 = 16;
// test
FindNums.findSumsForTarget(input1, target1);
FindNums.findSumsForTarget(input1, -1);
FindNums.findSumsForTarget(input2, target2);
FindNums.findSumsForTarget(input3, target1);
}
}
import java.util.*;
import java.io.*;
class hashsum
{
public static void main(String arg[])throws IOException
{
HashMap h1=new HashMap();
h1.put("1st",new Integer(10));
h1.put("2nd",new Integer(24));
h1.put("3rd",new Integer(12));
h1.put("4th",new Integer(9));
h1.put("5th",new Integer(43));
h1.put("6th",new Integer(13));
h1.put("7th",new Integer(5));
h1.put("8th",new Integer(32));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no.");
int no=Integer.parseInt(br.readLine());
Iterator i=h1.entrySet().iterator();
boolean flag=false;
while(i.hasNext())
{
Map.Entry e1=(Map.Entry)i.next();
Integer n1=(Integer)e1.getValue();
Iterator j=h1.entrySet().iterator();
while(j.hasNext())
{
Map.Entry e2=(Map.Entry)j.next();
Integer n2=(Integer)e2.getValue();
if(no==(n1+n2))
{
System.out.println("Pair of elements:"+n1 +" "+n2);
flag=true;
}
}
}
if(flag==false)
System.out.println("No pairs");
}
}
public static void hash1(int[] a, int num) {
Arrays.sort(a);
// printArray(a);
int top = 0;
int bott = a.length - 1;
while (top < bott) {
while (a[bott] > num)
bott--;
int sum = a[top] + a[bott];
if (sum == num) {
System.out.println("Pair " + a[top] + " " + a[bott]);
top++;
bott--;
}
if (sum < num)
top++;
if (sum > num)
bott--;
}
}
Solution: O(n) time and O(log(n)) space.
public static boolean array_find(Integer[] a, int X)
{
boolean[] b = new boolean[X];
int i;
for (i=0;i<a.length;i++){
int temp = X-a[i];
if(temp >= 0 && temp < X) //make sure you are in the bound or b
b[temp]=true;
}
for (i=0;i<a.length;i++)
if(a[i]<X && b[a[i]]) return true;
return false;
}
Recursively to find the subset whose sum is the targeted sum from given array.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static Set<List<Integer>> set = new HashSet<>();
public static void main(String[] args) {
int[] biggerArray = {1, 2, 1, 1};
int targetedSum = 3;
findSubset(biggerArray, targetedSum);
}
public static void findSubset(int[] biggerArray, int targetedSum) {
for (int i = 0; i < biggerArray.length; i++) {
List<Integer> subset = new ArrayList<>();
if (biggerArray[i] > targetedSum)
continue;
else
subset.add(biggerArray[i]);
if (i + 1 < biggerArray.length)
find(subset, i, biggerArray, targetedSum, i);
}
System.out.println(set);
}
public static List<Integer> find(List<Integer> subset, int startIndex, final int[] biggerArray, final int targetedSum, final int skipIndex) {
if (skipIndex == startIndex) {
find(subset, startIndex + 1, biggerArray, targetedSum, skipIndex);
return null;
}
int subsetSum = findSumOfList(subset);
int remainedSum = targetedSum - subsetSum;
int i = startIndex;
if (remainedSum == 0) {
set.add(subset);
return null;
}
if ((startIndex < biggerArray.length) && (biggerArray[startIndex] == remainedSum)) {
List<Integer> temp = new ArrayList<Integer>(subset);
temp.add(biggerArray[i]);
set.add(temp);
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] < remainedSum)) {
while (i + 1 <= biggerArray.length) {
List<Integer> temp = new ArrayList<Integer>(subset);
if (i != skipIndex) {
temp.add(biggerArray[i]);
find(temp, ++i, biggerArray, targetedSum, skipIndex);
}
else {
i = i + 1;
}
}
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] > remainedSum)) {
find(subset, ++i, biggerArray, targetedSum, skipIndex);
}
return null;
}
public static int findSumOfList(List<Integer> list) {
int i = 0;
for (int j : list) {
i = i + j;
}
return i;
}
}
We need not have two for loops. The match can be detected in the same loop while populating the map it self.
public static void matchingTargetSumPair(int[] input, int target){
Map<Integer, Integer> targetMap = new HashMap<Integer, Integer>();
for(int i=0; i<input.length; i++){
targetMap.put(input[i],target - input[i]);
if(targetMap.containsKey(target - input[i])){
System.out.println("Mathcing Pair: "+(target - input[i])+" , "+input[i]);
}
}
}
public static void main(String[] args) {
int[] targetInput = {1,2,4,5,8,12};
int target = 9;
matchingTargetSumPair(targetInput, target);
}
We can easily find if any pair exists while populating the array itself. Use a hashmap and for every input element, check if sum-input difference element exists in the hashmap or not.
import java.util.*;
class findElementPairSum{
public static void main(String[] args){
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sum key: ");
int sum=sc.nextInt();
for(int i=0; i<10; i++){
int x = sc.nextInt();
if(!hm.containsKey(sum-x)){
hm.put(x, 1);
} else {
System.out.println("Array contains two elements with sum equals to: "+sum);
break;
}
}
}
}