Buscar este blog

jueves, 6 de junio de 2013

SUMAR TRES DIMENSIONES, MIL PERSONAS,LIST SET, TRON, MISTERMIND PROGRAMADO EN JAVA.

EJERCICIO PARA SUMAR UNA MATRIZ DE TRES DIMENSIONES:
package ejercicio130517;
public class matriz3d {
public static void main(String[] args) {
int i, j, k;
int matriz[][][] = new int [3] [3] [3];
for(i = 0; i < matriz.length; i++);{
for(j = 0; j < matriz[i].length; j++);{
for(k = 0; k < matriz[i][j].length; k++);{
matriz[i][j][k] = i;
System.out.println(i);
}}} }}
EJERCICIO PARA CONTABILIZAR "MIL PERSONAS"
package ejercicio130521;
public class milpersonas {
public static void main(String[] args) {
int m = 10;
for (int i=0; i<m; i++){
for (int j=0; j<m; j++){
for (int k=0; k<m; k++){
System.out.println("PERSONA "+i+", FAMILIA DE PERSONA "+j+",AMIGO DE FAMILIA DE PERSONA " +k);
}}}}}
EJERCICIO LIST SET
package ejercicio130522;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


public class ListSet {

  public static void main(String[] args) {

    //LIST Y SET
      
      ArrayList<String> yes = new ArrayList();
      List<String> yeso = new ArrayList<String>();
      yeso.add("Placido Domingo");
      yeso.add("Cesaria Evora");
      yeso.add("Runa Yacu");
      yeso.add("Placido Domingo");

      // RECORRER MEDIANTE UN FOR
      for (String e:yeso)
        System.out.println(e);
      
      // USO DEL ITERADOR
      Iterator p = yeso.iterator();
      while(p.hasNext()){
        System.out.println(p.next());
      }
     System.out.println();
      Set<String> yeset = new HashSet<String>();
      yeset.add("Placido Domingo");
      yeset.add("Cesaria Evora");
      yeset.add("Runa Yacu");
      yeset.add("Placido Domingo");
      for(String e:yeset)
        System.out.println(e);
}}

TRON DE 2 SERPIENTES EN JAVA CON SALTOS ALEATORIOS
package ejercicio130528;

import java.awt.Image;
import java.util.ArrayList;
public class Animation {
private ArrayList scenes;
private int sceneIndex;
private long movieTime;
private long totalTime;
public Animation(){
scenes = new ArrayList();
totalTime = 0;
start();
}
public synchronized void addScene(Image i, long t){
totalTime += t;
scenes.add(new oneScene(i,totalTime));
}
public synchronized void start(){
movieTime = 0;
sceneIndex = 0;
}
public synchronized void update(long timePassed){
if(scenes.size()>1){
movieTime += timePassed;
if(movieTime>=totalTime){
movieTime = 0;
sceneIndex = 0;
}
while(movieTime > getScene(sceneIndex).endTime){
sceneIndex++;
}
}
}
public synchronized Image getImage(){
if(scenes.size()==0)
{
return null;
}else{
return getScene(sceneIndex).pic;
}
}
private oneScene getScene(int x){
return (oneScene)scenes.get(x);
}
private class oneScene{
Image pic;
long endTime;
public oneScene(Image pic,long endTime){
this.pic = pic;
this.endTime = endTime;
}}}
package ejercicio130528;
import java.awt.*;
import java.awt.image.BufferedImage;

public abstract class Core {

private static final DisplayMode modes[] = 
{
//new DisplayMode(1920,1080,32,0),
new DisplayMode(1680,1050,32,0),
//new DisplayMode(1280,1024,32,0),
new DisplayMode(800,600,32,0),
new DisplayMode(800,600,24,0),
new DisplayMode(800,600,16,0),
new DisplayMode(640,480,32,0),
new DisplayMode(640,480,24,0),
new DisplayMode(640,480,16,0),
};
private boolean running;
protected ScreenManager sm;
public void stop(){
running = false;
}
public void run(){
try{
init();
gameLoop();
}finally{
sm.restoreScreen();
}
}
public void init(){
sm = new ScreenManager();
DisplayMode dm = sm.findFirstCompatibaleMode(modes);
sm.setFullScreen(dm);
Window w = sm.getFullScreenWindow();
w.setFont(new Font("Arial",Font.PLAIN,20));
w.setBackground(Color.WHITE);
w.setForeground(Color.RED);
w.setCursor(w.getToolkit().createCustomCursor(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), new Point(0, 0),"null")); 
running = true;
}
public void gameLoop(){
long startTime = System.currentTimeMillis();
long cumTime = startTime;
while (running){
long timePassed = System.currentTimeMillis()-cumTime;
cumTime+= timePassed;
update(timePassed);
Graphics2D g = sm.getGraphics();
draw(g);
g.dispose();
sm.update();
try{
Thread.sleep(20);
}catch(Exception ex){}
}
}
public void update(long timePassed){}
public abstract void draw(Graphics2D g);
}
package ejercicio130528;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class ScreenManager {
private GraphicsDevice vc;
public ScreenManager(){
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = e.getDefaultScreenDevice();
}
public DisplayMode[] getCompatibleDisplayModes(){
return vc.getDisplayModes();
}
public DisplayMode findFirstCompatibaleMode(DisplayMode[] modes){
DisplayMode goodModes[] = vc.getDisplayModes();
for(int x = 0; x<modes.length;x++){
for(int y = 0;y<goodModes.length;y++){
if(displayModesMatch(modes[x],goodModes[y])){
return modes[x];
}
}
}
return null;
}
public DisplayMode getCurrentDM(){
return vc.getDisplayMode();
}
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2){
if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){
return false;
}
if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){
return false;
}
if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){
return false;
}
return true;
}
public void setFullScreen(DisplayMode dm){
JFrame f = new JFrame();
f.setUndecorated(true);
f.setIgnoreRepaint(true);
f.setResizable(false);
vc.setFullScreenWindow(f);
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
}catch(Exception ex){}
f.createBufferStrategy(2);
}
}
public Graphics2D getGraphics(){
Window w = vc.getFullScreenWindow();
if(w != null){
BufferStrategy bs = w.getBufferStrategy();
return (Graphics2D)bs.getDrawGraphics();
}
else{
return null;
}
}
public void update(){
Window w = vc.getFullScreenWindow();
if(w != null){
BufferStrategy bs = w.getBufferStrategy();
if(!bs.contentsLost()){
bs.show();
}}}
public Window getFullScreenWindow(){
return vc.getFullScreenWindow();}
public int getWidth(){
Window w = vc.getFullScreenWindow();
if(w != null){
return w.getWidth();
}else{
return 0;
}
}
public int getHeight(){
Window w = vc.getFullScreenWindow();
if(w != null){
return w.getHeight();
}else{
return 0;
}}
public void restoreScreen(){
Window w = vc.getFullScreenWindow();
if(w != null){
w.dispose();
}
vc.setFullScreenWindow(null);
}
public BufferedImage createCompatibaleimage(int w, int h, int t){
Window win = vc.getFullScreenWindow();
if(win != null){
GraphicsConfiguration gc = win.getGraphicsConfiguration();
return gc.createCompatibleImage(w,h,t);
}else{
return null;
}}}
package ejercicio130528;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;

public class yourclass extends Core implements KeyListener, MouseListener,
MouseMotionListener {
int centrex1 = 40;
int centrey1 = 40;
int centrex2 = 600;
int centrey2 = 440;
int currentDirection1 = 1; 
int currentDirection2 = 3;
int moveAmount = 1; //velocidad de las serpientes
ArrayList<Integer> pathx1 = new ArrayList();
ArrayList<Integer> pathy1 = new ArrayList();
ArrayList<Integer> pathx2 = new ArrayList();
ArrayList<Integer> pathy2 = new ArrayList();

public void init() {
super.init();

Window w = sm.getFullScreenWindow();
w.addKeyListener(this);
w.addMouseListener(this);
w.addMouseMotionListener(this);
}

public static void main(String[] args) {
new yourclass().run();
}

public void draw(Graphics2D g) {
switch(currentDirection1){
case 0:
if (centrey1>0){
centrey1-=moveAmount;
} else {
centrey1 = sm.getHeight();
}
break;
case 1:
if (centrex1 < sm.getWidth()){
centrex1+=moveAmount;
} else {
centrex1 = 0;
}
break;
case 2:
if (centrey1 < sm.getHeight()){
centrey1+=moveAmount;
} else {
centrey1 = 0;
}
break;
case 3:
if (centrex1>0){
centrex1-=moveAmount;
} else {
centrex1 = sm.getWidth();
}
break;
}
switch(currentDirection2){
case 0:
if (centrey2>0){
centrey2-=moveAmount;
} else {
centrey2 = sm.getHeight();
}
break;
case 1:
if (centrex2 < sm.getWidth()){
centrex2+=moveAmount;
} else {
centrex2 = 0;
}
break;
case 2:
if (centrey2 < sm.getHeight()){
centrey2+=moveAmount;
} else {
centrey2 = 0;
}
break;
case 3:
if (centrex2>0){
centrex2-=moveAmount;
} else {
centrex2 = sm.getWidth();
}
break;
}
   for (int x = 0;x<pathx1.size();x++){
    if (((centrex1 == pathx1.get(x)) && (centrey1 == pathy1.get(x))) || ((centrex2 == pathx2.get(x)) && (centrey2 == pathy2.get(x))) || ((centrex1 == pathx2.get(x)) && (centrey1 == pathy2.get(x))) || ((centrex2 == pathx1.get(x)) && (centrey2 == pathy1.get(x)))){
    System.exit(0);
    }
   }//colisiones
pathx1.add(centrex1);
pathy1.add(centrey1);
pathx2.add(centrex2);
pathy2.add(centrey2);
g.setColor(Color.BLACK);
g.fillRect(0, 0, sm.getWidth(), sm.getHeight());
for (int x = 0;x<pathx1.size();x++){
int mh= (int)(Math.random()*6 + 1) ;
if (mh%2==0){
}
else {
g.setColor(Color.green);
g.fillRect(pathx1.get(x), pathy1.get(x), 1, 1);
g.setColor(Color.red);
g.fillRect(pathx2.get(x), pathy2.get(x), 1, 1);
}
}
}

public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
if (currentDirection1 != 2){
currentDirection1 = 0;
}
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (currentDirection1 != 0){
currentDirection1 = 2;
}
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (currentDirection1 != 3){
currentDirection1 = 1;
}
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (currentDirection1 != 1){
currentDirection1 = 3;
}
}
if (e.getKeyCode() == KeyEvent.VK_W){
if (currentDirection2 != 2){
currentDirection2 = 0;
}
} else if (e.getKeyCode() == KeyEvent.VK_S) {
if (currentDirection2 != 0){
currentDirection2 = 2;
}
} else if (e.getKeyCode() == KeyEvent.VK_D) {
if (currentDirection2 != 3){
currentDirection2 = 1;
}
} else if (e.getKeyCode() == KeyEvent.VK_A) {
if (currentDirection2 != 1){
currentDirection2 = 3;
}}}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent arg0) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {

}
}

MISTERMIND DE 5 FICHAS (COLORES O NUMEROS) EN JAVA
package ejercicio130604;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MM {
static String f = "";

public static void main(String[] args) {
int s = 0;
String n = "";
String diff = "";
boolean ans = false;
int[] d = new int[5]; //habia un 4
int[] pos = new int[5]; //habia un 4
pos[0] = (int) (Math.random() * 100);
pos[1] = (int) (Math.random() * 100);
pos[2] = (int) (Math.random() * 100);
pos[3] = (int) (Math.random() * 100);
pos[4] = (int) (Math.random() * 100); //esta línea no estaba
f = readLine("Welcome to MasterMind by Greg Cawthorne!\nIn this game you attempt to crack a code with only the aid of minor hints and you own ingenuity!\nPress enter to begin! ");
f = readLine("Would you like to play with letters (1) or numbers (2)? ");
do {
if (f.equals("letters") || f.equals("1")) {
diff = "letters";
ans = true;
System.out
.println("The code will be made up 5 letters of either R,G,B,Y,P,T "); //habia 4 letters
} else if (f.equals("numbers") || f.equals("2")) {
diff = "numbers";
ans = true;
System.out
.println("The code will be made up of 5 numbers of either 1,2,3,4,5,6 ");   //habia 4 numbers
} else {
f = readLine("Sorry, I didn't quite get that. Would you like to play with letters (1) or numbers (2)? ");
}
} while (ans == false);
for (int x = 0; x <= 4; x++) { //había x<=3
if (pos[x] <= 17) {
d[x] = 1;
} else if (pos[x] <= 34) {
d[x] = 2;
} else if (pos[x] <= 51) {
d[x] = 3;
} else if (pos[x] <= 68) {
d[x] = 4;
} else if (pos[x] <= 85) {
d[x] = 5;
} else if (pos[x] <= 100) {
d[x] = 6;
}}
if (diff.equals("numbers")) {
n = "numbers either 1,2,3,4,5 or 6";
} else if (diff.equals("letters")) {
n = "letters either R,B,G,Y,P or T all caps";
}

System.out.println("The computer has thought of his sequence.");
if(diff == "letters"){
check(d, n, s);
} else if (diff == "numbers"){
check2(n, d, s);
}
}

public static void check(int[] d, String n, int s) {
int count2= 0;
String r = "R";
String b = "B";
String g = "G";
String y = "Y";
String p = "P";
String tq = "T";
String f = "";
boolean z = false;
int v = 0;
f = readLine("Take a guess! ");
if ((f.length() == 5) //había if ((f.length() == 4)
&& (f.charAt(0) == r.charAt(0) || f.charAt(0) == b.charAt(0)
|| f.charAt(0) == g.charAt(0)
|| f.charAt(0) == y.charAt(0)
|| f.charAt(0) == p.charAt(0) || f.charAt(0) == tq
.charAt(0))
&& (f.charAt(1) == r.charAt(0) || f.charAt(1) == b.charAt(0)
|| f.charAt(1) == g.charAt(0)
|| f.charAt(1) == y.charAt(0)
|| f.charAt(1) == p.charAt(0) || f.charAt(1) == tq
.charAt(0))
&& (f.charAt(2) == r.charAt(0) || f.charAt(2) == b.charAt(0)
|| f.charAt(2) == g.charAt(0)
|| f.charAt(2) == y.charAt(0)
|| f.charAt(2) == tq.charAt(0) || f.charAt(2) == p
.charAt(0))
&& (f.charAt(3) == r.charAt(0) || f.charAt(3) == b.charAt(0)
|| f.charAt(3) == g.charAt(0)
|| f.charAt(3) == y.charAt(0)
|| f.charAt(3) == tq.charAt(0) || f.charAt(3) == p.charAt(0))
//estas cuatro lineas de abajo no estaban
&& (f.charAt(4) == r.charAt(0) || f.charAt(4) == b.charAt(0)
|| f.charAt(4) == g.charAt(0)
|| f.charAt(4) == y.charAt(0)
|| f.charAt(4) == tq.charAt(0) || f.charAt(4) == p.charAt(0))
) {
z = true;
System.out.println();
s++;
int chin[] = new int[6];
int chin2[] = new int[6];
char bin[] = new char[6];
bin[0] = 'R'; bin[1] = 'B'; bin[2] = 'G'; bin[3] = 'Y'; bin[4] = 'P'; bin[5] = 'T';
char a[] = new char[5]; //había char a[] = new char[4];
int t[] = new int[5]; //había int t[] = new int[4];
for (int x = 0;x<5;x++){ //había for (int x = 0;x<4;x++){
a[x] = (f.charAt(x));
}
for (int eye = 0; eye< 5;eye++){ //había for (int eye = 0; eye< 4;eye++){
for (int tim = 0; tim<6;tim++){
if (a[eye] == bin[tim]){
t[eye] = tim +1;
}}
}for (int x = 0;x<5;x++){ //había }for (int x = 0;x<4;x++){
if (t[x] == 1){
chin[0] = chin[0]+1;
} else if (t[x] == 2){
chin[1] = chin[1]+1;
} else if (t[x] == 3){
chin[2] = chin[2]+1;
} else if (t[x] == 4){
chin[3] = chin[3]+1;
} else if (t[x] == 5){
chin[4] = chin[4]+1;
} else if (t[x] == 6){
chin[5] = chin[5]+1;
}
if (d[x] == 1){
chin2[0] = chin2[0]+1;
} else if (d[x] == 2){
chin2[1] = chin2[1]+1;
} else if (d[x] == 3){
chin2[2] = chin2[2]+1;
} else if (d[x] == 4){
chin2[3] = chin2[3]+1;
} else if (d[x] == 5){
chin2[4] = chin2[4]+1;
} else if (d[x] == 6){
chin2[5] = chin2[5]+1;
}
}
for (int x = 0; x <= 4; x++) { //había for (int x = 0; x <= 3; x++) {
if (d[x] == t[x]) {
v++;
}
}
for (int x = 0;x<6;x++){
if (chin[x] <= chin2[x]){
count2 = count2 + chin[x];
} else {
count2 = count2 + chin2[x]; }
} count2 = count2 - v;
}
if (z == false) {
System.out.println("Invalid guess. Please guess four " + n
+ " with no spaces. :)");
} else { 
System.out.println("You guessed: " + f);
System.out.println("There are "+v+" letters in the right place,\nand "+count2+" other letters which are right, but in the wrong place.");
}
if (v == 4) {
System.out.print("Well done you cracked the code in " + s
+ " attempts!\n");
do{ f = readLine("Do you want to play again? ");
if (f.equals("yes") || f.equals("y") || f.equals("YES")){
main(null);
} else if (f.equals("no") || f.equals("n") || f.equals("NO")){
System.out.println("I hope you enjoyed MasterMind by Greg Cawthorne!");
System.exit(0);
} else {
System.out.print("Sorry I didn't quite get that. ");
z = false;
}} while (z == false);
} check(d, n, s);
}

public static void check2(String n, int[] d, int s){
int count2 = 0;
boolean z = false;
int v = 0;
String one = "1";
String two = "2";
String three = "3";
String four = "4";
String five = "5";
String six = "6";
f = readLine("Take a guess! ");
//había if((f.length() == 4) && (f.charAt(0) == one.charAt(0) || f.charAt(0) == two.charAt(0) || f.charAt(0) == three.charAt(0)

if((f.length() == 5) && (f.charAt(0) == one.charAt(0) || f.charAt(0) == two.charAt(0) || f.charAt(0) == three.charAt(0)
|| f.charAt(0) == four.charAt(0) || f.charAt(0) == five.charAt(0) || f.charAt(0) == six.charAt(0))
&& (f.charAt(1) == one.charAt(0) || f.charAt(1) == two.charAt(0)
|| f.charAt(1) == three.charAt(0)
|| f.charAt(1) == four.charAt(0)
|| f.charAt(1) == five.charAt(0) || f.charAt(1) == six.charAt(0))
&& (f.charAt(2) == one.charAt(0) || f.charAt(2) == two.charAt(0)
|| f.charAt(2) == three.charAt(0)
|| f.charAt(2) == four.charAt(0)
|| f.charAt(2) == five.charAt(0) || f.charAt(2) == six.charAt(0))
&& (f.charAt(3) == one.charAt(0) || f.charAt(3) == two.charAt(0)
|| f.charAt(3) == three.charAt(0)
|| f.charAt(3) == four.charAt(0)
|| f.charAt(3) == five.charAt(0) || f.charAt(3) == six.charAt(0))
//estas cuatro lineas de abajo no estaban
&& (f.charAt(4) == one.charAt(0) || f.charAt(4) == two.charAt(0)
|| f.charAt(4) == three.charAt(0)
|| f.charAt(4) == four.charAt(0)
|| f.charAt(4) == five.charAt(0) || f.charAt(4) == six.charAt(0))
){
z = true;
System.out.println();
s++;
int chin[] = new int[6];
int chin2[] = new int[6];
String a[] = new String[5]; //había String a[] = new String[4];
int t[] = new int[5]; //había int t[] = new int[4];
for (int x = 0;x<=4;x++){ //había for (int x = 0;x<=3;x++){
a[x] = String.valueOf(f.charAt(x));
t[x] = Integer.parseInt(a[x]);
if (t[x] == 1){
chin[0] = chin[0]+1;
} else if (t[x] == 2){
chin[1] = chin[1]+1;
} else if (t[x] == 3){
chin[2] = chin[2]+1;
} else if (t[x] == 4){
chin[3] = chin[3]+1;
} else if (t[x] == 5){
chin[4] = chin[4]+1;
} else if (t[x] == 6){
chin[5] = chin[5]+1;
}
if (d[x] == 1){
chin2[0] = chin2[0]+1;
} else if (d[x] == 2){
chin2[1] = chin2[1]+1;
} else if (d[x] == 3){
chin2[2] = chin2[2]+1;
} else if (d[x] == 4){
chin2[3] = chin2[3]+1;
} else if (d[x] == 5){
chin2[4] = chin2[4]+1;
} else if (d[x] == 6){
chin2[5] = chin2[5]+1;
}
}
System.out.println("You guessed: " + f);
for (int x = 0; x <= 4; x++) { // había for (int x = 0; x <= 3; x++) {
if (d[x] == t[x]) {
v++;
}
}
for (int x = 0;x<6;x++){
if (chin[x] <= chin2[x]){
count2 = count2 + chin[x];
} else {
count2 = count2 + chin2[x]; }
} count2 = count2 - v;
}
if (z == false) {
System.out.println("Invalid guess. Please guess five " + n
+ " with no spaces. :)");
} else { 
System.out.println("There are "+v+" numbers in the right place,\nand "+count2+" other numbers which are right, but in the wrong place.");
}
if (v == 5) { //había if (v == 4) {
System.out.print("Well done you cracked the code in " + s
+ " attempts!\n");
do{ f = readLine("Do you want to play again? ");
if (f.equals("yes") || f.equals("y") || f.equals("YES")){
main(null);
} else if (f.equals("no") || f.equals("n") || f.equals("NO")){
System.out.println("I hope you enjoyed MasterMind by Greg Cawthorne!");
System.exit(0);
} else {
System.out.print("Sorry I didn't quite get that. ");
z = false;
}} while (z == false);
} check2(n, d, s);
}
public static String readLine(String prompt) {
String input = "";
System.out.print(prompt);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {

input = br.readLine();

} catch (IOException ioe) {
}
return input;
}
}



