elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


  Mostrar Temas
Páginas: [1]
1  Programación / Java / Problema con bucle while junto con condiciones if en: 2 Diciembre 2016, 22:21 pm
Tengo un problema que yo creo que cualquier programador intermedio lo puede solucionar. El caso es que tengo un bucle while en el que si pongo en el input (por ejemplo) "suma" y añado los números se realiza la resta pero después vuelve a ejecutarse el while y sale como si hubiera puesto después nada en el input y me sale el error (y después, obviamente, se vuelve a ejecutar).


Código:
    import java.util.Scanner;
   
    public class MainClass {
    public static void main(String[] args){
   
    Scanner scan = new Scanner(System.in);
   
    System.out.println("\tCalculadora");
    System.out.println("--------------------------");
   
   
    int condicion = 1;
    while(condicion == 1){
   
    System.out.println("¿Qué operación desea realizar?");
    System.out.println("Suma");
    System.out.println("Resta");
    System.out.println("Salir");
   
    String operacion = scan.nextLine();
   
    if(operacion.toLowerCase().equals("suma")){
    System.out.println("Introduce los números que quieres sumar");
   
    System.out.println("Número 1: ");
    double numero1 = scan.nextDouble();
   
    System.out.println("Número 2: ");
    double numero2 = scan.nextDouble();
   
    Suma suma = new Suma(numero1, numero2);
   
    System.out.println("Resultado: " + suma.getSuma());
   
    }else if(operacion.toLowerCase().equals("resta")){
    System.out.println("Introduce los números que quieres restar");
   
    System.out.println("Número 1: ");
    double numero1 = scan.nextDouble();
   
    System.out.println("Número 2: ");
    double numero2 = scan.nextDouble();
   
   
    Resta resta = new Resta(numero1, numero2);
   
    System.out.println("Resultado: " + resta.getResta());
   
    }else if(operacion.toLowerCase().equals("salir")){
    System.out.println("¡Adiós! ;)");
    condicion = 0;
   
   
    }else{
    System.out.println("Error: Puede ser que hayas escrito mal la palabra. Vuelve a intentarlo");
    }
    }
    }
    }


Por consola:
           Calculadora
    --------------------------
    ¿Qué operación desea realizar?
    Suma
    Resta
    Salir
    SUMA (input)
    Introduce los números que quieres sumar
    Número 1:
    1 (input)
    Número 2:
    1 (input)
    Resultado: 2.0
    ¿Qué operación desea realizar?
    Suma
    Resta
    Salir
    Error: Puede ser que hayas escrito mal la palabra. Vuelve a intentarlo
    ¿Qué operación desea realizar?
    Suma
    Resta
    Salir

Si necesitáis las otras dos clases os las envio, pero creo que no hace falta, por eso no las añado.


¡Saludos! ;)


2  Programación / Java / Problema con if de comparación de Strings en: 26 Noviembre 2016, 14:34 pm
Comparo dos Strings que son iguales y me sale error ;(

Al ejecutarlo:
   Calculadora
--------------------------
¿Qué operación desea realizar?
Suma
SUMA (Esta línea la he insertado yo al ejecutar)
Error


Código:
import java.util.Scanner;

public class MainClass {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);

System.out.println("\tCalculadora");
System.out.println("--------------------------");

System.out.println("¿Qué operación desea realizar?");
System.out.println("Suma");

String operacion = scan.nextLine();

if(operacion.toLowerCase() == "suma"){
System.out.println("Introduce los números que quieres sumar");
System.out.println("Número 1: ");
double numero1 = scan.nextDouble();
System.out.println("Número 2: ");
double numero2 = scan.nextDouble();

Suma suma = new Suma(numero1, numero2);

System.out.println(suma.getSuma());

}else{
System.out.println("Error");
}

}
}

Creo que para resolver esto no se necesita la otra clase que he creado, pero si la necesitáis os la pasaré ;)

Saludos :D
3  Programación / Scripting / [PYTHON] No puedo importar un módulo empaquetado correctamente en: 18 Diciembre 2015, 22:04 pm
He estado programando un programa de aventura de texto y tengo el siguiente problema:
Yo importo el módulo empaquetado y me lo ejecuta directamente y no me deja reutilizarlo más. Es raro:
import scenes.scene1
Se ejecuta directamente, sin haberlo llamado y cuando lo llamo no me hace caso.
¿Alguna solución? Si necesitan que pase el código lo paso.
Gracias  ;)
4  Sistemas Operativos / GNU/Linux / Compatibilidad wireless de distro instalada en un pendrive en: 25 Noviembre 2015, 16:31 pm
Lo que necesitaría saber es como hago para que un pendrive que tenga instalado una distro(ojo, no me refiero a un pendrive con un instalador de x distro), sea compatible con cualquier tarjeta wireless de cualquier pc.
Esto lo digo para no tener que conectar el pc que utilizo a un cable ethernet.
5  Programación / Scripting / (PYTHON) No logro entender una parte del código en: 3 Agosto 2015, 12:56 pm
Hola buenas. El problema esque no logro entender una parte del código del ejercicio 35 del libro "Learn Python The Hard Way". Os pongo todo el código y después os selecciono la parte que no entiendo:

Todo el código:
Código
  1. # -*- coding: utf-8 -*-
  2.  
  3. from sys import exit
  4.  
  5. def gold_room():
  6.    print "This room is full of gold. How much do you take?"
  7.  
  8.    next = raw_input("> ")
  9.    if "0" in next or "1" in next:
  10.        how_much = int(next)
  11.    else:
  12.        dead("Man, learn to type a number.")
  13.  
  14.    if how_much < 50:
  15.        print "Nice, you're not greedy, you win!"
  16.        exit(0)
  17.    else:
  18.        dead("You greedy bastard!")
  19.  
  20.  
  21. def bear_room():
  22.    print "There is a bear here."
  23.    print "The bear has a bunch of honey."
  24.    print "The fat bear is in front of another door."
  25.    print "How are you going to move the bear?"
  26.    bear_moved = False
  27.  
  28.    while True:
  29.        next = raw_input("> ")
  30.  
  31.        if next == "take honey":
  32.            dead("The bear looks at you then slaps your face off.")
  33.        elif next == "taunt bear" and not bear_moved:
  34.            print "The bear has moved from the door. You can go through it now."
  35.            bear_moved = True
  36.        elif next == "taunt bear" and bear_moved:
  37.            dead("The bear gets pissed off and chews your leg off.")
  38.        elif next == "open door" and bear_moved:
  39.            gold_room()
  40.        else:
  41.            print "I got no idea what that means."
  42.  
  43.  
  44. def cthulhu_room():
  45.    print "Here you see the great evil Cthulhu."
  46.    print "He, it, whatever stares at you and you go insane."
  47.    print "Do you flee for your life or eat your head?"
  48.  
  49.    next = raw_input("> ")
  50.  
  51.    if "flee" in next:
  52.        start()
  53.    elif "head" in next:
  54.        dead("Well that was tasty!")
  55.    else:
  56.        cthulhu_room()
  57.  
  58.  
  59. def dead(why):
  60.    print why, "Good Job!"
  61.    exit(0)
  62.  
  63. def start():
  64.    print "You are in a dark room."
  65.    print "There is a door to your right and left."
  66.    print "Which one do you take?"
  67.  
  68.    next = raw_input("> ")
  69.  
  70.    if next == "left":
  71.        bear_room()
  72.    elif next == "right":
  73.        cthulhu_room()
  74.    else:
  75.        dead("You stumble around the room until you starve.")
  76.  

start()

La parte del código que no entiendo:

    
Código
  1.   elif next == "taunt bear" and not bear_moved:
  2.            print "The bear has moved from the door. You can go through it now."
  3.            bear_moved = True
  4.        elif next == "taunt bear" and bear_moved:
  5.            dead("The bear gets pissed off and chews your leg off.")

Los dos elif en el bucle "while True:" dan de resultado True (porque antes del "while True:" hay un bear_moved = False). He hecho pruebas y cuando cambio el primer elif a que de resultado False me sale siempre el primer elif cuando pongo "taunt bear", y se supone que el que tiene de resultado True tiene que salir en vez de uno que sale de resultado False. Estoy muy confundido y necesito ayuda, ya que no sé como entenderlo. Gracias por adelantado ;D

Mod: Los códigos deben ir en etiquetas GeSHi
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines