Mostrando entradas con la etiqueta switch. Mostrar todas las entradas
Mostrando entradas con la etiqueta switch. Mostrar todas las entradas

martes, 25 de febrero de 2014

Generar número aleatorio en Java Math.random() – dinero – Shipping – Rooms


Si queremos generar unnúmero aleatorio en java lo que haremos será hacer uso del métodoMath.random(). Éste método devuelve un valor aleatorio de tipodoublecon signo positivo, mayor o igual a 0.0 e inferior a 1.0. Es útil si queremos que en nuestras aplicaciones suceda algo dependiendo al valor aleatorio generado. Tambiénes posible aumentar el rango del valor aleatorio, de manera que no sea solo mayor o igual a 0.0 e inferior a uno, sino que seamayor o igual a 0 y menor a un número que queramos.¿Como se haría? solo debemos multiplicar el método Math.random() por dicho número.

Vamos generar 5 valores aleatorios en un rango mayor o igual que 0 y menor a 5 con un ciclo for y veamos los resultados:


public class NumeroAleatorio {
static double numero;

public static void main(String args[]){
for(int i = 0; i 5; i++){

numero = Math.random() * 5;
System.out.print(numero);
System.out.println("");
}
}
}

También podemos generar valores enteros aleatorios, imaginemos que tenemos un dado, cuando lo lanzamos hay 6 posibilidades, puede ser 1,2...6. Simulemos un dado con el Math.random



public class NumeroAleatorio {
static int numero;

public static void main(String args[]){

numero = (int) (Math.random() *6) + 1;
System.out.print(numero);
System.out.println("");
}
}

En éste caso la variable numero será deltipo entero, como el métodoMath.random retorna un valor del tipodouble haremos uso deloperador cast(int). El operador cast lo que hace esforzar a un dato, variable o expresión a convertirse en un nuevo tipo de dato, en nuestro caso en un entero. Es importante saber que la operación(int) (Math.random() *6)retornara un valor entero mayor o igual que 0 y menor que 6. Pero nuestro dado necesita un valor entre 1 y 6 por estosumamos 1 a nuestra operación(int) (Math.random() *6) + 1. De ésta manera podremos simular un dado en java.

¿Como sería si quiero que ocurra algo dependiendo del valor generado? Lo que haremos será hacer uso de los operadores relacionales. Generemos un valor aleatorio en que si éste es menor que 0.5 diga Hola mundo! y si es menor que 1 diga Hello World!.


public class NumeroAleatorio {
static double numero;

public static void main(String args[]){

numero = Math.random();
if(numero 0.5)
System.out.println("Hola mundo!");
else
System.out.println("Hello World!");
}
}

¿Y si queremos usar elMath.random junto a unasentencia switch se podría? ¡Seguro que si!


public class NumeroAleatorio {
static int numero;

public static void main(String args[]){

numero = (int) (Math.random() * 5) + 1;
switch(numero){
case 1:
System.out.println("Venezuela");
break;
case 2:
System.out.println("Argentina");
break;
case 3:
System.out.println("Colombia");
break;
case 4:
System.out.println("Ecuador");
break;
case 5:
System.out.println("Peru");
break;
}

}
}

Lo que hacemos es nuevamente utilizar eloperador cast para convertir el valor generado en un entero, luego hacemos una sentencia switch con 5 posibilidades, en nuestro caso imprimimos en pantalla el nombre de un país dependiendo del número generado.

También te podría interesar:
60+ Manuales y libros sobre programación para descargar
Medir el tiempo de ejecución en Java
De sistema decimal a sistema binario en c++ y Java
3 libros sobre programacion orientada a objetos

