I am a student currently using java and I am having a hard time programming a high and low guessing game. I cannot use looping or "while" code. Any thoughts? This is what I have as of now:   public class FinalProject1  {    public static void main(String [] args)      {         System.out.println("Number Guessing Game 1-1000\nGuess a number");        guess();     }    public static int random()      {         int x = (int)(1000*Math.random() + 1);         return x;     }    public static void guess()    {        int num = random();       int tries = 0;       Scanner keyboard = new Scanner(System.in);       String inputString = keyboard.nextLine();       int input = Integer.parseInt(inputString);        if (input &gt; num)        {           System.out.println("Guess a higher number");           inputString = keyboard.nextLine();       }        else if (input &lt; num)        {           System.out.println("Guess a lower number");           inputString = keyboard.nextLine();       }        else if (num == input)        {           System.out.println("You Win");    }  }  }
122060
Can anybody suggest programming examples that illustrate recursive functions? There are the usual old horses such as Fibonacci series and Towers of Hanoi, but anything besides them would be fun.
121
I always thought Java uses pass-by-reference. However, I've seen a couple of blog posts (for example, ) that claim that it isn't (the blog post says that Java uses pass-by-value). I don't think I understand the distinction they're making. What is the explanation?
39845
Using Java 6, how can I implement a ? It is very easy and possible in Ruby. How can I get similar in Java?
10097
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.
45967
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards.  #include &lt;iostream&gt; #include &lt;vector&gt;  using namespace std;  int main() {     vector&lt;char&gt; deck;     char suit[] = {'h','d','c','s'};     char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'};     for (int j=0; j&lt;13; j++) {         for (int i=0; i&lt;4; i++) {             deck.push_back(card[j] suit[i]);         }            }      return 0; }   I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.
33117
Your (honest) opponent choose a random number from 1 to 13 inclusive. You have to guess the number, and you win if the guess is correct. If not, your opponent either reduces the number chosen by one or increases it by 1, and you guess again.  The question is, what is the minimum # of attempts necessary to guarantee a win for you.  I am not able to get a handle on the problem.  Also, (a new variant just thought of), how many guesses should be allowed for a fair or "nearest to fair" game ?
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
30265
I have been trying to solve , but in vain. Please help.     You are given two boxes with a number inside each box. The two numbers   are different but you have no idea what they are. You pick one box to   open; read the number inside; and then guess if the number in the   other box is larger or smaller. You win if you guess correctly, and   lose otherwise. Is there anyway that you can win the game with more   than 50% chances no matter what the two numbers are?
31170
i am instantiating prefab cars ... the clones had a random countdown timer with each one off them and its working very well but the its not  decreasing its not counting down the timer is inside the spawn method the spawn method is inside the WHILE loop and the while loop is inside the UpDate() ... i  tried  to move the countdown to Update() but didnn't worked ... any ideas ...Thank You!  void Update() {     p -= Time.deltaTime;           while (carNumber &lt; cars &amp;&amp; p &lt;= 0 )         {              SpawnCars();             print(carNumber);             p = 5;                    }  }   and this is the spawn method:   public void SpawnCars() {     if (spawnAllowed)     {         // choose a random strat point 1/6              randomSpawnPoint = Random.Range(0, spawnPoints.Length);         // choose a random car 1/6         randomSpawnCars = Random.Range(0, Cars.Length);         // clone randomly a car(1/6) from a random pre_set-points(1/6)         GameObject obj = Instantiate(Cars[randomSpawnCars], spawnPoints[randomSpawnPoint].position, Quaternion.Euler(-90, 180, 0)) as GameObject;         // carNumber will count how many cloned car          carNumber++;         // destroy the  cloned car after N sec        // Destroy(obj, 8);         // every cloned car will take a tag with it         obj.gameObject.tag = "select" + k;         k++;         rcf = obj.GetComponent&lt;RayCastForward&gt;();         //textCDT         time = Random.Range(4f, time);         TextMesh txt = FindObjectOfType&lt;TextMesh&gt;();   //the Timer:         time -= Time.deltaTime;         coolDown = time.ToString("0");         txt.text = ""+coolDown;      } }   edit: i forgot to tell that the timer  is inside SpawnCars().
23692
Consider a game where one would roll a random integer between $1$ and $N_0$ where $N_0 \ge 1$. The newly randomly generated number is now the new &quot;upper limit&quot; of the game, the game continues by rolling a random number between $1$ and the randomly generated number. This game continues until the randomly generated number is 1. Here is an example of how it can look like. Consider $N_0 = 1000$ $$N_1 = Random(1, N_0) = Random(1, 1000) = 623$$ $$N_2 = Random(1, N_1) = Random(1, 623) = 366$$ $$N_3 = Random(1, N_2) = Random(1, 366) = 303$$ $$N_4 = Random(1, N_3) = Random(1, 303) = 190$$ $$N_5 = Random(1, N_4) = Random(1, 190) = 52$$ $$N_6 = Random(1, N_5) = Random(1, 52) = 13$$ $$N_7 = Random(1, N_6) = Random(1, 13) = 1$$ $$END$$ The Length of the example game was 7, it took 7 rolls to reach 1. Given the Starting Upper Limit $N_0$, what is the average amount of rolls needed to reach 1? I have tried to write Python code to help with this problem and it seems this follows a Logarithmic Pattern with the function to approximate the amount is $f(N_0) = 1.0168287465013466\ln(N_0) + 1.4731706151125865$
45336
When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.  As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:  if (condition) {     do     {        ...     } while (same condition); }   or the inverse (if inside the while), it makes me wonder if they actually wrote it that way or if they added the if statement when they realized the loop didn't handle the null case.  I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?
74579
I am writing this java program to find all the prime numbers up to num using the Sieve of Eratosthenes, but when I try to compile, it says I can't use a long var as an array index, and it expects an int var in its place. But I'll be working with large numbers, so I can't use int. What can I do?  import java.util.*; import java.lang.*;  public class t3{     public static void main(String[] args){         long num = 100;          //declaring list and filling it with numbers         ArrayList&lt;Long&gt; numlist = new ArrayList&lt;Long&gt;();         for(long x=2 ; x&lt;num ; x++){             numlist.add(new Long(x));         }          //sieve or eratosthenes         for(long x=0 ; x&lt;Math.sqrt(num) ; x++){             for(long y=x+1 ; y&lt;numlist.size() ; y++){                 if(numlist[y]%numlist[x] == 0){                     numlist.remove(y);                 }             }         }          //print list         for(Object item : numlist){             System.out.println((Long)item);         }     } }
76661
I'm reading an algorithms book and I came across a code example for a primality test. The problem is that I couldn't understand the condition for the :  public static boolean isPrime( int N ) {         if (N &lt; 2) return false;         for ( int i = 2; i * i &lt; N; i++ ) {             if ( N % i == 0 )                 return false;         }          return true; }   If we multiply i by itself we would miss a lot of numbers to check. So if we want to check if n=10 is prime or not, then we would quickly end the loop by i=3. I know that the idea is finish the loop as early as possible, but how do we guarantee that by using that condition we are actually checking all possible divisors and the rest that we omitted are never going to be divisors?  This condition seems quite common and popular but I really wasn't able to understand it or find an interpretation. I understood the condition i &lt; n/2 but not that one. I hope I'm not stupid!
111663
In a set of if/elif/else/fi statements, I have made 'else' present the user with an error message, but I also want it to take the user back to the question which was asked before the if/else statements so that they can try to answer it again.  How do I take the user back to a previous line of code? Or, if this is not possible, is there another way to do this?
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
100872
High Low game is one where one person picks a number between a range (say 1-100) and another person have to guess it. With each guess, s/he is told whether the guess was high, low or correct.  If the person picking the number picks it at random, then the best strategy would be to use binary search algorithm (start at middle of range, and then keep dividing sample space in half) to minimize the number of guesses.   (1) If the players however are playing adversarially, i.e. Person picking the number wants to maximize the guesses taken by guesser and Guesser wants to guess the number in minimum guesses; what is best strategies for both of them?  (2) Also, related question : If it is known that Person picking the number is trying to defeat the Binary search algorithms, what would be the best strategy to guess the number in least amounts of guesses?
16499
If yes, on which operating system, shell or whatever?  Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems):  public class ExitCode {     public static void main(String args[]) {         System.exit(Integer.parseInt(args[0]));     } }   Running it on Linux and bash, it returns always values less equal 255, e.g. (echo $? prints the exit code of the previous executed command)  &gt; java ExitCode 2; echo $? 2  &gt; java ExitCode 128; echo $? 128  &gt; java ExitCode 255; echo $? 255  &gt; java ExitCode 256; echo $? 0  &gt; java ExitCode 65536; echo $? 0     EDITED: the (only, so far) answer below fully  explain what happens on UNIXes. I'm still wondering about other OSes.