Simplify If Condition

May 24, 2014

I m trying to simplify an if condition as much as possible and i m curious if it can be made more short then i managed to .The problem is simple , a integer number with 3 digits is generated and the user is asked to input another 3 digits integer number ... One of the conditions that need to be verified is if all the digits in each number match but not exactly ( aka 123 and 132 ) .Using only an if statement to verify this what is the most short condition that can be checked to identify when the digits in a 3 digits number match the digits of another 3 digits integer number (not interested if they match exactly) .

The simplest condition i managed to find is :

else if (guessDigit1 + guessDigit2 + guessDigit3
== lotteryDigit1 + lotteryDigit2 + lotteryDigit3
&& (guessDigit1 == lotteryDigit1 || guessDigit1
== lotteryDigit2 || guessDigit1 == lotteryDigit3)
&& (guessDigit2 == lotteryDigit1 || guessDigit2
== lotteryDigit2 || guessDigit2 == lotteryDigit3)) {
System.out.println("Match all digits: you win $3,000");}

Is there a better(shorter ) condition that can be used ?

View Replies


ADVERTISEMENT

How To Simplify Classes By Using Interfaces And / Or Inheritance

Apr 6, 2014

I am trying to figure out how I can most easily make it easier to make new types of units in my game. I have buildings and ships, and would like to know how I could make it easy to add new units. I have been recently told about interfaces, and have worked with inheritance a little bit.

What I would like to able to do is have it so that all of the variables and methods common to all ships could be stored in a superclass or interface, and same with the buildings. I would also like to be able to assign behaviours to the buildings and ships, maybe as interfaces, which could contain all of the methods and variables required for the functions of that ship or building.

For example, creating a new type of building that can shoot, build ships, and can regenerate nearby ships. So it would possible inherit all of the variables and methods common to all buildings, such as health, image, x, y, getX(), getY() etc. But it would then also gain the variables and methods essential for its functionality, such as shootRange, shoot(), regenRate, etc.

How could this best be achieved?

View Replies View Related

Simplify Two Large Methods Into One Similar Method?

Jan 4, 2015

Right now I have 12 methods, each roughly 40 lines long, and I am contemplating whether I should simplify some of the pairs (12 methods, but every other method is very similar to each other, so 6 pairs) into one method.

The main pro of simplifying them is that my class will be much smaller, right now its about 555 lines of code. However a con is that it might not be as straight forward, at first glance at least.

Here is what I am talking about. Two original methods that are very similar:

void rotateRightClockwise(int rotations){//rotates FRONTS's RIGHT! CONFIRMED
String a, b, c;//temp values
for(int i = 1; i <= rotations; i++){//confirmed
a = cube.cube[1][2].square[2];//3
b = cube.cube[1][2].square[5];//6
c = cube.cube[1][2].square[8];//9

[Code] ....

The only difference between these two methods, other than the last chunk for each method, is the I have to change the 2nd square bracket, [], values from lines 9-23 for cube[][]. That's it. So I am thinking of combining them into something like this...

private void rotateRight(int rotations, int x, int y){
String a, b, c;//temp values
for(int i = 1; i <= rotations; i++){//confirmed
a = cube.cube[1][2].square[2];//3
b = cube.cube[1][2].square[5];//6
c = cube.cube[1][2].square[8];//9

[Code] .....

And then after calling this similar method, I would finish off the last chunk from each methods, since they are too different (ie lines 26-38).

The reason why I ask this is because I am trying to build up my portfolio and I want to know if the employer would look at this and say "that was a good move by compacting your code" or "this is not that straight forward".

View Replies View Related

Ending The Run After If A Condition Is Not Met?

May 24, 2014

For an assignment

-I am too write a program that checks if 3 numbers (scannerinputted) are three sides of a triangle if not just ignore it.

-If they are the 3 sides to a triangle tell what kinda triangle it is Right/scalene/equilateral etc.

-ignore the 3 numbers if they are <=0

if(side1+side2>side3 && side1+side3>side2 && side2+side3>side1)
System.out.println("This is a Triangle.");
else
System.out.println("Not a Triangle.");

How can I make the program stop immediately if the else statement is checked. I have more "if statements afterward.

so it would say.

"This not a triangle"

"This is scalene or isosceles"

how can I get this output.

"This is not a triangle" and stop there.

View Replies View Related

For Loop With Condition

May 11, 2014

[public static void PrintNum () {

int i;
int j = 0;
for (i =100; j<5; i=i)j=100-(i-=1);
System.out.println(i);
} ]

I'm not following how it calculated to 95 since I'm confused with this

part i=i)j = 100-(i-=1);

View Replies View Related

JSF :: How To Check Condition In Xhtml

Mar 26, 2014

I need to display button based on the condition in xhtml page.

using JSF2 & richface 4.0
<c:forEach items="#{empList}" var="emp">

How to check condition like empList.size > 0 in xhtml?

if list is having value, need to show buttons.

View Replies View Related

Coding Own Classes - If Condition?

Jun 9, 2014

public int getIndexOfAMonster(String nameToGet){
int retValue = -1; //default is not found
for (int i = 0; i <= numberOfMonsters - 1; i++)
if (monsters[i].getName().equals(nameToGet))
retValue = i;
return retValue;
}

1.What does the if-condition do?If the name of a monster in the array is equal to the name stored in the variable, return the monster's assigned value.

2.What does the for loop do? The loop condition simply loops through the whole arraylists. (In other words, it simply checks each Monster contained in the lists).

3.Assuming that the driver code compiles, explain what it’s use is? If the name of the monster is the same as the variable passed unto this method, return the number assigned to that Monster.

View Replies View Related

If Condition Matches Multiple Times

Feb 16, 2015

I'm working on a problem that requires me to generator all possible word combinations based on a 7-digit number as input. Many of the generated "words" will be nonsense, but some with be "NEWCARS", "TAKEOUT", etc... This problem mimics the phone number a company would use to support clients remember that number.

I completed the exercise, but I would like to explore more elegant solutions. Specifically, I've used an IF-THEN-ELSE condition inside of a FOR loop. Here is my working code:

package com.johnny_v.exercises.telephone;
public class WordGenerator {
public static void main(String[] args) {
int numOfTimes = 2187;
String two = "ABC";
String three = "DEF";
String four = "GHI";

[code].....

I receive StringIndexOutOfBoundsException exceptions. I it's because multiple conditions are matched. For example, the indexSix is reset to 0 when row is a multiple of 9. Because row is also a multiple of 3, this condition also executes and then increments "indexSix".

View Replies View Related

Why If Condition Not Working When Compare Two Strings

May 11, 2014

Is there a different logic in Java for if statements when it comes to conditions? I mean my attempt to compare a String variable and a String attribute of a class that is on an array of objects was frustrated someway. It will not enter the if block. The two strings are equal. I displayed the values of each strings before the if evaluation and they are equal. The simbol I used was the ==, and I also tried the string.equals(string variable) as well as the compareTo() == 0 option but none of those worked. I wish I knew what it is the way to compare two strings.

View Replies View Related

Servlets :: How To Create Deadlock Condition

Mar 2, 2014

How can we create deadlock condition on our servlet? Does calling doGet() from doPost() and vice versa really cause a deadlock? Or, does it cause a StackOverflowException?

View Replies View Related

While Getting Input From User Check A Second Condition

Apr 22, 2015

Is it possible to wait for an input for a user and check in the meantime if something else is true?

Now if the server in the meantime says: there is no input needed and tells it the client.

Could the client now somehow change from

input.readLine() to another Method say: quit() ?

I am stuck there because I know the server sends: quit to the client1 but the client2 cannot react because it still waits for an input for the user.

Maybe something with Thread.sleep ?

View Replies View Related

Search Algorithm Not Reaching End Condition

Apr 29, 2015

I am using what is known as a Depth First Search to solve a maze using my own Stack created class for an assignment. The reason I believe I am getting this error is because my program is never meeting the `finishSpot` condition. I have used the debugger and it looks like it is infinitely stuck at the Point before the `finishSpot`. My logic seems to be mostly correct except until the point where my maze solver tries to finish the maze, so i just need meeting that last condition that is causing my program to crash.

This is a sample maze:

*****
*s* *
* * *
* f*
*****

Here is my Main which uses my created Stack class.

//Creates a Stack and determines the start and endpoints.
public static void solveDFS( char [][] maze ){
LinkedStack stack = new LinkedStack();
Point currentSpot = findPoint( maze,'s' );
Point finishSpot = findPoint( maze, 'f' );
findPath( maze,currentSpot, finishSpot,stack );

[Code] ....

I made a mistake it says my program is crashing which it is not, but simply not meeting the condition.

View Replies View Related

How To Create A New Array For Each Numbers That Are Passing Through Condition

May 26, 2014

how to translate it into Java language due to lack of experience (2 weeks). My solution I've formed in my head is: create a new array for the numbers that are in improvement and then declare a "max" variable. Check which array's length is higher and print that length. What I don't know to do is: I don't know how to create a new array for each numbers that are passing through the condition.

Note: I couldn't find anything on internet about my problem so that's why I'm here.

My code is this one:

class MyClass {
static int progresie=0;
public static void longest_improvement(Integer[] grades) {
for(int i=0;i<grades.length-1;i++){
if(grades[i]<=grades[i+1]){
progresie ++;
}
}
System.out.println(progresie);
}
}

View Replies View Related

Validate Postal Code Based On Condition

Feb 18, 2014

How can I validate the postal code based on this condition...

9999 may not be used for US province .

If the street province is Mexico or Argentina or Brazil the street postal code must be 9999 ....

View Replies View Related

Changing Background Image Of JPanel When Certain Condition Meets?

Apr 22, 2015

In my program one of the panel has a background image and I need that background image to be updated/refresh or changed whenever the panel reaches certain number of clicks

here's the code

Constructor/gui
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;;
 public class demo { 
JFrame frame = new JFrame ("Idle Game Test!");
JPanel backGroundPanel = new JPanel ();

[code].....

also is there other way to access those static variables? the way i implemented them works but i do think there are other ways that are more suitable or better but i cant figure out.

View Replies View Related

Instance Of Operator - No Output Generated Since If Condition Fails

Feb 2, 2014

As per my knowledge, the instance of operator compiles only if the reference type compared to class type are in the same inheritance tree. According to that, below code should not compile but it compiles FINE!!.

Output:No output generated since the if condition fails

public class InstanceOfTest implements Inter{ 
public static void main(String arg[]){
Inter iot = new InstanceOfTest();
if(iot instanceof Someone) //here Inter(interface) and Someone(class) are not in the same inheritance tree.
System.out.println("iot is a Someone");
}
}
 
interface Inter{}
class Someone{}

View Replies View Related

Running Java Application - Analyze Traffic Condition

Jun 18, 2014

I have a java application which uses Google Maps to analyze the traffic condition. But sometimes it can be run and work properly, sometimes not. On some computers on which there is installed java, the program can be run, and on some, again with installed java (jre), exactly the same version, the program can not be run. For example the application first run well on my desktop computer, connected in a LAN, and then stopped working well when run. But when I use laptop which uses the WiFi and run the same computer using VMWare, if I connect to the desktop on which the program can not be run, on the laptop the same program can be run well, in the same room, but using the Wifi.

View Replies View Related

Input Validation - Where Condition Is A Word From Set And Value Is A Positive Integer

Mar 18, 2015

I am trying to create a program that first asks the user for an input in the form: condition = value, where condition is a word from the set {limit, deficient, abundant, perfect, prime}, and value is a positive integer. Then it verifies the input. If the input is invalid it prints a message indicating that and terminates. If the input is valid it prints a table with the number of abundant, deficient, perfect and prime numbers less than or equal to N, where N = 1, 2, 3, ..., limit.

My problem is with the input validation. i want it to read the value as a string and verify if it's integer.

Here is my code

import java.util.Scanner;
 public class Factors
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int n, f, fsum, p=0, a=0, d=0,pe=0,limit=0,abundant=0, deficient=0;
System.out.print("Enter stoping condition (condition = value): ");
String cond = scan.next();

[Code] ....

View Replies View Related

Keeping Track Of Product With Highest Price - Loop Condition

Sep 22, 2014

The Program prompts the user to enter the number of products in the product catalog. The program should then prompt the user for the name and the price of each product in the product catalog. Once all of the products have been entered, the program should output the product information (name and price) of the most expensive product in the catalog. Your solution to keep track of the product with the highest price.

import java.util.Scanner;
public class ProductTester {
private static final String price = null;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the number of Products: ");
int count = console.nextInt();

[Code] ....

View Replies View Related

Could Program Fail With Race Condition By Concurrent Threads In A Multi Thread Environment

Feb 18, 2014

I have a task of returning US holiday based on the given date and this utility will be used in a multi thread environment. I have written as below, how to know if my code breaks at any given point by multiple threads

Declared Enum

public enum Holiday {
CHRISTMASDAY("Christmas Day"),
GOODFRIDAY("Good Friday"),
INDEPENDENCEDAY("Independence Day"),
LABORDAY("Labor Day"),
NONE("None");

[code]...

I tried to test this with few concurrent threads, and noticed that the DB call is made for the very first time or when the year being requested is not same as the cached year. But I wanted to see, if this is properly synchronizing and would not fail in any case. My intention is to make a singleton HolidayCalendar, and also synchronized well enough so that every thread using this class gets the required data without blocking each other.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved