diff --git a/README.md b/README.md index 69e33f6..00b159b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,13 @@ +# ThinkJava2 - Castellano + +Intento de proyecto de traducción de este excelente libro al castellano. + +Es un proyecto, de momento, puramente personal y al que dedico mucho menos tiempo del que me gustaría, de modo que avanzará muy despacio (o incluso nada). Las contribuciones son más que bienvenidas. + +La motivación de este proyecto es hacer este texto accesible a los estudiantes con poco o ningún conocimiento de Inglés. Descubrí el libro mientras buscaba un material adecuado para enseñar programación y Java en la Formación Profesional de Grado Superior. Me encantó la filosofía del libro, sus principios guía y su clara vocación pedagógica. + +Mi agradecimiento y mi admiración a los autores por ceder su trabajo bajo una licencia abierta. + # ThinkJava2 LaTeX source for Think Java, 2nd edition. Copyright (c) 2020 Allen B. Downey and Chris Mayfield. This edition was published in December 2019 by [O'Reilly Media](https://www.oreilly.com/library/view/think-java-2nd/9781492072492/) (ISBN 9781492072508). diff --git a/appd.tex b/appd.tex index 14da5d1..ff4a8b5 100644 --- a/appd.tex +++ b/appd.tex @@ -1,4 +1,5 @@ -\chapter{Debugging} +%\chapter{Debugging} +\chapter{Depuración} \label{debugging} \index{debugging} diff --git a/ch00.tex b/ch00.tex index f1f41a9..b3a67ce 100644 --- a/ch00.tex +++ b/ch00.tex @@ -1,48 +1,75 @@ -\chapter*{Preface} - -\markboth{PREFACE}{PREFACE} -\addcontentsline{toc}{chapter}{Preface} - -{\it Think Java} is an introduction to computer science and programming intended for readers with little or no experience. -We start with the most basic concepts and are careful to define all terms when they are first used. -The book presents each new idea in a logical progression. -Larger topics, like control flow statements and object-oriented programming, are divided into smaller examples and introduced over the course of several chapters. - -This book is intentionally concise. -Each chapter is 12--14 pages and covers the material for one week of a college course. -It is not meant to be a comprehensive presentation of Java, but rather, an initial exposure to programming constructs and techniques. -We begin with small problems and basic algorithms and work up to object-oriented design. -In the vocabulary of computer science pedagogy, this book uses the ``objects late'' approach. - - -\section*{The Philosophy Behind the Book} - -Here are the guiding principles that make the book the way it is: +\chapter*{Prefacio} + +\markboth{PREFACIO}{PREFACIO} +\addcontentsline{toc}{chapter}{Prefacio} + +%{\it Think Java} is an introduction to computer science and programming intended for readers with little or no experience. +{\it Think Java} es una introducción a las ciencias de la computación (informática) y la programación dirigida a lectores con poca o ninguna experiencia. +%We start with the most basic concepts and are careful to define all terms when they are first used. +Comenzaremos con los conceptos más básicos y pone un cuidado especial en definir cada término cuando se usa por primera vez. +%The book presents each new idea in a logical progression. +El libro presenta cada nueva idea en una progresión lógica. +%Larger topics, like control flow statements and object-oriented programming, are divided into smaller examples and introduced over the course of several chapters. +Los contenidos de más entidad, como las sentencias de control de flujo o la programación orientada a objetos, se dividen en partes más pequeñas y son presentados a lo largo de varios capítulos. + +%This book is intentionally concise. +La intención de este libro es ser conciso. +%Each chapter is 12--14 pages and covers the material for one week of a college course. +Cada capítulo tiene unas 12 páginas y proporciona material para una semana de un curso de enseñanza superior. +%It is not meant to be a comprehensive presentation of Java, but rather, an initial exposure to programming constructs and techniques. +No está concebido para ser una presentación exhaustiva del lenguaje Java, sino una primera toma de contacto con las técnicas y construcciones que se usan en programación. +%We begin with small problems and basic algorithms and work up to object-oriented design. +Comenzaremos con problemas pequeños y algoritmos básicos e iremos progresando hasta el diseño orientado a objetos. +%In the vocabulary of computer science pedagogy, this book uses the ``objects late'' approach. +En el vocabulario de la pedagogía de las ciencias de la computación, este libro usa la aproximación llamada ``objetos tardíos'' (objects late). + + +%\section*{The Philosophy Behind the Book} +\section*{La Filosofía del Libro} + +%Here are the guiding principles that make the book the way it is: +Estos son los principios que hacen que este libro sea como es: \begin{description} -\item[One concept at a time:] -We break down topics that give beginners trouble into a series of small steps, so that they can exercise each new concept in isolation before continuing. - -\item[Balance of Java and concepts:] -The book is not primarily about Java; it uses code examples to demonstrate computer science. -Most chapters start with language features and end with concepts. - -\item[Conciseness:] -An important goal of the book is to be small enough so that students can read and understand the entire text in a one-semester college or AP course. +%\item[One concept at a time:] +\item[Un concepto a la vez:] +%We break down topics that give beginners trouble into a series of small steps, so that they can exercise each new concept in isolation before continuing. +Dividimos los temas que suelen ser mas difíciles y problemáticos para los principiantes en series de pasos pequeños de modo que se pueda entender y practicar cada concepto de forma aislada. + +%\item[Balance of Java and concepts:] +\item[Equilibrio entre enseñar Java y enseñar conceptos:] +%The book is not primarily about Java; it uses code examples to demonstrate computer science. +El principal tema del libro no es Java, es usar la programación como introducción a las ciencias de la computación. +%Most chapters start with language features and end with concepts. +La mayoría de los capítulos comienzan con características del lenguaje y terminan con conceptos. + +%\item[Conciseness:] +\item[Concisión:] +%An important goal of the book is to be small enough so that students can read and understand the entire text in a one-semester college or AP course. %Students can read 1--2 chapters per week, depending on the pace of the instruction. - -\item[Emphasis on vocabulary:] -We try to introduce the minimum number of terms and define them carefully when they are first used. -We also organize them in glossaries at the end of each chapter. - -\item[Program development:] -There are many strategies for writing programs, including bottom-up, top-down, and others. -We demonstrate multiple program development techniques, allowing readers to choose methods that work best for them. - -\item[Multiple learning curves:] -To write a program, you have to understand the algorithm, know the programming language, and be able to debug errors. -We discuss these and other aspects throughout the book and summarize our advice in Appendix~\ref{debugging}. +Uno de los objetivos más importantes del libro es ser suficientemente breve como para que los estudiantes puedan leer y entender el texto completo en un semestre de un curso de educación superior. + +%\item[Emphasis on vocabulary:] +\item[Énfasis en el vocabulario:] +%We try to introduce the minimum number of terms and define them carefully when they are first used. +Intentamos introducir el mínimo número de terminos y definirlos cuidadosamente cuando se usan por primera vez. +%We also organize them in glossaries at the end of each chapter. +También se incluye un glosario al final de cada capítulo. + +%\item[Program development:] +\item[Desarrollo de programas:] +%There are many strategies for writing programs, including bottom-up, top-down, and others. +Hay muchas estrategias para escribir programas, descendiente (top-down), ascendiente (bottom-up), etc. +%We demonstrate multiple program development techniques, allowing readers to choose methods that work best for them. +Se muestran múltiples estrategias y técnicas de desarrollo de programas para permitir que el lector escoja aquella que le funciona mejor. + +%\item[Multiple learning curves:] +\item[Múltiples curvas de aprendizaje:] +%To write a program, you have to understand the algorithm, know the programming language, and be able to debug errors. +Para escribir un programa hay que entender el algoritmo, conocer el lenguaje de programación y ser capaz de depurar los errores que surjan. +%We discuss these and other aspects throughout the book and summarize our advice in Appendix~\ref{debugging}. +Se presentan estos y otros aspectos a lo largo del libro y un resumen de nuestros consejos en el Appendice~\ref{debugging} %\item[Spiral approach:] %Some concepts take time to sink in. @@ -56,31 +83,48 @@ \section*{The Philosophy Behind the Book} \end{description} - -\section*{Object-Oriented Programming} - -Some Java books introduce classes and objects immediately; others begin with procedural programming and transition to object-oriented more gradually. - -Many of Java's object-oriented features are motivated by problems with previous languages, and their implementations are influenced by this history. -Some of these features are hard to explain when people aren't familiar with the problems they solve. - -We get to object-oriented programming as quickly as possible (beginning with Chapter~\ref{immutable}). -But we introduce concepts one at a time, as clearly as possible, in a way that allows readers to practice each idea in isolation before moving on. -So it takes some time to get there. - -You can't write Java programs (even Hello World) without encountering object-oriented features. -In some cases we explain a feature briefly when it first appears, and then explain it more deeply later on. - -If you read the entire book, you will see nearly every topic required for Java SE Programmer I certification. -Supplemental lessons are available in the official Java tutorials on Oracle's website (\url{https://thinkjava.org/tutorial}). - -This book is also well suited to prepare high school students for the AP Computer Science A exam, which includes object-oriented design and implementation. -(AP is a registered trademark of The College Board.) +%\section*{Object-Oriented Programming} +\section*{Programación Orientada a Objetos} + +%Some Java books introduce classes and objects immediately; others begin with procedural programming and transition to object-oriented more gradually. +Algunos libros de Java introducen los conceptos de clase y objeto al principio; otros empiezan con la programación procedural y presentan una transición gradual hacia la orientación a objetos. + +%Many of Java's object-oriented features are motivated by problems with previous languages, and their implementations are influenced by this history. +Muchos aspectos de la orientación a objetos en Java son motivados por problemas existentes en otros lenguajes de programación anteriores, y por tanto están influenciados por ese pasado. +%Some of these features are hard to explain when people aren't familiar with the problems they solve. +Esto hace que algunos de estos aspectos sean difíciles de explicar y de comprender cuando uno no conoce los problemas que motivaron su creación. + +%We get to object-oriented programming as quickly as possible (beginning with Chapter~\ref{immutable}). +Abordamos la Programación Orientada a Objetos lo antes posible (comenzando en el Capítulo~\ref{immutable}). +%But we introduce concepts one at a time, as clearly as possible, in a way that allows readers to practice each idea in isolation before moving on. +Iremos introduciendo los conceptos de uno en uno, de la forma más clara posible y de un modo que permita a los lectores practicar cada uno de forma individual antes de pasar al siguiente. +%So it takes some time to get there. +Conocer y comprender la Programación Orientada a Objetos lleva su tiempo. + +%You can't write Java programs (even Hello World) without encountering object-oriented features. +No se pueden escribir programas Java (ni siquiera el modesto Hola Mundo) sin toparse con aspectos de la Programación Orientada a Objetos. +%In some cases we explain a feature briefly when it first appears, and then explain it more deeply later on. +Por eso en algunos casos daremos una breve explicación de ese aspecto concreto, en el momento en el que aparezca, y se explicará con mas profundidad más adelante. + +%If you read the entire book, you will see nearly every topic required for Java SE Programmer I certification. +Si lees el libro completo, habrás visto prácticamente todas las materias requeridas para la certificación Java SE Programmer I. +%Supplemental lessons are available in the official Java tutorials on Oracle's website (\url{https://thinkjava.org/tutorial}). +Hay disponibles lecciones adicionales en los tutoriales oficiales de Java en el sitio web de Oracle (\url{https://thinkjava.org/tutorial}). + +%This book is also well suited to prepare high school students for the AP Computer Science A exam , which includes object-oriented design and implementation. +%(AP is a registered trademark of The College Board.) +Este libro es también adecuado para preparar a los estudiantes de Ciclos Superiores para el examen "AP Computer Science A" \footnotemark, que incluye diseño e implementación de programas con orientación a objetos. %We introduce nearly every topic in the ``AP Java subset'' with a few exceptions. -A mapping of {\it Think Java} section numbers to the AP course is available on our website: \url{https://thinkjava.org/}. +Se introducen todos los temas del "AP Java subset", con unas pocas excepciones. +%A mapping of {\it Think Java} section numbers to the AP course is available on our website: \url{https://thinkjava.org/}. +La correspondencia entre los números de seccion del {\it Think Java} con los del "AP course" se puede consultar en nuestro sitio web: \url{https://thinkjava.org/}. +\footnotetext{N. del T.: el examen que se menciona es parte del programa "Advanced Placement" (\url{https://apstudents.collegeboard.org/}) de la organización estadounidense "College Board". Este programa +consiste en dar acceso a contenidos de nivel universitario a estudiantes pre-universitarios, de modo que puedan mejorar su educación y obtener visibilidad para estar mejor posicionados a la hora de acceder +a las distintas universidades.} -\section*{Changes to the Second Edition} +%\section*{Changes to the Second Edition} +\section*{Cambios en la Segunda Edición} This new edition was written over several years, with feedback from dozens of instructors and hundreds of students. A complete history of all changes is available on GitHub. diff --git a/ch01.tex b/ch01.tex index 2d52b0b..069b641 100644 --- a/ch01.tex +++ b/ch01.tex @@ -1,41 +1,61 @@ -\chapter{Computer Programming} +\chapter{Programación} \label{theway} -The goal of this book is to teach you to think like a computer scientist. -This way of thinking combines some of the best features of mathematics, engineering, and natural science. -Like mathematicians, computer scientists use formal languages to denote ideas---specifically, computations. -Like engineers, they design things, assembling components into systems and evaluating trade-offs among alternatives. -And like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions. - -\index{problem solving} - -An important skill for a computer scientist is {\bf problem solving}. -It involves the ability to formulate problems, think creatively about solutions, and express solutions clearly and accurately. -As it turns out, the process of learning to program computers is an excellent opportunity to develop problem-solving skills. +%The goal of this book is to teach you to think like a computer scientist. +El objetivo de este libro es enseñarte a pensar como un informático +%This way of thinking combines some of the best features of mathematics, engineering, and natural science. +Este modo de pensar combina algunas de las mejores características de las matemáticas, ingeniería y ciencias naturales. +%Like mathematicians, computer scientists use formal languages to denote ideas---specifically, computations. +Como los matemáticos, los informáticos usan lenguajes formales para expresar ideas---en particular, cálculos. +%Like engineers, they design things, assembling components into systems and evaluating trade-offs among alternatives. +Como los ingenieros, diseñan cosas, ensamblando componentes para crear sistemas y evaluando los pros y contras de las distintas alternativas. +%And like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions. +I como los científicos, observan el comportamiento de sistemas compplejos, construyen hipótesis y comprueban sus predicciones. + +%\index{problem solving} +\index{resolución de problemas} + +%An important skill for a computer scientist is {\bf problem solving}. +Una habilidad importante para un informático es la {\bf resolución de problemas}. +%It involves the ability to formulate problems, think creatively about solutions, and express solutions clearly and accurately. +Incluye la capacidad para formular problemas, pensar soluciones de modo creativo, y ser capaz de expresarlas de modo claro y preciso. +%As it turns out, the process of learning to program computers is an excellent opportunity to develop problem-solving skills. +El proceso de aprender a programar es una excelente oportunidad para desarrollar la habilidad de enfrentar y resolver problemas. %That's why this chapter is called, ``The way of the program''. -On one level, you will be learning to write Java programs, a useful skill by itself. -But on another level, you will use programming as a means to an end. -As we go along, that end will become clearer. - - -\section{What Is a Computer?} - -When people hear the word {\em computer}, they often think of a desktop or a laptop. -Not surprisingly, searching for ``computer'' on Google Images (\url{https://images.google.com/}) displays rows and rows of these types of machines. -However, in a more general sense, a computer can be any type of device that stores and processes data. - -Dictionary.com defines a computer as ``a programmable electronic device designed to accept data, perform prescribed mathematical and logical operations at high speed, and display the results of these operations. -Mainframes, desktop and laptop computers, tablets, and smartphones are some of the different types of computers.'' +%On one level, you will be learning to write Java programs, a useful skill by itself. +En un nivel, aprenderemos a escribir programas Java, que es una habilidad útil. +%But on another level, you will use programming as a means to an end. +Pero en otro nivel, usaremos la programación como un medio para un fin. +%As we go along, that end will become clearer. +Esto se irá viendo más claro segun avancemos. + +%\section{What Is a Computer?} +\section{¿Qué es un Ordenador?} + +%When people hear the word {\em computer}, they often think of a desktop or a laptop. +Cuando la gente oye la palabras {\em ordenador} suelen pensar en un ordenador de sobremesa o un portatil. +%Not surprisingly, searching for ``computer'' on Google Images (\url{https://images.google.com/}) displays rows and rows of these types of machines. +Es normal, si buscamos ``ordenador'' en Google Imagenes (\url{https://images.google.com/}) obtendremos filas y filas de este tipo de máquinas. +%However, in a more general sense, a computer can be any type of device that stores and processes data. +Pero, en un sentido más general, un ordenador es cualquier tipo de dispositivo capaz de almacenar y procesar información. + +%Dictionary.com defines a computer as ``a programmable electronic device designed to accept data, perform prescribed mathematical and logical operations at high speed, and display the results of these operations. +% Mainframes, desktop and laptop computers, tablets, and smartphones are some of the different types of computers.'' +El sitio Dictionary.com define un ordenador como ``un dispositivo electrónico programable diseñado para aceptar datos, realizar operaciones matemáticas y lógicas a alta velocidad y mostrar los resultados de estas operaciones. +Mainframes, portátiles y equipos de escritorio, tabletas y teléfonos inteligentes son algunos de los tipos de ordenadores.'' \index{hardware} -\index{processor} -\index{memory} +\index{procesador} +\index{memoria} \index{CPU} \index{RAM} -Each type of computer has its own unique design, but internally they all share the same type of {\bf hardware}. -The two most important hardware components are {\bf processors} (or CPUs) that perform simple calculations and {\bf memory} (or RAM) that temporarily stores information. -Figure~\ref{fig.cpuram} shows what these components look like. +%Each type of computer has its own unique design, but internally they all share the same type of {\bf hardware}. +Cada tipo de ordenador tiene un diseño único y diferente, pero internamente todos ellos comparten el mismo tipo de {\bf hardware}. +%The two most important hardware components are {\bf processors} (or CPUs) that perform simple calculations and {\bf memory} (or RAM) that temporarily stores information. +Los dos tipos más importantes de componentes hardware son {\bf procesadores} (o CPUs) que realizan los cálculos y {\bf memoria} (o RAM) que almacena temporalmente la información. +%Figure~\ref{fig.cpuram} shows what these components look like. +La figura~\ref{fig.cpuram} muestra el aspecto de estos componentes. \begin{figure}[!ht] \begin{center} @@ -44,47 +64,72 @@ \section{What Is a Computer?} \hspace{2em} %https://commons.wikimedia.org/wiki/File:Memory_module_DDRAM_20-03-2006.jpg \includegraphics[height=11em]{figs/RAM.jpg} -\caption{Example processor and memory hardware.} +%\caption{Example processor and memory hardware.} +\caption{Ejemplo de procesador y memoria.} \label{fig.cpuram} \end{center} \end{figure} -Users generally see and interact with touchscreens, keyboards, and monitors, but it's the processors and memory that perform the actual computation. -Nowadays it's fairly standard, even for a smartphone, to have at least eight processors and four gigabytes (four billion cells) of memory. +%Users generally see and interact with touchscreens, keyboards, and monitors, but it's the processors and memory that perform the actual computation. +Los usuarios generalmente ven e interactuan con pantallas táctiles, teclados, y monitores, pero son el procesador y la memoria los que están realizando los cálculos necesarios para que el sistema funcione. +%Nowadays it's fairly standard, even for a smartphone, to have at least eight processors and four gigabytes (four billion cells) of memory. +Actualmente es bastante común, hasta para un teléfono, tener al menos ocho procesadores y cuatro gigabytes (cuatro billones de celdas) de memoria. -\section{What Is Programming?} +\section{¿Qué es programar?} -\index{program} +\index{programar} -A {\bf program} is a sequence of instructions that specifies how to perform a computation on computer hardware. -The computation might be something mathematical, like solving a system of equations or finding the roots of a polynomial. -It could also be a symbolic computation, like searching and replacing text in a document or (strangely enough) compiling a program. +%A {\bf program} is a sequence of instructions that specifies how to perform a computation on computer hardware. +Un {\bf programa} es una secuencia de instrucciones que especifica como realizar un cálculo usando una computadora. +%The computation might be something mathematical, like solving a system of equations or finding the roots of a polynomial. +El cálculo (o computación) puede ser algo puramente matemático, como resolver un sistema de ecuaciones o hallar las raices de un polinomio. +%It could also be a symbolic computation, like searching and replacing text in a document or (strangely enough) compiling a program. +Puede ser tambien una operación con símbolos, como buscar y sustituir texto en un documento, o convertir código fuente en código ejecutable (compilar un programa). -The details look different in different languages, but a few basic instructions appear in just about every language: +%The details look different in different languages, but a few basic instructions appear in just about every language: +Hay una serie de instrucciones que aparecen en practicamente todos los lenguajes, aunque puedan tener apariencias diferentes en los distintos lenguajes. \begin{description} -\item[input:] Get data from the keyboard, a file, a sensor, or some other device. -\item[output:] Display data on the screen, or send data to a file or other device. -\item[math:] Perform basic mathematical operations like addition and division. -\item[decision:] Check for certain conditions and execute the appropriate code. -\item[repetition:] Perform an action repeatedly, usually with some variation. +%\item[input:] Get data from the keyboard, a file, a sensor, or some other device. +\item[entrada:] Obtener datos desde el teclado, un fichero, un sensor, o algún otro dispositivo. +%\item[output:] Display data on the screen, or send data to a file or other device. +\item[salida:] Presentar datos en pantalla, escribirlos en fichero o enviarlos a otro dispositivo. +%\item[math:] Perform basic mathematical operations like addition and division. +\item[matemáticas:] Efectuar las operaciones matemáticas básicas como sumas, productos, divisiones, etc. +%\item[decision:] Check for certain conditions and execute the appropriate code. +\item[decisiones:] Comprobar ciertas condiciones y ejecutar las instrucciones apropiadas en cada caso. +%\item[repetition:] Perform an action repeatedly, usually with some variation. +\item[repeticion:] ejecutar unas instrucciones repetidamente, habitualmente con alguna variación. \end{description} -\index{programming} +\index{programar} + +%Believe it or not, that's pretty much all there is to it. +Lo creas o no, eso es básicamente programar. +%Every program you've ever used, no matter how complicated, is made up of small instructions that look much like these. +Todos los programas que has usado alguna vez, no importa como de complicados fueran, están hechos de pequeñas instrucciones como las que hemos descrito arriba. +%So you can think of {\bf programming} as the process of breaking down a large, complex task into smaller and smaller subtasks. +Por tanto, {\bf programar} es el proceso de descomponer una tarea larga y compleja en subtareas más pequeñas. +%The process continues until the subtasks are simple enough to be performed with the electronic circuits provided by the hardware. +El proceso continua hasta que las subtareas son tan simples que se pueden realizar con los circuitos electrónicos que componen el hardware. -Believe it or not, that's pretty much all there is to it. -Every program you've ever used, no matter how complicated, is made up of small instructions that look much like these. -So you can think of {\bf programming} as the process of breaking down a large, complex task into smaller and smaller subtasks. -The process continues until the subtasks are simple enough to be performed with the electronic circuits provided by the hardware. +%\section{The Hello World Program} +\section{El programa Hola Mundo} +%\label{hello} +\label{hola} +%Traditionally, the first program you write when learning a new programming language is called the ``Hello World'' program. +Tradicionalmente el primer programa que uno escribe cuando aprende un lenguaje de programación nuevo es el ``Hola Mundo''. +%All it does is output the words {\tt Hello, World!} to the screen. +Este programa lo único que hace es imprimer las palabras {\tt Hola Mundo} por pantalla. +%In Java, it looks like this \footnotemark: +En Java, tendría este aspecto \footnotemark: -\section{The Hello World Program} -\label{hello} -Traditionally, the first program you write when learning a new programming language is called the ``Hello World'' program. -All it does is output the words {\tt Hello, World!} to the screen. -In Java, it looks like this: +\footnotetext{N. del T.: he decidido no traducir dentro del código fuente. Es decir, la clase Hello se va a seguir llamando Hello y no Hola. +Creo que es un trabajo innecesario y que el riesgo (alto) de introducir errores en el código, no compensa. +Además en muchos entornos académicos y profesionales se exige programar con nombres de variables/funciones en Inglés.} % NOTE(ABD): I changed a lot of ``print'' to ``display'', partly to be % more precise, but also to reduce the number of times ``print'' appears, @@ -103,13 +148,15 @@ \section{The Hello World Program} } \end{trinket} -When this program runs, it displays the following: +%When this program runs, it displays the following: +Cuando este programa se ejecuta presenta lo siguiente en pantalla: \begin{stdout} Hello, World! \end{stdout} -Notice that the output does not include the quotation marks. +%Notice that the output does not include the quotation marks. +Date cuenta de que las comillas no se imprimen. %\index{public} %\index{static} @@ -120,20 +167,23 @@ \section{The Hello World Program} %In fact, we won't be able to explain all of them for several more chapters. %But we can start with the structure. -\index{statement} -\index{print statement} +\index{instrucción} +\index{instrucción print} -Java programs are made up of {\em class} and {\em method} definitions, and methods are made up of {\em statements}. -A {\bf statement} is a line of code that performs a basic action. -In the Hello World program, this line is a {\bf print statement} that displays a message to the user: +%Java programs are made up of {\em class} and {\em method} definitions, and methods are made up of {\em statements}. +Los programas Java están compuestos por definiciones de {\em clases} and {\em métodos}, y los métodos están compuestos por {\em instrucciones}. +%A {\bf statement} is a line of code that performs a basic action. +Una {\bf instrucción} es una línea de código que realiza una acción básica. +%In the Hello World program, this line is a {\bf print statement} that displays a message to the user: +En el programa Hola Mundo, la siguiente línea es una {\bf instrucción print} que presenta un mensaje al usuario: \begin{code} System.out.println("Hello, World!"); \end{code} \index{println} -\index{semicolon} -\index{; semicolon} +\index{punto y coma} +\index{; punto y coma} \java{System.out.println} displays results on the screen; the name \java{println} stands for ``print line''. Confusingly, {\em print} can mean both ``display on the screen'' and ``send to the printer''. diff --git a/ch02.tex b/ch02.tex index fef64c9..66978a4 100644 --- a/ch02.tex +++ b/ch02.tex @@ -1,16 +1,20 @@ -\chapter{Variables and Operators} +\chapter{Variables y Operadores} \label{variables} -This chapter describes how to write statements using {\em variables}, which store values like numbers and words, and {\em operators}, which are symbols that perform a computation. -We also explain three kinds of programming errors and offer additional debugging advice. +%This chapter describes how to write statements using {\em variables}, which store values like numbers and words, and {\em operators}, which are symbols that perform a computation. +Este capítulo describe como escribir instrucciones usando {\em variables}, que almacenan valores como números y palabras, y {\em operadores}, que son símbolos que realizan cálculos. +%We also explain three kinds of programming errors and offer additional debugging advice. +También explicaremos tres tipos de errores de programación y algunos consejos para depurarlos. %Understanding what can go wrong will help you get it right. %Finally we discuss the rules of code style, which helps make programs easier to read and debug. -To run the examples in this chapter, you will need to create a new Java class with a \java{main} method (see Section~\ref{hello}). -Throughout the book, we often omit class and method definitions to keep the examples concise. +%To run the examples in this chapter, you will need to create a new Java class with a \java{main} method (see Section~\ref{hello}). +Para ejecutar los ejemplos de este capítulo necesitarás crear una clase Java con un método \java{main} (ver Sección~\ref{hello}). +%Throughout the book, we often omit class and method definitions to keep the examples concise. +A lo largo del libro a menudo omitiremos las definiciones de las clases y los métodos, para mantener los ejemplos de código lo más breves posibles. - -\section{Declaring Variables} +%\section{Declaring Variables} +\section{Declarar Variables} %NOTE: in response to review comments, I am cleaning up the use of % ``memory''. I would like to avoid talking about hardware, or being @@ -20,29 +24,38 @@ \section{Declaring Variables} % that. I'd rather offer the abstract model that a variable indicates % a location that contains a value. +%\index{variable} +%\index{value} \index{variable} -\index{value} - -One of the most powerful features of a programming language is the ability to define and manipulate variables. -A {\bf variable} is a named location in memory that stores a {\bf value}. -Values may be numbers, text, images, sounds, and other types of data. +\index{valor} + +%One of the most powerful features of a programming language is the ability to define and manipulate variables. +Una de las funcionalidades más potentes de un lenguaje de programación es la habilidad de definir y manipular variables. +%A {\bf variable} is a named location in memory that stores a {\bf value}. +Una {\bf variable} es un nombre que se asocia a una zona de la memoria donde se almacena un {\bf valor} +%Values may be numbers, text, images, sounds, and other types of data. +Este valor puede ser un número, texto, una imagen, un sonido o cualquier otro tipo de dato. %They can be printed, and as we'll see later, operated on. -To store a value, you first have to declare a variable: +%To store a value, you first have to declare a variable: +Para poder almacenar un valor, primero hay que declarar la variable: %Since the values we want to store are text, we declare that the new variable is a string: \begin{code} String message; \end{code} -\index{declaration} -\index{statement!declaration} -\index{type!int} -\index{type!char} -\index{type!String} - -This statement is called a {\bf declaration}, because it declares that the variable \java{message} has the type \java{String}. -Each variable has a {\bf type} that determines what kind of values it can store. -For example, the \java{int} type can store integers like \java{1} and \java{-5}, and the \java{char} type can store characters like \java{'A'} and \java{'z'}. +\index{declaración} +\index{instrucción!declaración} +\index{tipo!int} +\index{tipo!char} +\index{tipo!String} + +%This statement is called a {\bf declaration}, because it declares that the variable \java{message} has the type \java{String}. +Esta instrucción se llama una {\bf declaración} porque declara que la variable \java{message} es de tipo \java{String}. +%Each variable has a {\bf type} that determines what kind of values it can store. +Cada variable tiene un {\bf tipo} que determina el tipo de valores que puede almacenar. +%For example, the \java{int} type can store integers like \java{1} and \java{-5}, and the \java{char} type can store characters like \java{'A'} and \java{'z'}. +Por ejemplo, el tipo \java{int} puede almacenar enterios como \java{1} y \java{-5}, y el tipo \java{char} puede almacenar caracteres como \java{'A'} y \java{'z'}. Some types begin with a capital letter and some with lowercase. You will learn the significance of this distinction later, but for now you should take care to get it right. diff --git a/thinkjava2.tex b/thinkjava2.tex index 741d5c4..d03877c 100644 --- a/thinkjava2.tex +++ b/thinkjava2.tex @@ -77,6 +77,7 @@ \usepackage{comment} \excludecomment{htmlonly} \includecomment{latexonly} +\usepackage[spanish,es-noshorthands]{babel} %END LATEX \input{latexonly.tex}