miércoles, 5 de junio de 2013

Examen SQL

1/ Muestra el nombre del barrio y todos los apartamentos que estén situados en esos barrios cuyo precio sea superior a 350€:

Select b.nombre as 'nombre barrio', a.edificio, a.domicilio, a.piso, a.numeroapto from barrios as b join apartamentos as a on b.codigo=a.codigobarrio where a.precio>350;


2/ Muestra todos los registros y un mensaje que ponga ‘caro’ si el precio de un apartamento supera los 350€

select *, if(precio>350, 'caro', ' ') from barrios as b join apartamentos as a on b.codigo=a.codigobarrio;

3/ Muestra el promedio de los apartamentos agrupados por barrio:

select b.nombre, avg (a.precio) from barrios as b join apartamentos as a on b.cdigo=a.codigobarrio group by b.nombre

4/ Muestra todos los barrios y apartamentos, incluso aquellos barrios en los que no hayan apartamentos:


select * from barrios as b left join apartamentos as a on b.codigo=a.codigobarrio;

5/ Agrupando por nombre de barrio, muestra el nombre del barrio, la media del precio del barrio y cuenta la cantidad de apartamentos que hay en cada barrio.
Además, muestra un mensaje en el que aparezca una nueva media de la siguiente forma: si la media del barrio es mayor a 400€, la nueva media aumentaría un 15%, pero si es menor de 400€, la nueva media aumenta un 10%:


select b.nombre, avg(precio), count(a.numeroapto), if(avg(a.precio)>400, avg(a.precio)+(avg(a.precio)*0.15), avg(a.precio)+(avg(a.precio)*0.1))as medias from barrios as b join apartamentos as a on b.codigo=a.codigobarrio group by b.nombre;

Actividad Final SQL Bases de Datos.



a)    Enunciado:

Una empresa de consultoría de aplicaciones móviles desea poder realizar un informe sobre las descargas de aplicaciones de “iphone” en sus dispositivos.
Para ello necesita saber, qué móvil se ha bajado algo (IMEI), qué modelo de dispositivo es, qué versión tiene, y de qué color es.
Además también quiere almacenar qué aplicación ha sido descargada (nombre), qué tamaño tiene y su coste.
Para finalizar, necesitaría conocer la fecha de descarga de la misma, la cual genera un número automático de orden de descarga.

b)    Diseño Entidad Relación:

c)    Diseño SQL:

create table Iphone(imei varchar(5), modelo varchar (2), version int, color varchar(6), primary key (imei))ENGINE=INNODB;

create table aplicacion(nombre varchar (10), size int, precio int, primary key (nombre))ENGINE=INNODB;

create table descarga(numero int not null auto_increment, imeimovil varchar(5), nombreap varchar (10), fecha date, primary key(numero), index(nombreap), foreign key (imeimovil) references iphone(imei), foreign key (nombreap) references aplicacion(nombre))ENGINE=INNODB;

d)    Pantallazo de las tablas con sus datos:
TABLA IPHONE:
Insert into Iphone values ('11111', '4', 6, 'BLANCO');
Insert into Iphone values ('22222', '4s', 5, 'NEGRO');
Insert into Iphone values ('33333', '4s', 6, 'BLANCO');
Insert into Iphone values ('44444', '5', 6, 'BLANCO');
Insert into Iphone values ('55555', '4s', 6, 'NEGRO');
Insert into Iphone values ('66666', '4', 5, 'NEGRO');
Insert into Iphone values ('77777', '4', 5, 'NEGRO');
Insert into Iphone values ('88888', '5', 6, 'NEGRO');
Insert into Iphone values ('99999', '5', 6, 'NEGRO');

TABLA APLICACION:

insert into aplicacion    values ("instagram", 1, 2);
insert into aplicacion    values ("twitter", 2, 1);
insert into aplicacion    values ("triviados", 5, 3);
insert into aplicacion    values ("candycrush", 6, 5);
insert into aplicacion    values ("shazam", 2, 2);
insert into aplicacion    values ("youtube", 4, 1);
insert into aplicacion    values ("runtastic", 9, 2);
insert into aplicacion    values ("facebook", 3, 1);

TABLA DESCARGA:
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'facebook', '20130301');
insert into descarga (imeimovil, nombreap, fecha) values ('11111', 'twitter', '20130301');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'twitter', '20130305');
insert into descarga (imeimovil, nombreap, fecha) values ('66666', 'facebook', '20130305');
insert into descarga (imeimovil, nombreap, fecha) values ('66666', 'runtastic', '20130306');
insert into descarga (imeimovil, nombreap, fecha) values ('88888', 'runtastic', '20130307');
insert into descarga (imeimovil, nombreap, fecha) values ('88888', 'facebook', '20130308');
insert into descarga (imeimovil, nombreap, fecha) values ('77777', 'facebook', '20130309');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'candycrush', '20130310');
insert into descarga (imeimovil, nombreap, fecha) values ('22222', 'youtube', '20130311');
insert into descarga (imeimovil, nombreap, fecha) values ('22222', 'twitter', '20130312');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'runtastic', '20130313');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'facebook', '20130314');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'twitter', '20130315');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'instagram', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'triviados', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'runtastic', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('88888', 'twitter', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('77777', 'twitter', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('66666', 'twitter', '20130320');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'youtube', '20130320');
insert into descarga (imeimovil, nombreap, fecha) values ('99999', 'twitter', '20130321');
insert into descarga (imeimovil, nombreap, fecha) values ('99999', 'shazam', '20130321');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'instagram', '20130321');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'shazam', '20130322');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'twitter', '20130323');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'instagram', '20130324');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'runtastic', '20130330');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'candycrush', '20130330');
insert into descarga (imeimovil, nombreap, fecha) values ('99999', 'youtube', '20130330');

e)     Consultas sobre la base de datos. Deberás utilizar y realizar pantallazos de:
I.-Muestra por pantalla las descargas realizadas por un terminal 4s:
SELECT *
FROM descarga
JOIN Iphone ON Iphone.imei = descarga.imeimovil
WHERE Iphone.modelo = '4s'

II.-Muestra todas las descargas ordenadas por imei:
SELECT *
FROM descarga
ORDER BY imeimovil

III.-Muestra la cantidad de veces que se haya descargado cada una de las aplicaciones:
select count(d.nombreap), (a.nombre) from descarga as d join aplicacion as a on d.nombreap=a.nombre group by a.nombre;

IV.- Cuenta  todas las descargas realizadas ordenadas por modelo de iphone:
select count(d.nombreap), (i.modelo) from descarga as d join Iphone as i on d.imeimovil=i.imei group by i.modelo;

V.-Muestra por pantalla la cantidad de descargas realizadas por cada terminal (por imei):
SELECT COUNT( d.nombreap ) , i.imei FROM descarga AS d JOIN Iphone AS i ON d.imeimovil = i.imei GROUP BY i.imei

VI.-Muestra por pantalla todas las descargas realizadas de cada aplicación mostrando además un mensaje si la aplicación ha sido un éxito (hay más de 4 descargas) .
select count(d.nombreap), (a.nombre), if (count(d.nombreap)>4, 'exito', ' ') as 'exito o no' from descarga as d  join aplicacion as a on d.nombreap=a.nombre group by a.nombre

VII.-Muestra por pantalla el total de dinero gastado por dispositivo.
SELECT d.imeimovil, sum(a.precio)
from aplicacion as a
join descarga as d
on a.nombre=d.nombreap
group by d.imeimovil

VIII.- Muestra por pantalla todas las aplicaciones que empiecen por 't':
select * from aplicacion where nombre like 't%'

IX.-Muestra por pantalla las aplicaciones que hayan sido descargadas mas de tres veces:
select count(nombreap),nombreap from descarga  group by nombreap  having count(nombreap)>3;

X.-Muestra por pantalla todos aquellos terminales que se hayan descargado 'runtastic' o 'facebook', con su fecha de descarga.
select fecha, imeimovil, nombreap from descarga where nombreap='facebook' or nombreap='runtastic'

XI.- Actualiza los precios de 'shazam' a 5.
UPDATE aplicacion SET precio =5 WHERE nombre = 'shazam' 

select * from aplicación


XII.-Muestra por pantalla todas las aplicaciones aunque no hayan sido descargadas ninguna vez:
Para realizar un right join necesito agregar una nueva línea en la tabla aplicación:
insert into aplicacion    values ("amazon", 10, 7);
SELECT *
FROM aplicacion AS a
LEFT JOIN descarga AS d ON a.nombre = d.nombreap

jueves, 23 de mayo de 2013

TECLADO JAVA ENTORNO GRAFICO

package editor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class Editor extends JFrame implements MouseListener{
    String firstRow[] = {"~","1","2","3","4","5","6","7","8","9","0","-","+","<<<<<"};
    String secondRow[] = {"Tab","Q","W","E","R","T","Y","U","I","O","P","[","]","\\"};
    String thirdRow[] = {"Caps","A","S","D","F","G","H","J","K","L",":","\"","Enter"};
    String fourthRow[] = {"Shift","Z","X","C","V","B","N","M",",",".","?","   ^" };
    String fifthRow[]={"      " ,"<" ,"\\/",">" };
    String noShift="`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./";
    String specialChars ="~-+[]\\;',.?";
   
    JButton first[];
    JButton second[];
    JButton third[];
    JButton fourth[];
    JButton fifth[];
    Color cc = new JButton().getBackground();
    JTextArea  text;
    Boolean mayusculas = false;

   
    public static void main(String[] args) {
        new Editor().setVisible(true);
    }

    public Editor()
    {
        this.setResizable(false);
         this.getContentPane().setPreferredSize(new Dimension(1000,600));
        this.setLocation(50,50);
        iniciar();
    }

    private void iniciar()
    {

        text = new JTextArea();
        text.setPreferredSize(new Dimension(800,200));
        JLabel info = new JLabel("");
        setLayout(new BorderLayout());
        JPanel jpNorth = new JPanel();
        JPanel jpCenter = new JPanel();
        JPanel jpKeyboard = new JPanel();
        JPanel jpNote = new JPanel();
        add( jpNorth, BorderLayout.NORTH);
        add( jpNote);
        add( jpCenter, BorderLayout.CENTER);
        add(jpKeyboard, BorderLayout.SOUTH);

        jpNorth.setLayout(new BorderLayout());
        jpNorth.add(info, BorderLayout.WEST);
        jpNorth.add(info, BorderLayout.SOUTH);

        jpCenter.setLayout( new BorderLayout());
        jpCenter.add(text, BorderLayout.WEST);
        jpCenter.add(text, BorderLayout.CENTER);

        jpKeyboard.setLayout(new GridLayout(5,1));
        pack();

        first = new JButton[firstRow.length];
        JPanel p = new JPanel(new GridLayout(1, firstRow.length));
        for(int i = 0; i < firstRow.length; ++i)
        {
            JButton b= new JButton(firstRow[i]);
            b.setPreferredSize(new Dimension(100,50));
            first[i] = b;
            first[i].addMouseListener(this);
            p.add(first[i]);
        }
        jpKeyboard.add(p);
        second = new JButton[secondRow.length];
        p = new JPanel(new GridLayout(1, secondRow.length));
        for(int i = 0; i < secondRow.length; ++i)
        {
            second[i] = new JButton(secondRow[i]);
            second[i].addMouseListener(this);
            p.add(second[i]);

        }
        jpKeyboard.add(p);
        third = new JButton[thirdRow.length];
        p = new JPanel(new GridLayout(1, thirdRow.length));
        for(int i = 0; i < thirdRow.length; ++i)
        {
            third[i] = new JButton(thirdRow[i]);
            third[i].addMouseListener(this);
            p.add(third[i]);
        }
        jpKeyboard.add(p);
        fourth = new JButton[fourthRow.length];
        p = new JPanel(new GridLayout(1, fourthRow.length));
        for(int i = 0; i < fourthRow.length; ++i)
        {
            fourth[i] = new JButton(fourthRow[i]);
            fourth[i].addMouseListener(this);
            p.add(fourth[i]);
            if(i==fourthRow.length-2)
                p.add(new JPanel());

        }
        p.add(new JPanel());
        jpKeyboard.add(p);
        fifth = new JButton[fifthRow.length];
        p = new JPanel(new GridLayout(1, fifthRow.length));
        for(int i = 0; i < 1; ++i)
        {
            JPanel  spacePanel = new JPanel();
            p.add(spacePanel);
        }
        for(int i = 0; i < fifthRow.length; ++i)
        {
            if(i==1)
            {
                JButton b = new JButton(fifthRow[i]);
                b.setPreferredSize(new Dimension(400,10));
                b.setBounds(10, 10, 600, 100);
                fifth[i]=b;
                fifth[i].addMouseListener(this);
                p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());p.add(new JPanel());
            }
            else
            {
                fifth[i]=new JButton(fifthRow[i]);
                fifth[i].addMouseListener(this);
            }
            if(i==0)
            {
                   JPanel  spacePanel = new JPanel();
                   p.add(spacePanel);
            }
            p.add(fifth[i]);
        }
        jpKeyboard.add(p);
        }

    @Override
    public void mouseClicked(MouseEvent e) {
            JButton btn = (JButton) e.getSource();
            switch(btn.getText()) {
            case "Enter":
            case "\\/":
                text.setText(""+text.getText()+btn.getText()+"\n");
                break;
               
            case "<<<<<":
               String sCadena = text.getText();
               text.setText(sCadena.substring(0,text.getDocument().getLength()-1));
               break;
            case ">":          
                 text.grabFocus();
                break;
            case "<":
                    text.grabFocus();
                    int i = text.getDocument().getLength();
                    text.setCaretPosition(i - 1);
                    break;
              
            case "Caps":
            case "Shift":
                if (mayusculas){
                    mayusculas = false;
                    btn.setBackground(cc);               
                } else{
                mayusculas = true;
                btn.setBackground(Color.DARK_GRAY);
                }
                break;

               
            default:
                if (!mayusculas) {
                    String texto = (btn.getText()).toLowerCase();
                    text.setText(""+text.getText()+texto);   
                } else {
                    text.setText(""+text.getText()+btn.getText());
                }
            }
           
        }


    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Apéndice de método generado automáticamente
       
    }

    }

miércoles, 22 de mayo de 2013

EJERCICIOS I



select titulo, if(precio>50, `caro`, 'economico') from libros;
select autor, if (count(*)>1, 'mas de 1', '1') from libros group by autor;
select editorial, if (count(*)>4, '5 o mas', 'menos de 5') as cantidad from libros group by editorial order by cantidad;
select sexo count (sexo) if (sexo='f', 'rosas', 'corbata') as 'obsequio' from empleados where month (fecha nacimiento) = 5 group by sexo;
select nombre, fecha ingreso, year(current_date) year (fecha ingreso) as 'años de servicio', if ((year(current-date)-year(fechaingreso)) %10=0, 'si', 'no') as 'Placa' from empleados where month(fechaingreso)=4;
select nombre, sueldo, hijos, if (sueldo basico <=500, sueldobasico+(300*hijos), sueldobasico+(150*hijos)) as total from empleados where hijos > 0;
select dni, vencimiento, current_date as 'Fecha actual', total, if (datediff (current_date, vencimiento)>0, 'si', 'no') as vencida from luz;
select dni, count (*), if (count(*)>1, 'cortar servicio' ' ') as 'servicio' from luz where datediff (current_date, vencimiento)>0 group by documento;
select matricula,horallegada,horasalida, left(timediff(horasalida,horallegada),5) as horasminutos, if (hour(timediff(horasalida,horallegada))>4, hour(timediff(horasalida,horallegada)) div 4,0) as horagratis from vehiculos where horasalida is not null;
SELECT promedio, if (promedio>=4, 'aprobado','suspendido') from alumnos;
select nombre,promedio, if (promedio>=9,'medalla','') from alumnos
select *, if(entradasvendidas >= capacidad, 'agotadas','') from entradas;
select *, if(entradasvendidas >0 and `entradasvendidas`>(capacidad/2), 'mas de la mitad','menos de la mitad') from entradas;


A. Un profesor guarda los promedios de sus alumnos de un curso en una tabla llamada "alumnos".

create table alumnos(
  expediente char(5) not null,
  nombre varchar(30),
  promedio decimal(4,2)
);

1- Inserta los siguientes registros:
 insert into alumnos values(3456,'Perez Luis',8.5);
 insert into alumnos values(3556,'Garcia Ana',7.0);
 insert into alumnos values(3656,'Ludueña Juan',9.6);
 insert into alumnos values(2756,'Moreno Gabriela',4.8);
 insert into alumnos values(4856,'Morales Hugo',3.2);