caraccidentlawyer EMAIL BULK SERVICE Car Insurance Companies Online Classes chicago hair laser removal structured annuity settlement Car Insurance Quotes Utah cloud identity and access management buy structured settlements HOME PHONE INTERNET BUNDLE Online College Course colorado mesothelioma lawyers Donate Your Car Sacramento Online casino Hire php programmers Hard drive Data Recovery Services state of california car insurance holland michigan college structured settlement brokers Donate Car to Charity California Car Insurance in South Dakota asbestos lung cancer Social media examiner st louis mesothelioma attorney Donate your car for kids Criminal lawyer Forex Trading Platform semi truck accident lawyers Business finance group Psychic for free car insurance quotes mesothelioma charities Casino Mobile casino Make money online Australia harddrive data recovery services CRIMINAL DEFENSE ATTORNEYS FLORIDA Computer science classes online Criminal defense attorneys Florida saskatchewan auto insurance Proud Italian cook Bankruptcy lawyer donating used cars to charity home phone internet bundle Custom Christmas cards motorcycle accident attorney chicago donate your car for money Casino reviews mesothelioma claim AUTOMOBILE ACCIDENT ATTORNEY houston mesothelioma attorney new mexico mesothelioma lawyer refinance with poor credit personal injury solicitor la personal injury lawyer Business management software Cheap Domain Registration Hosting Live casino MET AUTO DUI lawyer anti spam appliance Hire php developers Neuson best accident attorneys Hire php developer SELL ANNUITY PAYMENT Donate Your Car for Kids Social media strategies Dwi lawyer personal injury firm Best social media platforms for business Donate your Car for Money georgia truck accident lawyer Massage School Dallas Texas mesothelioma attorney florida workplace accident attorney fast cash for house Service business software Cheap auto insurance in VA royalty free images stock mesothelioma lawyer texas ONLINECLASSES Health Records Personal Health Record Auto Accident Attorney Seo company Donate Old Cars to Charity CHEAP CAR INSURANCE FOR LADIES tennessee mesothelioma lawyer california motorcycle accident lawyer Christmas cards sell structured settlement calculator best mesothelioma lawyers structured settlement annuity companies los angeles auto accident attorneys personal injury law firm Donate Cars Illinois Criminal defense lawyer purchase structured settlements cell cycle regulation ppt Php programmers for hire Psd to html Psd to WordPress california law lemon Photo Christmas cards motor insurance quotes mesothelioma attorney directory Php programmers Annuity Settlements Business VOIP Solutions Seo companies Injury Lawyers New social media platforms Personal Injury Lawyers onlineclasses Social media platforms for business Adobe illustrator classes Custom WordPress theme designer mesothelioma lawyer virginia DONATE CARS IN MA Met Auto Seo services Best Seo company Online Motor Insurance Quotes Best social media platforms Online Christmas cards WORLD TRADE CENTER FOOTAGE Learning adobe illustrator verizon sip WebEx costs WordPress themes for designers WordPress hosting domain name yahoo Donating used cars to charity MORTGAGE ADVISER florida car insurance company Social media platforms Italian cooking school CAR INSURANCE QUOTES COLORADO Social media management Tech school Html email Nunavut Culture motorcycle accident attorney sacramento PHD IN COUNSELING EDUCATION LIFE INSURANCE CO LINCOLN meso lawyer ROYALTY FREE IMAGES STOCK Social media campaigns Car insurance in South Dakota mesothelioma lawyers san diego email bulk service VIRTUAL DATA ROOMS mesothelioma attorney pharmacist jobs in chicago online colledges Sell Annuity Payment Cheap car insurance in Virginia mesothelioma settlements amounts CAR INSURANCE QUOTES UTAH benchmark lending Cheap Car Insurance in Virginia Donate Cars in MA WordPress theme designers Online Stock Trading Asbestos Lung Cancer Donating Used Cars to Charity NEUSON best criminal lawyer in arizona business email web hosting workers compensation lawyer los angeles car accident lawyers life insurance quotes business administration masters See more at http//wwwginfostopnet/ Social media tools mesothelioma ct Mesothelioma Law Firm Donate Car for Tax Credit register free domains emergency response plan ppt World Trade Center Footage How to Donate A Car in California Paperport promotional code mesothelioma information BEST CRIMINAL LAWYER IN ARIZONA mesothelioma trial attorney DONATE YOUR CAR FOR MONEY Motor Replacements Asbestos Lawyers houston motorcycle accident lawyer Structures Annuity Settlement Online colledges Car Insurance Quotes Colorado Email Bulk Service mesothelioma law suit Dayton Freight Lines Donate a Car in Maryland buy gift card structured settlement company Donating a Car in Maryland cheap auto insurance in va Criminal Defense Attorneys Florida Best Criminal Lawyers in Arizona Cheap Car Insurance for Ladies car insurance quotes pa Dallas Mesothelioma Attorneys Life Insurance Co Lincoln Holland Michigan College mesothelioma lawyer dallas federal criminal defense attorney Online Colleges Paperport Promotional Code MOTOR REPLACEMENTS Forensics Online Course HOW TO DONATE A CAR IN CALIFORNIA Donate a car in Maryland low credit line credit cards uk homeowner loans donate your car for kids Psychic for Free mesothelioma lawyer houston business voip solutions CAR INSURANCE IN SOUTH DAKOTA Low Credit Line Credit Cards Car Insurance Quotes MN Attorney michigan motorcycle accident lawyer Cheap Auto Insurance in VA city college in miami supportpeachtreecom Forensics online course illinois law lemon Home Phone Internet Bundle DONATE CAR FOR TAX CREDIT donate car for tax credit PHD on Counseling Education better conferencing calls Car Insurance Quotes PA Royalty Free Images Stock mesothelioma personal injury lawyers world trade center footage Webex Costs new york mesothelioma law firm Register Free Domains Better Conference Calls Futuristic Architecture Mortgage Adviser Car Donate Virtual Data Rooms accident attorney in los angeles

domingo, 30 de junio de 2013

Sentencia switch (Switch case) – Free – Money – Justicia

La sentencia switch nos permitirá elegir entre varias opciones lo que queremos realizar dentro de nuestro programa, en pocas palabras un menú.

Ejemplo:


#include iostream
#include stdlib.h

using namespace std;

int main(){
int variable;
cout "Ingresa los numeros 1 o 2 y presiona enter" endl;
cout "Que quieres hacer?" endl;
cout "1 te dira hola en ingles" endl;
cout "2 te dira hola en frances" endl;
cout "3 cerrara el programa" endl;
cin variable;
switch(variable){
case 1:
cout "hello" endl;
break;
case 2:
cout "bonjour" endl;
break;
case 3:
return 0;
break;
default:
cout "No has apretado uno de los casos posibles" endl;
break;
}
system("PAUSEnull");
return 0;
}


Como nuestras opciones son números enteros, declaramos una variable de éste tipo (int). Luego, le indicamos al usuario con una serie de mensajes el funcionamiento de cada opción, finalmente realizamos la estructura del "switch".


Nunca olvidar los "break" luego de cada "case".

DONATE YOUR CAR FOR MONEY Casino reviews World Trade Center Footage Dwi lawyer CRIMINAL DEFENSE ATTORNEYS FLORIDA Psd to html Donate Your Car Sacramento Cheap Auto Insurance in VA personal accident attorney Make money online Australia Italian cooking school World trade center footage Seo services SELL ANNUITY PAYMENT Motor Replacements Online Classes BEST CRIMINAL LAWYER IN ARIZONA DONATING A CAR IN MARYLAND FORENSICS ONLINE COURSE Mobile casino Cheap Car Insurance for Ladies Register Free Domains Online casino structured settlement cash out mesothelioma lawyer houston georgia truck accident lawyer structured settlement annuity companies DONATING USED CARS TO CHARITY Proud Italian cook Social media strategies Service business software Casino lease management software motorcycle accident lawyer san diego Asbestos Lawyers DUI lawyer Car Donate auto insurance cost by state mesothelioma attorney directory car accident lawyer san bernardino houston motorcycle accident lawyer Data Recovery Raid city college in miami Car Insurance Companies Hire php developer att call conference mesothelioma attorney illinois Forex Trading Platform Criminal lawyer data recovery raid mesotheloma Bankruptcy lawyer Live casino Hard drive Data Recovery Services Business finance group Hire php developers Insurance Companies donate old cars to charity Car Insurance Quotes MN Life Insurance Co Lincoln massage school dallas texas Christmas cards Annuity Settlements Donate Car for Tax Credit Hire php programmers Donate Your Car for Kids Seo company Personal Injury Law Firm Php programmers structured settlement quote car insurance in south dakota Dayton Freight Lines Personal Injury Lawyer what is structured settlement bus accident attorneys Email Bulk Service Criminal defense lawyer Better Conference Calls LIFE INSURANCE CO LINCOLN cheap car insurance in virginia Php programmers for hire Social media examiner peritoneal mesothelioma sell your structured settlement payments DONATE CARS IN MA ONLINECLASSES auto accident attorney Torrance forensics online course Holland Michigan College Best social media platforms for business st louis mesothelioma attorney Criminal defense attorneys Florida Car Insurance Quotes PA fast cash for house seattle mesothelioma lawyer accident attorneys orange county Donate car to charity California Computer science classes online Custom Christmas cards Donating Used Cars to Charity Seo companies CAR INSURANCE QUOTES PA personal injury attorney torrance auto accident attorney New social media platforms Car Insurance Quotes Utah Social media platforms for business Paperport promotional code structured settlement blog Custom WordPress theme designer PHD on Counseling Education Mesothelioma Law Firm Best Seo company average mesothelioma settlement verizon sip Auto Mobile Insurance Quote Asbestos Lung Cancer WEBEX COSTS car insurance quotes colorado Business management software workers compensation lawyer los angeles Car Insurance Quotes Colorado Best social media platforms buy gift card domain name yahoo life insurance quotes Online Christmas cards Html email holland michigan college Gas/Electricity mesothelioma law firms donate your car for kids mesothelioma law suits Dallas mesothelioma attorneys Photo Christmas cards WordPress themes for designers WordPress hosting WordPress theme designers business voip solutions Psd to WordPress DONATE A CAR IN MARYLAND Social media management Tech school webex costs Social media platforms car insurance companies criminal defense attorneys florida philadelphia mesothelioma lawyer google adsense domain registration yahoo Nunavut Culture CAR INSURANCE QUOTES MN Neuson HOLLAND MICHIGAN COLLEGE Best Criminal Lawyers in Arizona sell my structured settlement structured settlement investments injury lawyers tucson car accident attorney Adobe illustrator classes PAPERPORT PROMOTIONAL CODE Cheap car insurance for ladies mesothelioma attorney florida Automobile Accident Attorney Learning adobe illustrator Criminal Defense Attorneys Florida florida car insurance company Social media tools Social media campaigns Donate Car to Charity California Donate Cars in MA How to Donate A Car in California mesothelioma trial attorney Sell Annuity Payment DONATE CAR FOR TAX CREDIT Structures Annuity Settlement Donating a Car in Maryland Futuristic Architecture motorcycle accident attorney chicago los angeles auto accident attorneys canada personals yahoo ANNUITY SETTLEMENT home phone internet bundle Health Records Personal Health Record Virtual Data Rooms anti spam appliance Donate a Car in Maryland life insurance co lincoln donate your car for money Cheap Domain Registration Hosting attorney lawyer mesothelioma Personal Injury Lawyers Donate Cars Illinois PSYCHIC FOR FREE Donate car for tax credit small business administration sba buying structured settlements refinance with bad credit sell structured settlement calculator Online Motor Insurance Quotes structured settlement buyers meso lawyer Online Colleges Paperport Promotional Code Online College Course Massage School Dallas Texas CAR DONATE Psychic for Free motor replacements VIRTUAL DATA ROOMS Donate Old Cars to Charity Low Credit Line Credit Cards Cheap domain registration hosting Dallas Mesothelioma Attorneys Donate your Car for Money DONATE YOUR CAR SACRAMENTO Met Auto Forensics Online Course Home Phone Internet Bundle injury lawyers west palm beach Royalty free images stock best consolidation loan student phd in counseling education Royalty Free Images Stock criminal defense federal lawyer caraccidentlawyer california law lemon Car Insurance in South Dakota Webex Costs Cheap Car Insurance in Virginia mesothelioma law firm Email bulk service business voice mail service Auto Accident Attorney truck accident attorney los angeles Mortgage Adviser PhD in counseling education futuristic architecture personal injury firm Donate a car in Maryland structure settlements Car Accident Lawyers mesothelioma help Online Stock Trading Criminal lawyer Miami mesothelioma lawyer texas Motor Insurance Quotes Car Insurance Quotes primary pulmonary hypertension Injury Lawyers