I created this program to run infinite times asking the user to enter a choice(rock or paper or scissor), which seems to work fine. The problem is no else ....if or if ....else statements are satisfied. Whatever input i give it just prints out the else statement in the else statement, (Enter a valid choice). I cant find the mistake i made so ill link my code below..... Thanks in advance.  import java.util.Scanner; import java.util.Random;  public class apples {     public static void main(String args[]){          Scanner input = new Scanner(System.in);         Random number = new Random();          String rps[] = {"rock", "paper", "scissor"};         String player;         String ai;         int rand, pscore=0, aiscore=0;          while(1 &lt; 2){         System.out.println("Take your pick \nrock \npaper \nscissor");         player = input.nextLine();          rand = number.nextInt(3);         ai = rps[rand];          System.out.println(ai);          if(player == ai){             pscore+=0;             aiscore+=0;             System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);             System.out.print("\n");             continue;         }else{             if(player == "rock" &amp;&amp; ai == "paper"){                 aiscore+=1;                 pscore+=0;                 System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);                 System.out.print("\n");                 continue;             }else if(player == "rock" &amp;&amp; ai == "scissor"){                 pscore+=1;                 aiscore+=0;                 System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);                 System.out.print("\n");                 continue;             }else if(player == "paper" &amp;&amp; ai == "rock"){                 pscore+=1;                 aiscore+=0;                 System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);                 System.out.print("\n");                 continue;             }else if(player == "paper" &amp;&amp; ai == "scissor"){                 aiscore+=1;                 pscore+=0;                 System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);                 System.out.print("\n");                 continue;             }else if(player == "scissor" &amp;&amp; ai == "rock"){                 aiscore+=1;                 pscore+=0;                 System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);                 System.out.print("\n");                 continue;             }else if(player == "scissor" &amp;&amp; ai == "paper"){                 aiscore+=0;                 pscore+=1;                 System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);                 System.out.print("\n");                 continue;             }else{                 System.out.println("Enter a valid choice");                 System.out.print("\n");                 continue;             }         }         }       } }
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
37488
This works just fine:      protected void txtTest_Load(object sender, EventArgs e)     {         if (sender is TextBox) {...}      }   Is there a way to check if sender is NOT a TextBox, some kind of an equivalent of != for "is"?  Please, don't suggest moving the logic to ELSE{} :)
87341
An array is defined to be maxmin equal if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array.   if the input array is {} , isMaxMinEqual should return false (array must have at least two different elements) status = false; if the input array is {2}, isMaxMinEqual should return false (array must have at least two different elements). if the input array is {1,1,1,1,1,1}, isMaxMinEqual should return false (array must have at least two different elements).  if the input array is {2,4,6,8,11}, isMaxMinEqual should return true (Both max value(11) and min value 2 appear exactly one time). if the input array is {-2,-4,-6,-8,-11}, isMaxMinEqual should return true(Both max value(-2) and min value -11 appear exaclty one time).   I wrote the class MaxMin which satisfied the above condition.  public class MaxMin {  public static void main(String args[]) {     System.out.println("The result is: " + isMaxMinEqual(new int[]{2, 2})); }  public static boolean isMaxMinEqual(int[] a) {     boolean status = false;     int count = 0;     if (a.length &lt; 2) {         status = false;         return status;     }     for (int i = 1; i &lt; a.length; i++) {         if (a[i - 1] != a[i]) {             count++;         }     }      int max = a[0];     int min = a[0];     for (int i = 0; i &lt; a.length; i++) {         if (a[i] &gt; max) {             max = a[i];         } else if (a[i] &lt; min) {             min = a[i];         }     }      int maxCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == max) {             maxCount++;         }     }      int minCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == min) {             minCount++;         }     }     System.out.println(count);     System.out.println("max is: " + max);     System.out.println("min is: " + min);     System.out.println("Max Count is: " + maxCount);     System.out.println("Min Count is: " + minCount);      if (maxCount == minCount &amp;&amp; count &gt;= 1) {         status = true;     }      return status; } }
106949
I'd love some other opinions on what's more efficient in this code. Basically in the following code, there's a setInterval loop and I need 4 requirements to be true before the code runs in the loop. So in v.1 I wrote an if statement checking all 4. Worked fine.  Then I switched to just using try/catch, with the code I want to execute sitting in try{}. The logic was that during each loop, an exception would be generated but suppressed for each invalid condition. On the final loop where all conditions are true, the code executes and clears the interval.  Either works. I like the try/catch method because there's less conditional code that I need to write and worry about breaking. But I'm worried that try/catch is really inefficient, especially in a setInterval() loop hitting at 100ms. What are some opinions of other bright minds here on SO?  Try/Catch  var intvar = setInterval(function(){ try{         clearInterval(intvar);      jQuery('#'+nav[pageid].t1+'&gt;a').replaceWith(jQuery('&lt;span&gt;'+jQuery('#'+nav[pageid].t1+'&gt;a').text()+'&lt;/span&gt;'));      //set display classes for nav     jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav     jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav }catch(err){} },100);   IF Block  var intvar = setInterval(function(){  if(typeof jQuery == 'function' &amp;&amp; typeof nav == 'object' &amp;&amp; typeof pageid != 'undefined' &amp;&amp; typeof document.getElementById('leftnav') == 'object'){     clearInterval(intvar);     jQuery('#'+nav[pageid].t1+'&gt;a').replaceWith(jQuery('&lt;span&gt;'+jQuery('#'+nav[pageid].t1+'&gt;a').text()+'&lt;/span&gt;'));      //set display classes for nav     jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav     jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav }  },100);
88238
I have problem in some JavaScript that I am writing where the Switch statement does not seem to be working as expected.  switch (msg.ResultType) {   case 0:     $('#txtConsole').val("Some Val 0");     break;   case 1:     $('#txtConsole').val("Some Val 1");     break;   case 2:     $('#txtConsole').text("Some Val 2");     break; }   The ResultType is an integer value 0-2 and I can see that in FireBug.  In all cases, the switch transfers control to the final break statement which means all the logic is completely skipped.  What am I missing?
119341
I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve. int firstNumber; string sign; int secondNumber; int answer;  Console.WriteLine(&quot;Input Number:&quot;); firstNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  Console.WriteLine(&quot;Input Sign:&quot;); sign = Console.ReadLine(); Console.Clear();  Console.WriteLine(&quot;Input Second Number:&quot;); secondNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  switch (sign) {     case &quot;+&quot;:         answer = firstNumber + secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;-&quot;:         answer = firstNumber - secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;*&quot;:         answer = firstNumber * secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;/&quot;:         answer = firstNumber / secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     default:         Console.WriteLine(&quot;Invalid Input&quot;);     break; }
40567
I'm working on a project where i find i'm checking for the following in many, many places:  if(item.Rate == 0 || item.Rate == null) { }   more as a curiousity than anything, what's the best way to check for both cases?  I've added a helper method which is:  public static bool nz(object obj) {     var parsedInt = 0;     var parsed = int.TryParse(obj.ToString(), out parsedInt);     return IsNull(obj) || (parsed &amp;&amp; parsedInt == 0); }   Is there a better way?
27797
I'm not the most experienced person when it comes to commands. I worked out how to do stuff like when holding x you have y effect. I wanted to think of something that gave other people an effect when hit. Here is what I came up with but I got stuck when it said it couldn't execute the command.  /scoreboard objective add nokill dummy  /scoreboard objective add poi dummy  /scoreboard players set [player] nokill 1  /scoreboard players add @a poi 1 {SelectedItem:{id:minecraft:diamond_sword,display:{Name:{Poison sword}}}}  /execute @a[score_poi_min=1] ~ ~ ~ /effect @p[score_nokill_max=1,r=5] {HurtTime:1} minecraft:poison 10 1
16336
Given the following code (that doesn't work):  while True:     #snip: print out current state     while True:         ok = get_input("Is this ok? (y/n)")         if ok.lower() == "y": break 2 #this doesn't work :(         if ok.lower() == "n": break     #do more processing with menus and stuff   Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?
1905
I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.   Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.  Anyhow -   I was developing a basic shopping cart which could contain an ArrayList of Book objects. In order to implement the addBook(), removeBook(), and hasBook() methods of the Cart, I wanted to check if the Book already existed in the Cart. So off I go -  public boolean equals(Book b) {     ... // More code here - null checks     if (b.getID() == this.getID()) return true;     else return false; }   All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much.  Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following:  public boolean hasBook(int i) {     Book b = new Book(i);     return hasBook(b); }  public boolean hasBook(Book b) {     // .. more code here     return this.books.contains(b); }   All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following:  public boolean equals(Object o) {     Book b = (Book) o;     ... // The rest goes here    }   Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly  was  a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?
26673
Switch statement fallthrough is one of my personal major reasons for loving switch vs. if/else if constructs. An example is in order here:  static string NumberToWords(int number) {     string[] numbers = new string[]          { "", "one", "two", "three", "four", "five",            "six", "seven", "eight", "nine" };     string[] tens = new string[]          { "", "", "twenty", "thirty", "forty", "fifty",            "sixty", "seventy", "eighty", "ninety" };     string[] teens = new string[]         { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",           "sixteen", "seventeen", "eighteen", "nineteen" };      string ans = "";     switch (number.ToString().Length)     {         case 3:             ans += string.Format("{0} hundred and ", numbers[number / 100]);         case 2:             int t = (number / 10) % 10;             if (t == 1)             {                 ans += teens[number % 10];                 break;             }             else if (t &gt; 1)                 ans += string.Format("{0}-", tens[t]);         case 1:             int o = number % 10;             ans += numbers[o];              break;         default:             throw new ArgumentException("number");     }     return ans; }   The smart people are cringing because the string[]s should be declared outside the function: well, they are, this is just an example.  The compiler fails with the following error:   Control cannot fall through from one case label ('case 3:') to another Control cannot fall through from one case label ('case 2:') to another   Why? And is there any way to get this sort of behaviour without having three ifs?
39427
Switch statements are typically faster than equivalent if-else-if statements (as e.g. descibed in this ) due to compiler optimizations.  How does this optimization actually work? Does anyone have a good explanation?
35663
My controller code is as follows -          for(String resStr : responseArray){             if(resStr.indexOf('r_error_str') != -1){                 responseString += resStr.substring(resStr.indexOf('=') + 1);                  responseString += '\n';             }         }   but when i display this 'responseString ' String using 'apex:outputLabel or apex:outputText or as Exception message '\n' is not converting in new line. Whole String is coming in one line.  Can anyone explain why is this happining
82893
Is it true that I cannot have OR or AND operators in if statements in APEX?  I have an object that has a picklist Code__c, and I need to execute some code if the code is set to either A or B.  How would I write something like:  if(pc.Code__c = 'A' || pc.Code__c = 'A') { }   Tia.
16473
Consider the class below that represents a Broker:  public class Broker {     public string Name = string.Empty;     public int Weight = 0;      public Broker(string n, int w)     {         this.Name = n;         this.Weight = w;     } }   I'd like to randomly select a Broker from an array, taking into account their weights.  What do you think of the code below?  class Program     {         private static Random _rnd = new Random();          public static Broker GetBroker(List&lt;Broker&gt; brokers, int totalWeight)         {             // totalWeight is the sum of all brokers' weight              int randomNumber = _rnd.Next(0, totalWeight);              Broker selectedBroker = null;             foreach (Broker broker in brokers)             {                 if (randomNumber &lt;= broker.Weight)                 {                     selectedBroker = broker;                     break;                 }                  randomNumber = randomNumber - broker.Weight;             }              return selectedBroker;         }           static void Main(string[] args)         {             List&lt;Broker&gt; brokers = new List&lt;Broker&gt;();             brokers.Add(new Broker("A", 10));             brokers.Add(new Broker("B", 20));             brokers.Add(new Broker("C", 20));             brokers.Add(new Broker("D", 10));              // total the weigth             int totalWeight = 0;             foreach (Broker broker in brokers)             {                 totalWeight += broker.Weight;             }              while (true)             {                 Dictionary&lt;string, int&gt; result = new Dictionary&lt;string, int&gt;();                  Broker selectedBroker = null;                  for (int i = 0; i &lt; 1000; i++)                 {                     selectedBroker = GetBroker(brokers, totalWeight);                     if (selectedBroker != null)                     {                         if (result.ContainsKey(selectedBroker.Name))                         {                             result[selectedBroker.Name] = result[selectedBroker.Name] + 1;                         }                         else                         {                             result.Add(selectedBroker.Name, 1);                         }                     }                 }                   Console.WriteLine("A\t\t" + result["A"]);                 Console.WriteLine("B\t\t" + result["B"]);                 Console.WriteLine("C\t\t" + result["C"]);                 Console.WriteLine("D\t\t" + result["D"]);                  result.Clear();                 Console.WriteLine();                 Console.ReadLine();             }         }     }   I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.  Is there a more accurate algorithm?  Thanks!
12184
I'm trying to get an understanding of what the the java keyword this actually does. I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
73349
When I use an Iterator of Object I use a while loop (as written in every book learning Java, as Thinking in Java of Bruce Eckel):  Iterator it=...  while(it.hasNext()){     //... }   but sometime i saw than instead somebody use the for loop:  Iterator it=... for (Iterator it=...; it.hasNext();){     //... }   I don't' understand this choice:    I use the for loop when I have a collection with ordinal sequence (as array) or with a special rule for the step (declared generally as a simple increment counter++).  I use the while loop when the loop finishes with I have'nt this constraints but only a logic condition for exit.   It's a question of style-coding without other cause or it exists some other logic (performance, for example) that I don't' know?  Thanks for every feedback