Entrada de datos con Scanner de Java

¿Para qué nos sirve la clase Scanner?

La clase Scanner es la clase más sencilla para poder leer datos de un programa de Java. Scanner, por tanto, se encarga de proporcionarnos un conjunto de métodos cuya finalidad es el permitirnos leer valores de entrada de distintas fuentes.

Librerías necesarias para trabajar con Scanner

Aunque la podemos autoImportar al realizar la declaración del objeto Scanner (lo veremos en el siguiente apartado), la librería encargada de realizar los imports para que nuestra clase Scanner funcione correctamente será:

import java.util.Scanner;

Crear el objeto Scanner

Creamos el objeto Scanner mediante a Scanner sc = new Scanner(); y dentro de los paréntesis, le especificamos el Sistem.in o también le podríamos añadir un archivo(File, aunque esto no lo veremos en este ejemplo).

Tipos de datos entrada

Existen diferentes tipos de datos y por ello, la clase scanner en función del tipo de dato introducido, utiliza distintos métodos para capturar un tipo de dato u otros en función del tipo de datos que se introduzca:

  • nextInt() lee un valor int introducido por el usuario:
  • nextLong() lee un valor long introducido por el usuario.
  • nextShort() lee un valor short introducido por el usuario.
  • nextDouble() lee un valor double introducido por el usuario.
  • nextByte() lee un valor byte introducido por el usuario.
  • nextBoolean() lee un valor boolean introducido por el usuario.
  • nextLine() lee un valor String introducido por el usuario.

Scanner con cadena de texto (String)

Vamos a crear un ejemplo de un programa que nos solicite nuestro nombre y posteriormente nos salude.

Cuando trabajamos con Scanner, se aconseja meter todo dentro de un try Catch para evitar excepciones. Aunque cuando utilizamos el método que captura cadenas de texto nextLine() podemos afirmar que es el más permisivo de todos y no como norma general no lo requería como tal.

Resultado:

Scanner con Enteros (int)

Vamos a crear un ejemplo de la creación de un programa que nos solicite un número entero. Y posteriormente, nos aparezca un mensaje de si el número es par u impar.

Resultados:

En este tipo de entrada, podemos observar que el resultante empieza a ser mucho menos permisivo y tener le try catch dentro de la clase nos puede evitar que al generarse un valor programa detenga muchos problemas.

Si el número es par:

Si el número es impar:

En este caso, podemos evaluar los diferentes errores que podemos recibir. Si intentamos poner un 1,0 o 1.0:

Pero si no es un número, nos encontramos con un mensaje inesperado:

Vamos a controlar la excepción mediante a un try catch, en este caso, usaremos el Excepción que es el padre de todas las excepciones.

Y ahora aunque sigue siendo un error, en este caso, sería controlado.

Scanner con Double con UseLocale

En el ejemplo anterior, no tenemos el problema de los decimales debido a que es un entero. Pero si empezamos a trabajar por ejemplo con un double, una posible solución sería la siguiente:

Aunque nos encontramos con el problema que si utilizamos el decimal con punto o con coma, el resultado será muy distinto:

Si introducimos un número decimal con punto:

Si introducimos un número decimal con coma, nos encontramos con el siguiente error:

Si evolucionamos el ejemplo anterior, tendremos como resultado:

Y ahora, finalmente, podemos testear que la coma funciona correctamente.

Bueno, ya hemos visto como trabajar con varios tipos de de datos de entrada y con useLocale. Y hemos trabajado con String, int, y double. Si os fijáis el trabajar con tipo de dato u otro no tiene mucha diferencia. Un saludo javer@s!