2- Si el alumno tiene un promedio superior o igual a 4, muestra un mensaje "aprobado" en caso contrario "suspendido":

SELECT promedio, if (promedio>=4, 'aprobado','suspendido') from alumnos;

3- Es política del profesor entregar una medalla a quienes tengan un promedio igual o superior a 9. Muestra los nombres y promedios de los alumnos y un mensaje "medalla" a quienes cumplan con ese requisito:


select nombre,promedio, if (promedio>=9,'medalla','') from alumnos

B) Un teatro con varias salas guarda la información de las entradas vendidas en una tabla llamada "entradas".

create table entradas(
  sala tinyint unsigned,
  fecha date,
  hora time,
  capacidad smallint unsigned,
  entradasvendidas smallint unsigned,
  primary key(sala,fecha,hora)
 );

1- Inserta algunos registros:
 insert into entradas values(1,'2006-05-10','20:00',300,50);
 insert into entradas values(1,'2006-05-10','23:00',300,250);
 insert into entradas values(2,'2006-05-10','20:00',400,350);
 insert into entradas values(2,'2006-05-11','20:00',400,380);
 insert into entradas values(2,'2006-05-11','23:00',400,400);
 insert into entradas values(3,'2006-05-12','20:00',350,350);
 insert into entradas values(3,'2006-05-12','22:30',350,100);
 insert into entradas values(4,'2006-05-12','20:00',250,0);

2- Muestra todos los registros y un mensaje si las entradas para una función están agotadas:


select *, if(entradasvendidas >= capacidad, 'agotadas','') from entradas

3- Muestra todos los datos de las funciones que tienen vendidas entradas y muestre un mensaje si se vendió más o menos de la mitad de la capacidad de la sala:

select *, if(entradasvendidas >0 and `entradasvendidas`>(capacidad/2), 'mas de la mitad','menos de la mitad') from entradas



Ejercicio: Tabla vehículos
Un parking guarda cada día los datos de los vehículos que acceden a la playa en una tabla llamada "vehiculos".

create table vehiculos(
  matricula char(6) not null,
  tipo char(4),
  horallegada time not null,
  horasalida time,
  primary key(matricula,horallegada)
 );

1- Inserta algunos registros:
insert into vehiculos (matricula,tipo,horallegada,horasalida)  values('ACD123','auto','8:30','9:40');
insert into vehiculos (matricula,tipo,horallegada,horasalida)  values('AKL098','auto','8:45','15:10');
insert into vehiculos (matricula,tipo,horallegada,horasalida)  values('HGF123','auto','9:30','18:40');
insert into vehiculos (matricula,tipo,horallegada,horasalida)  values('DRT123','auto','15:30',null);
insert into vehiculos (matricula,tipo,horallegada,horasalida)  values('FRT545','moto','19:45',null);
insert into vehiculos (matricula,tipo,horallegada,horasalida)  values('GTY154','auto','20:30','21:00');

2- Muestra la matricula, la hora de llegada y de salida de todos los vehículos, más una columna que calcule la cantidad de horas que estuvo cada vehículo en la playa, sin considerar los que aún no se fueron de la playa:


SELECT `matricula`,`horallegada`,`horasalida`,left(timediff(horasalida,horallegada),5) as horasminutos FROM `vehiculos`

3- Se cobra 1 euro por hora. Pero si un vehículo permanece en la playa 4 horas, se le cobran 3 euros, es decir, no se le cobra la cuarta hora; si está 8 horas, se cobran 6 euros, y así sucesivamente. Muestra la matricula, la hora de llegada y de salida de todos los vehículos, más la columna que calcule la cantidad de horas que estuvo cada vehículo en la playa (sin considerar los que aún no se fueron de la playa) y otra columna utilizando "if" que muestre la cantidad de horas gratis:

 select matricula,horallegada,horasalida,
  left(timediff(horasalida,horallegada),5) as horasminutos,
  if (hour(timediff(horasalida,horallegada))>4,
  hour(timediff(horasalida,horallegada)) div 4,0) as horagratis
  from vehiculos
  where horasalida is not null;

jueves, 16 de mayo de 2013

EJERCICIOS JOIN SQL

12. VARIAS TABLAS JOIN
select * from clientes as c join provincias as p on c.codigo=p.codigo;
select * from clientes as c.join provincias as p on codigo=p.codigo order by c.nombre;
12.1 VARIAS TABLAS LEFT JOIN
12.2 VARIAS TABLAS RIGHT JOIN
Tablas socios e inscritos
1. select * from socios as s left join inscritos as i on s.dni=i.dni
2. select * from inscritos as i right join socios as s on s.dni=i.dni;
4. select * from socios as s right join inscritos as i on s.dni=i.dni;
12.6 JOIN GROUP BY Y FUNCIONES DE AGRUPAMIENTO
Tabla clientes y provincias
1.select count (c.nombre), (p.nombre) from clientes as c join provincias as p on c.codigo group by p.nombre;
2.select count (c.nombre), p.nombre from clientes as c left join provincias as p on c. codigo group by p.nombre;;
3.select p.nombre count (c.codigoprovincia) as 'cantidad clientes' from provincias as p join clientes as c on p.codigo =c.codigo provincia group by p.nombre having count (c.codigoprovincia)>=2;
Tabla apartamentos y barrrios
2.select i.edificio, i.domicilio, i.piso, i.numeroapto, i.precio, b.nombre from inmuebles as i cross join barrios as b;
3.select i.edificio, count (i.domicilio), b.nombre from inmuebles as i join barrios as b on i.codigobarrio=b.codigo group by i.edificio;
4.selecti.domicilio, avg(i.precio) b.nombre from inmuebles as i cross join barrios as b on i.codigobarrio=b.codigo group by b.nombre;