my code executes, but does not get any output - java

I am Jordan a high school student, i recently got a coding challenge/homework that goes like this: you have the numbers 1 to 18 and you need to find combinations of flowing numbers that are equal when you put an equal sign in between them and a plus sign between every number, for example: 1+2=3 or
4+6+7+8=9+10+11
I need to find six of these combinations but my program will not find any, please help.
public static void main(String[] args) {
int[] A = new int[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
boolean check;
int s = A[1];
int e = A[s+1];
int eq= A[s+1];
for(e=s+1;e==A[17];e++){
for(eq=s+1;eq==e;eq++){
if(Integer.sum(s, eq-1) == e) {
check = true;
}
if(check = true) {
System.out.println("start number is ---" + s + "equal number is ---" + eq + "end number is ---" + e);
i expect to get a starting point where to put the equal and an ending point for six combinations but instead i get nothing

Related

Stack Overflow on Random Integers

Where the commented section is, it says that there is a StackOverflowError - null. I am trying to get it to make random numbers to match up with an inputted value. The goal of this code is to do the following:
Accept a top number (ie 1000 in order to have a scale of (1-1000)).
Accept an input as the number for the computer to guess.
Computer randomly guesses the first number and checks to see if it is correct.
If it is not correct, it should go through a loop and randomly guess numbers, adding them to an ArrayList, until it guesses the input. It should check to see if the guess is already in the array and will generate another random number until it makes one that isn't in the list.
In the end, it will print out the amount of iterations with the count variable.
Code:
import java.util.*;
public class ArrNumGuess
{
public static Integer top, input, guess, count;
public static ArrayList <Integer> nums;
public static void main ()
{
System.out.println("Please enter the top number");
top = (new Scanner(System.in)).nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
input = Integer.parseInt(((new Scanner(System.in)).nextLine()).trim());
nums = new ArrayList<Integer>(); //use nums.contains(guess);
guess = (new Random()).nextInt(top) + 1;
nums.add(guess);
System.out.println("My first guess is " + guess);
count = 1;
if(guess != input)
{
guesser();
}
System.out.println("It took me " + count + " tries to find " + guess + " and " + input);
}
public static void guesser()
{
boolean check = false;
while(!check)
{
guess = (new Random()).nextInt(top) + 1; //Stack Overflow - null
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
else if(guess.equals(input))
{
check = true;
System.out.println("My guess was " + guess);
// nums.add(guess);
count++;
}
else
{
System.out.println("My guess was " + guess);
nums.add(guess);
count++;
}
}
}
}
In guesser() method, you're invoking itself:
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
There is quite a possibility it will never end. But all that is in while loop, so why not get rid of recurrence and do this in an iterative style?
OK - a different approach to your guesser for fun. Enumerate a randomized sequence of numbers in specified range (1 to 'top') and find the guess in the list whose index is effectively the number of "attempts" and return.
(BTW - #Andronicus answer is the correct one.)
/** Pass in 'guess' to find and 'top' limit of numbers and return number of guesses. */
public static int guesser(int guess, int top) {
List<Integer> myNums;
Collections.shuffle((myNums = IntStream.rangeClosed(1, top).boxed().collect(Collectors.toList())), new Random(System.currentTimeMillis()));
return myNums.indexOf(guess);
}
You are making it more complicated than it needs to be and introducing recursion unnecessarily. The recursion is the source of your stack overflow as it gets too deep before it "guesses" correctly.
There is a lot of sloppiness in there as well. Here's a cleaned up version:
import java.util.*;
public class Guess {
public static void main(String args[]) {
System.out.println("Please enter the top number");
Scanner scanner = new Scanner(System.in);
int top = scanner.nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
int input = scanner.nextInt();
if (input < 1 || input > top) {
System.out.println("That's not in range. Aborting.");
return;
}
ArrayList <Integer> nums = new ArrayList<>();
Random rng = new Random(System.currentTimeMillis());
while(true) {
int guess = rng.nextInt(top) + 1;
if (!nums.contains(guess)) {
nums.add(guess);
if (nums.size() == 1) {
System.out.println("My first guess is " + guess);
} else {
System.out.println("My guess was " + guess);
}
if (guess == input) {
System.out.println("It took me " + nums.size() + " tries to find " + guess);
break;
}
}
}
}
}

Java Random Number generator generate same number but when I compare them it is not same

I am very new to Java Programming. For example, even if I roll the same number i still lose the bet. If I roll like one and fine, I still win the bet amount. I am trying to fix that problem for hours. But can't figure it out. Please, someone, help me. Thanks in advance.
Here is my code.
public class Dice {
private int dice;
public Random number;
//default constructor
public Dice() {
number = new Random();
}
//To generate random number between 1 to 6. random starts from 0. there is no 0 on dice.
//By adding one, it will start at 1 and end at 6
}
//Method to check two dice
public boolean isequal(int dice1,int dice2) {
}
else
}
public class Playgame
{
//
}
public static void main(String[] args) {
//
}
}
{
return false;
}
}
userinput.close();
}
}
At least one problem is here (there may be others) :
if(obj1.isequal(obj1.play(), obj1.play()) == true)
{
System.out.println("You rolled a " + toString(obj1.play()) + " and a "
+ toString(obj1.play()) );
When you print the message, you are calling obj1.play() again and generating 2 new random numbers. If you need to use the value twice (once for comparison and once for printing) then you should store it in a variable.
int firstRoll = obj1.play();
int secondRoll = obj1.play();
if(obj1.isequal(firstRoll, secondRoll) == true)
{
System.out.println("You rolled a " + toString(firstRoll) + " and a "
+ toString(secondRoll) );
//...
Each call to obj1.play() return a different values.
Hence your test: obj1.isEqual(obj1.play(), obj1.play()) will mostly not return true.
no need for the dice class if it is to generate the random number and checks whether two number is equal or not. try the code below it will work
Random random = new Random();
int n1 = random.nextInt(6) + 1;
int n2 = random.nextInt(6) + 1;
System.out.println("You rolled a " + toString(n1)+ " and a " +toString(n2));
if (n1 == n2) {
double win = betmoney * 2;
System.out.println("You win $" + win);
startmoney += win;
} else {
startmoney -= betmoney;
System.out.println("You lose $" + betmoney);
System.out.println("You left only $" + startmoney);
}
problem with your code is your generating random numbers two times 1.during condition check and 2. in the sysout statement. your program is working fine only. but due to this your confusing yourself that it.
Each time you call ob1.play() method, it will give you different numbers.
in if clause:
if(obj1.isequal(obj1.play(), obj1.play()) == true)
will give you two random values that different from two random values in if block:
System.out.println("You rolled a " + toString(obj1.play()) + " and a " + toString(obj1.play()) );

Get the next sequence in an arithmetic or geometric progression

I want to make an application that takes a sequence of 3 numbers per line to produce and stops when it reaches a sequence of zeros and then prints if it's an arithmetic progression or geometric progression and the next number in the series.
Example input:
4 7 10
2 6 18
0 0 0
should output
AP 13
GP 54
here is my code I wanna know what's wrong with it and what are the possibilities that won't work with my code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
static String s="";
public static void main (String[] args) throws IOException
{
String c;
String a[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
c= br.readLine();
a = c.split(" ");
if(c.charAt(0)!='0'){
calc(a[1], a[2]);
}
}while((c.charAt(0))!='0');
printer(s);
}
public static void calc(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
if(y%x==0){
s += "GP" +" " + (y*(y/x)) + "z";
return;
}else{
s += "AP" + " " + (y + (y-x)) + "z";
return;
}
}
public static void printer(String s){
String p= "";
for(int i =0;i<=s.length()-1;i++){
if(s.charAt(i)!='z'){
p+= s.charAt(i);
}else{
System.out.println(p);
p= "";
}
}
}
}
Your problem it that you discover progression type incorrectly. For example, 0 4 8 is obviously AP, but your algorithm will say it is GP. Another example: 8 4 2 is GP, but 2%4 will return false, saying it is AP. Also, you don't proceed cases when offered sequence is not progression at all.
It is absolutely clear that all 3 numbers should be involved. Suppose that integer numbers a, b, c form AP or GP, and you need to discover which progression it is. Simple math can be used:
If they form AP, then a + c = b + b. Next element is c + c - b
If they form GP, then a * c = b * b. Next element is c * c / b
(Please notice how + is changed to *, and - to /, when you switch from AP to GP).
Your code works on the assumption that if two consecutive numbers of a 3 number series is divisible, the series is a GP and that if it's not, it has to be an AP. This assumption is wrong. There are many cases in which it will not be true, such as a series 0,3,6. It is an AP, not a GP. So instead of sending 2 parameters to the function calc(), you should send all three numbers as parameters, and check as follows:
if((a+c)==(2*b))
{//AP
}
else if((a*c)==(b*b))
{//GP
}
These above are the proper check for Arithmetic and Geometric progressions. Also while checking if the inputs are all 0, you are only checking for the first element. Instead you have to see if all three of the elements are 0. Your code might not work in the case of 0,3,6 or 0,2,4 or 0,1,2. So instead you have to check like this:
int flag=0;
for(int i=0;i<3;i++)
if(Integer.parseInt(a[i]))
flag=1;
if(flag==1)
{//continue prog
}
else
{//Terminate prog as input is 0,0,0
}

Number guessing game keeps repeating same questions and guesses incorrectly

If you run the the game you can see that certain numbers the game cannot guess correctly. For example if your number is 13 the game will loop two times too many and will also guess your number as 12 instead of 13. I think this is an issue with the counting but I've tried tracing the loops repeatedly but cannot find the error. I think the issue mainly lies within my while loop.
//import statements
import java.util.Scanner;
public class Numbers
{
public static void binarySearch()
{
int position=0;
String answer;
int upper_BOUND=100;
int lower_BOUND=0;
Scanner input=new Scanner(System.in);
while( (lower_BOUND <= upper_BOUND))
{
position = (lower_BOUND + upper_BOUND) / 2;
System.out.println("Is your value greater than " + position + "?");
answer=input.next();
if((upper_BOUND-lower_BOUND<=1))
{
break;
}
if (answer.equals("no")) // If the number is > key, ..
{ // decrease position by one.
upper_BOUND = position --;
}
if(answer.equals("yes"))
{
lower_BOUND = position ++; // Else, increase position by one.
}
}
System.out.println("Is your number " + position + "?");
String answer2=input.next();
System.out.println(position+" is the answer.\n Thank you for playing the guessing game.");
//else
// System.out.println("Bruh pick a number from 1 to 100 ");
}
}
......
tester class
public class NumberGuesser
{
public static void main(String[] args)
{
int[ ] num = new int [100];
// Fill array
for (int i = 0; i <= 99; i++)
num[i]=i;
//The search method
Numbers.binarySearch();
}
}
Your issue should be with the increment that you do in "lower_BOUND = position ++; " here what happens is when you increment the position value, the "++" first increments and then assigns the value to position variable. The lowerbound is not actually assigned the incremented value of position but old value of positon. So please make a change to "lower_BOUND = ++ position ; "
Like below
if(answer.equals("yes"))
{
lower_BOUND = ++ position ; // Else, increase position by one.
}
And also my suggestion is to check your " if((upper_BOUND-lower_BOUND <= 1))" condition. I guess the condition should be like this " if((upper_BOUND-lower_BOUND == 0)) "
And please remove unused code in your "NumberGuesser" class, this will confuse people who are trying to answer your question.

Sets using bit strings in Java trouble

public class BitStringOperations3
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
int setA = 0;
int setB = 0;
int elementsSetA = 0;
int elementsSetB = 0;
System.out.println ("How many integers are in set A?");
elementsSetA = in.nextInt ();
while (elementsSetA > 9 || elementsSetA < 0)
{
System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
elementsSetA = in.nextInt();
}
System.out.println ("How many integers are in set B?");
elementsSetB = in.nextInt ();
while (elementsSetB > 9 || elementsSetB < 0)
{
System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
elementsSetB = in.nextInt();
}
for (int i = 1; i <= elementsSetA; i++)
{
System.out.println ("Please enter integer number " + i + " in set A: ");
setA = add(setA, in.nextInt() );
}
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = add(setB, in.nextInt () );
}
}
public static boolean setContainsValue (int set, int value)
{
boolean setContainsValue = (set & maskForValue) != 0;
return true;
}
public static int addValueToSet (int set, int newValue)
{
set = set | maskForValue;
return set;
}
public static void printSet (int set, int value)
{
int mask = 1;
System.out.print ("{");
for (int i = 0; i<= 9; i++)
{
if(( mask & set ) == 1)
System.out.print(i + " " );
int maskForValue = 1 << value;
set >>= 1; //set = (set >> 1);
}
System.out.println ("} ");
}
}
I am having trouble with an assignment for school. We are given the universal set U = {0-9}. I have to gather user input for both sets, and then use bit strings (we are not allowed to use the Set or HashSet classes in java) to store the sets and perform operations on them, such as complement, Set A union Set B and such. I know how to do those, but my code does not convert Sets A and B into the memory correctly and therefore, I cannot perform any operations on them. Help will be gladly appreciated! Thanks in advance. :)
Edit 1:
Alright, I read your ideas and tried to implement them as good as I could, and I have given the result above. This program really pushes me out of my comfort zone and I really appreciate all the help.
First of all, do yourself a favour and create helper methods. Then concentrate only on making them correct:
public static boolean contains(int set, int value) {
//return true if value bit is 1 in set
}
public static int add(int set, int newValue) {
//add newValue to set and return it
}
Afterwards you can express your logic more clearly:
if ( contains(set, 1) ) {
//print 1
}
Some general hints:
Don't use Math.pow() as that is made for floating-point numbers. To get a power of 2 as an integer, use bit shifting:
int maskForValue = 1 << value;
To check if a certain bit is set, find the mask for that bit and use &. This zeros out all bits except for the bit you're checking.
boolean setContainsValue = (set & maskForValue) != 0;
To set a bit in a bit field, find the mask for that bit and use |. This ensures that that bit becomes 1.
set = set | maskForValue;
Edit
As to your direct problem, take a look at this:
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = in.nextInt ();
}
You're overwriting setA and setB every time. In the end, setA and setB will contain the last value the user specified. Then later, you do this:
for (int i = 0; i <=9; i++)
setB |= (int)pow(2.0, i-1);
Which just ignores the user's input and overwrites all bits 0-9 (though in an unsafe way!). So of course what the user inputs is irrelevant.
Get rid of the latter for loops and then store the input like this (using the helper methods I described above):
for (int i = 1; i <= elementsSetB; i++)
{
System.out.println ("Please enter integer number " + i + " in set B: ");
setB = add(setB, in.nextInt());
}
Edit 2
You seem to be having problems understanding where I'm coming from with my idea of these "helper" methods. If this is the first time you've worked with methods that have parameters, sorry for clouding up the issue. But they allow you to focus on getting one piece of functionality working at a time. I'll expand on what I mean more here:
public static boolean setContainsValue(int set, int value) {
//return true if the bit string (or bit set) represented by the "set" parameter
//contains the value stored in the "value" parameter
//see the FIRST and SECOND bullet points above for how to do this
}
public static int addValueToSet(int originalSet, int valueToAdd) {
//add the value stored in the "valueToAdd" parameter to the set represented by the
//"originalSet" parameter and return the result
//see the FIRST and THIRD bullet points above for how to do this.
}
I'll even write some tests for you too. The methods above haven't been implemented properly until at least all of the following print true:
int set = 0;
System.out.println( ! contains(set, 1) ); //make sure set doesn't contain 1
set = addValueToSet(set, 1);
System.out.println( contains(set, 1) ); //make sure set now contains 1
System.out.println( !contains(set, 2) ); //make sure set doesn't contain 2
set = addValueToSet(set, 2);
System.out.println( contains(set, 1) ); //make sure set still contains 1
System.out.println( contains(set, 2) ); //make sure set now contains 2
First, you need a class (this is object-oriented programming, right?) to contain the "DigitSet".
public DigitSet {
private BitSet digits;
public DigitSet() {
// digits contains one bit for each digit
digits = new BitSet(10);
}
... rest of DigitSet code goes here, like ...
/**
* Check if this set contains a particular digit.
*/
public boolean contains(int value) {
// check to see if value is a valid input (0-9)
// look in digits to see if the "right" bit is set.
}
public void set(int value) {
// check to see if value is a valid input (0-9)
// set the "right" bit in digits to 1.
}
public void clear(int value) {
// check to see if value is a valid input (0-9)
// set the "right" bit in digits to 0.
}
public DigitSet union(DigitSet other) {
// construct a "new" output DigitSet.
// Walk through all of the digits in "this" set
// if a digit is set in this set, set it in the output set.
// Walk through all of the digits in the "other" set
// if a digit is set in the other set, set it in the output set.
}
public String toString() {
// return a display string based on the set "digit" bits
}
}
Then the rest is just input handling and "perform the operation"
public static void main(String[] args) {
DigitSet first = new DigitSet();
// read in the values for the first digit set, for each value
// set the digit in first like so
first.set(value);
DigitSet second = new DigitSet();
// read in the values for the second digit set, for each value
second.set(value);
DigitSet result = first.union(second);
System.out.println("Result: " + result.toString());
}

Categories

Resources