96 comentarios

  1. Frenando Martínez

    18 octubre, 2019 a las 11:02

    Buenos días :
    Estoy siguiendo vuestro curso, y tengo varias dudas, he pasado del nivel 0 al nivel 1 y de repente hay 10 ejercicios con cadenas de texto , que no encuentro cuando lo habéis explicado, me pasa lo mismo con los:
    if, else,case, no los encuentro,la verdad estoy un poco pedido.
    Por favor, a ver si me podéis ayudar.
    Muchas Gracias y un saludo.

    • admin

      21 octubre, 2019 a las 8:38

      Buenas Fernando,

      Antes de nada gracias por el feedback.
      Tomo nota, estoy trabajando en varios niveles e intentaré en medida de lo posible completar los ejercicios con una explicación lo antes posible.
      Pese a ello, te aconsejo que por el momento investigues tu mismo por tu cuenta sobre el tema, mirando que hace cada método o analizando lo que hago en los bucles.
      En la programación ser autodidacta te va a dar un añadido que cada día es más necesario por ello te aconsejo que como ejercicio trabajes esa faceta. Si ves que tienes cualquier duda que no eres capaz de resolver, no dudes en contactarme.

      Un saludo

  2. Quality content is the main to be a focus for the visitors to pay a quick visit the
    web site, that’s what this web page is providing.

  3. This is really interesting, You’re a very skilled blogger.

    I’ve joined your feed and look forward to seeking more of your excellent post.
    Also, I’ve shared your site in my social networks!

    Feel free to visit my page: Artctic Box AC

  4. I’m also commenting to let you be aware of of the remarkable experience my cousin’s princess obtained reading through yuor web blog.
    She even learned too many pieces, most notably what it is like
    to possess an excellent coaching character to get most people
    very easily thoroughly grasp chosen specialized subject areas.
    You truly exceeded people’s desires. Many thanks for producing those
    necessary, trustworthy, edifying and as well as fun tips on the topic to Gloria.

    Look into my blog … 80gm.net

  5. Nice answers in return of this issue with solid arguments and telling all regarding that.

    Visit my web page … Insights CBD Gummies Price [forum.adm-tolka.ru]

  6. Hello, this weekend is good designed for me, as this point in time i am reading
    this wonderful educational article here at my home.

    My blog … https://housetheland.com

  7. This is really interesting, You’re a very skilled blogger. I
    have joined your feed and look forward to seeking more of your great post.
    Also, I have shared your website in my social networks!

  8. Right here is the perfect website for everyone who hopes to find out about this topic.
    You realize so much its almost hard to argue with you (not that I
    really will need to…HaHa). You certainly put a fresh spin on a subject that has been written about for years.
    Great stuff, just wonderful!

  9. Hello, Neat post. There’s an issue together with your site in internet
    explorer, could check this? IE still is the marketplace leader and a large component to people will miss your magnificent writing due to this
    problem.

    Also visit my blog … http://www.fles.hlc.edu.tw

  10. Hello to all, how is the whole thing, I think every one is getting more from this web page, and your views are fastidious in support of new visitors.

    My web site: Viking XL Keto BHB

  11. We are a group of volunteers and starting a brand new scheme
    in our community. Your website provided us with helpful info to work on. You’ve done
    an impressive job and our whole neighborhood
    can be thankful to you.

    my homepage; True Keto

  12. Some really fantastic posts on this site, thanks for contribution.

    My page Arctos Air Cooler Review

  13. I’m still learning from you, but I’m trying to reach my goals.

    I definitely love reading all that is written on your site.Keep the aarticles coming.
    I liked it!

    Stop by my site: Keto Incinerate Review

  14. Incredible! This blog looks just like my old one!
    It’s on a totally different topic but it has pretty much the same layout and design. Superb choice of colors!

    my page: Optimum Keto Pills (http://www.tpspa.net)

  15. Great weblog right here! Also your web site rather
    a lot up very fast! What host are you the use of?
    Can I am getting your associate link for your host? I desire my web site loaded up as fast as yours lol

  16. I do not know if it’s just me or if perhaps everybody else encountering issues with your site.
    It looks like some of the written text within your content are running off the
    screen. Can someone else please comment and let me know if this is happening to them too?
    This may be a issue with my internet browser because
    I’ve had this happen previously. Thanks

  17. I like this web site very much so much great info.

    Here is my page – Optimum Keto

  18. You actually make it seem so easy with your presentation however I to find this matter
    to be really one thing which I think I’d never understand.
    It seems too complex and extremely extensive for me. I’m having
    a look ahead on your next post, I will try to get the grasp of it!

    Also visit my web site … Green Earth CBD Gummies Review

  19. Some genuinely wonderful content on this website, thanks for contribution.

    Here is my web site; Derma Ella Advanced Skin Care Reviews

  20. Hello there! I could have sworn I’ve been to your blog before but after
    browsing through many of the articles I realized it’s new to me.
    Nonetheless, I’m definitely happy I stumbled upon it and I’ll be
    book-marking it and checking back frequently!

    My blog post … Moscatcher Mosquito Zapper (forum.adm-tolka.ru)

  21. I have to thank you for the efforts you have put in penning this site.

    I really hope to view the same high-grade blog posts by you in the future as well.
    In truth, your creative writing abilities has encouraged me to get my own blog now 😉

    My blog; Wawza Apple Cider Vinegar, http://www.mhes.tyc.edu.tw/userinfo.php?uid=3673524,

  22. I ᥙsed to be able to find good information from your content.

    Here іs my ԝeb bⅼog; klik disini

  23. Howdy very nice blog!! Man .. Excellent .. Amazing ..
    I’ll bookmark your web site and take the feeds also…I’m glad to find so many
    helpful info right here within the publish, we want develop extra
    techniques on this regard, thank you for sharing.

    Feel free to visit my homepage … hotelforrest.ru

  24. continuously i used to read smaller articles which as well clear their motive, and that is also
    happening with this piece of writing which I am reading at this place.

    Also visit my web blog Green Leaf Hills

  25. I conceive this web site has got some rattling good info for everyone :
    D.

    Also visit my web page: Luiresse Reviews

  26. My partner and I absolutely love your blog and find the majority of your post’s to be
    what precisely I’m looking for. Do you offer guest
    writers to write content for you? I wouldn’t mind composing a post
    or elaborating on a number of the subjects you write about here.
    Again, awesome weblog!

  27. Hey there, You have done a great job. I will definitely digg it and in my opinion recommend to my friends.
    I’m sure they’ll be benefited from this site.

    My web-site Arctos Portable AC

  28. Hey there! This is my first visit to your blog!
    We are a team of volunteers and starting a new initiative in a community in the same niche.
    Your blog provided us useful information to work on. You have done a marvellous job!

  29. I love your blog.. very nice colors & theme. Did you
    design this website yourself or did you hire someone to
    do it for you? Plz respond as I’m looking
    to create my own blog and would like to know where u got
    this from. kudos

  30. Everything is very open with a clear description of the challenges.

    It was truly informative. Your website is extremely helpful.

    Many thanks for sharing!

    Here is my blog post :: Sparkling Pure CBD

  31. This info is worth everyone’s attention. How can I find out more?

  32. I do trust all of the ideas you’ve introduced for your post.

    They’re very convincing and will certainly work. Nonetheless, the posts are very short
    for novices. Could you please prolong them a bit from subsequent time?
    Thank you for the post.

    Also visit my site … forum.techzooka.com

  33. Wow, wonderful blog layout! How lengthy have you been blogging for?

    you made running a blog glance easy. The whole glance of your website is magnificent,
    let alone the content!

    Here is my webpage; forum.adm-tolka.ru

  34. Hello! Do you know if they make any plugins to help with SEO?

    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains.
    If you know of any please share. Appreciate it!

  35. I do not even know how I stopped up here, but I assumed this post was good.
    I don’t understand who you might be but definitely you are going to a famous blogger in the event you aren’t already
    😉 Cheers!

    Feel free to visit my homepage http://donkhamin.go.th/webboard/index.php?action=profile;u=261344

  36. There is noticeably a lot to identify about this.
    I suppose you made certain good points in features also.

    My web-site; Keto Max XR Pills

  37. I every time spent my half an hour to read this webpage’s
    articles or reviews daily along with a cup of coffee.

    Take a look at my blog: Niva CBD

  38. Excellent blog here! Also your web site loads up very fast!
    What host are you using? Can I get your affiliate link to your host?
    I wish my website loaded up as quickly as yours lol

    my site Ketorol Pills

  39. It’s a pity you don’t have a donate button! I’d certainly donate to
    this outstanding blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will share this blog with my Facebook group.
    Talk soon!

  40. Greetings from Carolina! I’m bored to death at work so I decided to
    browse your site on my iphone during lunch break. I enjoy the info you provide here and can’t wait to take a
    look when I get home. I’m surprised at how quick your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyhow, excellent blog!

    my blog … Eagle CBD Gummies

  41. Good day! Do you use Twitter? I’d like to follow you if
    that would be ok. I’m absolutely enjoying your blog and look forward to new
    updates.

    Feel free to visit my web site … Keto Secret Review

  42. Valuable info. Fortunate me I discovered your site accidentally, and I’m surprised why this coincidence didn’t came about in advance!
    I bookmarked it.

  43. Can you tell us more about this? I’d love to find out some additional information.

    My blog post Keto Incinerate Advanced Weight Loss

  44. Hey there! This post could not be written any better!
    Reading through this post reminds me of my previous room mate!
    He always kept chatting about this. I will forward this article to him.
    Fairly certain he will have a good read. Thanks for sharing!

    Here is my website; Optimum Keto Review

  45. Just what I was looking for, regards for posting.

    My homepage – Natural Burn Keto Pills

  46. I got this web site from my pal who told me regarding this site and now this
    time I am visiting this web page and reading very informative
    content at this time.

  47. Howdy, I believe your web site may be having internet browser compatibility problems.
    Whenever I take a look at your web site in Safari, it looks fine however, if opening in IE, it’s got some overlapping issues.
    I merely wanted to provide you with a quick heads up!

    Aside from that, excellent blog!

    My web page: Bio Shed Keto

  48. It’s impressive that you are getting thoughts
    from this piece of writing as well as from our discussion made at this time.

  49. I don’t even know how I stopped up right here, but I assumed this
    post used to be good. I don’t know who you’re however definitely you are going to a well-known blogger if you
    happen to aren’t already. Cheers!

  50. I do not even know the way I finished up here, however I thought this publish was once great.

    I don’t recognize who you’re however definitely
    you are going to a well-known blogger if you happen to aren’t already.
    Cheers!

    Here is my web blog :: Niva CBD Gummies

  51. Some truly nice and useful information on this web site,
    likewise I think the style has got excellent features.

    My blog – mhes.tyc.edu.tw

  52. Hi, this weekend is pleasant in support of me, since this
    time i am reading this impressive educational piece of writing here at my home.

  53. Thank you for some other informative web site. The place
    else could I am getting that kind of info written in such a perfect
    approach? I’ve a challenge that I’m just now working on, and I have been at the look out for such information.

    Here is my web page … Primiene Review

  54. I really appreciate this post. I’ve been looking all
    over for this! Thank goodness I found it on Bing.
    You have made my day! Thanks again!

    My page … Wawza Gummies

  55. hello there and thank you for your info ? I have definitely picked up anything new from right here.
    I did however expertise a few technical points using this website,
    as I experienced to reload the website lots of times previous to I could get it to
    load properly. I had been wondering if your hosting is OK?

    Not that I’m complaining, but slow loading instances times will very frequently affect
    your placement in google and can damage your high-quality
    score if ads and marketing with Adwords. Anyway
    I am adding this RSS to my email and can look out for a lot
    more of your respective exciting content.
    Ensure that you update this again very soon.

    my web-site: Green CBD Gummies

  56. Very interesting topic, thanks for putting up.

    My blog post … Yec Keto

  57. Every weekend i used to visit this web site, for the reason that i
    want enjoyment, as this this site conations truly nice funny data too.

    Feel free to surf to my homepage: http://www.associazioneingegnerichieti.it

  58. Your style is unique compared to other people I’ve read stuff from.

    Many thanks for posting when you have the opportunity, Guess I will
    just bookmark this web site.

  59. Thank you a bunch for sharing this with all people you
    really know what you are talking about! Bookmarked.
    Kindly also visit my website =). We may have a link exchange contract among us!

    Have a look at my webpage MaxBHB

  60. Greetings! Very useful advice within this article! It is the little changes that
    produce the largest changes. Thanks a lot for sharing!

  61. I am always thought about this, thank you for posting.

    My page; Pure Keto Burn

  62. Magnificent beat ! I wish to apprentice while you amend
    your site, how could i subscribe for a blog site? The account helped me a acceptable deal.
    I had been tiny bit acquainted of this your broadcast provided bright clear
    idea

    Stop by my homepage :: True Burn Keto Cost – http://www.fotosombra.com.br,

  63. It’s nearly impossible to find well-informed people for
    this topic, but you sound like you know what you’re talking about!
    Thanks

    my web page … Total Keto 365 Reviews

  64. Yay google is my queen helped me to find this outstanding
    web site!

    Take a look at my homepage … Kirk

  65. This is the perfect site for everyone who really wants to
    find out about this topic. You realize a whole lot its almost hard to argue with you (not that I actually
    will need to…HaHa). You definitely put a brand new spin on a topic which has been discussed for ages.
    Wonderful stuff, just wonderful!

    Feel free to surf to my web site; olm.nicht-wahr.de

  66. Magnificent items from you, man. I have have in mind your stuff prior to and you’re simply
    extremely fantastic. I actually like what you have acquired right here, certainly
    like what you’re saying and the way in which wherein you assert it.
    You are making it entertaining and you still care for to stay it smart.
    I can not wait to learn much more from you. This is actually a tremendous site.

    Stop by my webpage Infinuity CBD Gummies

  67. Heya i am for the primary time here. I found this board and I
    in finding It really useful & it helped me out much.
    I am hoping to provide something back and aid others like you helped me.

  68. I’ve been surfing online more than 4 hours today, yet
    I never found any interesting article like yours. It’s pretty worth enough for me.
    In my view, if all webmasters and bloggers made good content as you did,
    the internet will be much more useful than ever
    before.

    Stop by my web blog … Aizen Power

  69. It’s wonderful that you are getting thoughts from this article as
    well as from our discussion made at this time.

  70. It is perfect time to make some plans for the future and it’s time to
    be happy. I’ve read this post and if I could I
    desire to suggest you some interesting things or tips. Perhaps you can write next articles referring to this article.
    I want to read more things about it!

  71. It’s very simple to find out any matter on net as compared to
    books, as I found this article at this web page.

    My web page: Biodermeux Cream

  72. I was examining some of your posts on this website and I believe
    this site is really instructive! Keep on posting.

    Also visit my blog Strawberry CBD Gummies Reviews

  73. Thanks for the auspicious writeup. It in truth was a leisure
    account it. Glance complex to far brought agreeable from you!
    By the way, how can we keep in touch?

    my homepage – http://www.koan.at/UserProfile/tabid/61/userId/194708/Default.aspx

  74. Hi there! Would you mind if I share your blog with my twitter
    group? There’s a lot of people that I think would really enjoy your content.
    Please let me know. Thanks

  75. Wow! Thank you! I always wanted to write on my blog something like that.
    Can I take a portion of your post to my website?

    Also visit my website: Bio Wellness CBD Gummies Review

  76. Hiya, I’m really glad I’ve found this information. Nowadays bloggers publish just about gossips
    and web and this is actually irritating. A good web site with exciting
    content, this is what I need. Thank you for keeping this web site,
    I will be visiting it. Do you do newsletters?

    Cant find it.

    Here is my blog post – http://www.comptine.biz/modules.php?name=Your_Account&op=userinfo&username=StilwellFlorian

  77. Hey I know this is off topic but I was wondering if you knew of
    any widgets I could add to my blog that automatically tweet my newest twitter updates.

    I’ve been looking for a plug-in like this for quite some time and
    was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look
    forward to your new updates.

  78. Thank you for being my teacher on this theme. I actually enjoyed your own article greatly and
    most of all favored how you really handled the issues I widely known as controversial.
    You’re always quite kind towards readers like me and assist
    me in my living. Thank you.

    Look into my web page; Frost Portable AC

  79. Hello. Great job. I did not imagine this. This is a great story.

    Thanks!

    Look into my web site … Tacoma Farms CBD Reviews

  80. I like reading through an article that will make men and
    women think. Also, thank you for allowing me to comment!

    Review my homepage: Rapid Fire Keto

  81. Thanks for sharing your thoughts on omega 3. Regards

    Also visit my blog :: Infinity CBD

  82. What’s up every one, here every one is sharing such familiarity, therefore it’s fastidious to read this weblog,
    and I used to pay a quick visit this web site daily.

    my web page – Health Flow Pills Review

  83. Do you mind if I quote a couple of your posts
    as long as I provide credit and sources back to your webpage?
    My blog is in the very same niche as yours and my visitors would really benefit from some
    of the information you provide here. Please let me know if this alright with you.

    Cheers!

  84. Spot on with this write-up, I honestly feel this amazing site needs much
    more attention. I’ll probably be returning to read through more, thanks for the info!

    my blog Infinity CBD Review

  85. I am really impressed with your writing abilities and also with the layout for your blog.
    Is this a paid subject or did you modify it yourself?
    Either way keep up the excellent quality writing, it is uncommon to
    look a great blog like this one today..

    Feel free to surf to my blog post; Summer Valley CBD Gummies Reviews

  86. I really enjoy reading through on this website, it has great posts.

    Also visit my website :: TestoXmen

  87. Hi this is kinda of off topic but I was wanting to
    know if blogs use WYSIWYG editors or if you have to manually code with HTML.

    I’m starting a blog soon but have no coding skills so I wanted to get advice
    from someone with experience. Any help would be enormously appreciated!

  88. Great blog here! Also your web site loads up fast! What
    host are you using? Can I get your affiliate link to your host?
    I wish my website loaded up as fast as yours lol asmr https://app.gumroad.com/asmr2021/p/best-asmr-online asmr

  89. I wanted to follow up and let you know how great I valued discovering your web blog today.

    I’d consider it a real honor to work at my office and
    be able to operate on the tips discussed on your website and also participate in visitors’ remarks like this.
    Should a position of guest article writer become available at your
    end, remember to let me know.

    Also visit my web-site … 163.30.42.16

  90. Hello, I think your blog might be having browser compatibility issues.
    When I look at your website in Safari, it looks fine but when opening
    in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, awesome blog!

    Feel free to surf to my webpage: Bell

  91. Hi! This is my first visit to your blog! We are a group of volunteers
    and starting a new initiative in a community in the
    same niche. Your blog provided us useful information to work on. You have done
    a extraordinary job! cheap flights http://1704milesapart.tumblr.com/ cheap flights

  92. I do not even understand how I stopped up right here, but I
    thought this submit used to be great. I don’t understand who you
    might be however certainly you’re going to a famous blogger when you are not already.
    Cheers!

    Feel free to visit my web site :: Denise

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.

Cerrar