How do I use the Scanner class to read in sentence as 1 string?

From my code:
Scanner scan=new Scanner(System.in);
String message="";
System.out.println("Enter message: ");//get message to transmit
message=scan.next();
System.out.println("Message: " + message + " will be used for the simulation");I would like to store the user input as 1 string in the variable message; even if the user enters an entire sentence with whitespace. However, using next() does not do this (I believe it auto delimits at white space) and using nextLine() does not let the user even enter text. The command line looks like this:
Enter message:
Message: will be used for the simulation
I tried fiddling around with setting the delimit but the program would then hang after the user typed something. I'm assuming there's a simple way to do this that I'm missing.
This is part of a larger program which expects String message to be one string with all the user input. Thanks.
Edited by: csnoob on Apr 15, 2009 3:10 AM

Maybe you are confusing things somewhere but your code runs fine replacing next() with nextLine()
Scanner scan = new Scanner(System.in);
String message="";
System.out.println("Enter message: ");//get message to transmit
message=scan.nextLine();
System.out.println("Message: " + message + " will be used for the simulation");Mel

Similar Messages

  • Anyone use the scanner class?

    The scanner class makes command line input easy:
    Scanner input = new Scanner(System.in);
    input.nextLine() returns the string
    My result always appears before the input is shown. For example:
    Please enter a string: You entered this is a string
    this is a string<--the user input isn't displayed after the prompt.
    How do I make the user input appear right after the prompt? Thank you.

    ShaqDiesel wrote:
    The scanner class makes command line input easy:
    Scanner input = new Scanner(System.in);
    input.nextLine() returns the string
    My result always appears before the input is shown. For example:
    Please enter a string: You entered this is a string
    this is a string<--the user input isn't displayed after the prompt.
    How do I make the user input appear right after the prompt? Thank you.What? I don' understand your post. What is expected result, and what do you get?
    Kaj

  • How to use the scanner class to ask for a character?

    Hey guys, this is my assignment:
    Ask the user for a single letter and a sentence, and print out the
    number of times that letter shows up in the sentence.
    Please tell me how to scan for a character. I tried this:
    import java.util.Scanner;
    public class Frequencies
        public static final void main(String[] args)
            Scanner scanner = new Scanner(System.in);
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter a sentence");
            String x = scanner.next();
            System.out.println("Enter a letter to look for");
            String y = scan.next();
            char z = y.charAt(0);
            int chara = 0;
            for(int i = 0; i<x.length(); i++){
                    if(z==y.charAt(i)){
                            chara = chara++;
            System.out.println("There are " + chara + " " + z + "s in the sentence");
    }and got the error after Running (not compiling):
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
            at java.lang.String.charAt(String.java:687)
            at Frequencies.main(Frequencies.java:16)I thought this meant that I was asking for the character in postition 1 of string y, but in my code I wrote position 0
    when I tried inserting words in the character place (just to see what happened, not expecting functionallity, I got
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: [NUMBER OF CHARACTERS]
            at java.lang.String.charAt(String.java:687)
            at Frequencies.main(Frequencies.java:16)Please help.
    The assignment isn't due nor graded, this is just killing me lol.
    Thanks in advance
    Edited by: Sevan on Oct 18, 2008 4:40 PM

    jverd wrote:
    Skydev2u wrote:
    I've used this method for a while now and it gets the job done.
    import java.util.Scanner;
    public class ReadInput {
    public static void main(String[] args) {
    Scanner UserInput = new Scanner(System.in);
    char letter = UserInput.findWithinHorizon(".", 0).charAt(0);
    I know you're trying to help, but this isn't really doing it. It does nothing to address the source of the OP's problem. The way he's doing it now is almost right. He just needs to do a tiny bit of detective work to fix a small bug. Tossing off a totally different approach, with no explanation, is not particularly helpful.Your right jverd I skimmed the OP's problem too quick;y and in tern didn't understand it fully. After reading the post thoroughly I saw that the problem can be solved by taking the sentence the user enters and then converting it into a array of characters. Then searching for the specific letter the user enters is achieved by comparing it to each individual element of the char array. Then incrementing a counter variable each time a match is made. I hope this example code solve your problem.
    * @author skydev
    import java.util.Scanner;
    public class SentenceReader {
        public static void main(String[] args) {
            int counter = 0; //Amount of time the letter appears in the sentence
            char letter;    //Letter the user search for
            char[] sentenceArray; //char array to hold the elements of the string the user inputs
            String sentence; //sentence the user inputs
            Scanner UserInput = new Scanner(System.in);
            System.out.println("Please enter a sentence! ");
            sentence = UserInput.nextLine();
            sentenceArray = sentence.toCharArray(); //splits up the users sentence into a array of char
            System.out.println("Please enter a letter to search for ");
            letter = UserInput.findWithinHorizon(".", 0).charAt(0);
             for(int i = 0; i < sentence.length(); i++){
                    if(letter == sentenceArray){ //search to see if the letter of interest equals to each char (letter) of the array
    counter++; //increments the amount of time the letter appears, set to 0 by default
    System.out.println("The letter appeared " + counter + " times in the sentence"); //Displays the result :) I love programming

  • Can anyone help me with this program using the Scanner Class?

    I have to write a program that asks for the speed of a vehicle (in miles-per-hour) and the number of hours it has traveled. It should use a loop to display the distance a vehicle has traveled for each hour of a time period specified by the user. Such as 1 hour will equal 40 miles traveled, 2 hours will equal 80, 3 hours will equal 120, etc. This is what I've come up with thus far. Any help is appreciated.
    import java.util.Scanner;
         public class DistanceTraveled
              public static void main(String[] args)
                   int speed;
                   int hours;
                   int distance;
                   Scanner keyboard = new Scanner(System.in);
                   System.out.print("What is the speed of the vehicle in miles-per-hour?");
                   speed = keyboard.nextInt();
                   System.out.print("How many hours has the vehicle traveled for?");
                   hours = keyboard.nextInt();
                   distance = speed*hours;
                   while (speed < 0)
                   while (hours < 1)
                   System.out.println("Hour     Distance Traveled");
                   System.out.println("------------------------");
                   System.out.println(hours + " " + distance);
    }

    When you post code, wrap it in code tags. Highlight it and click the CODE button above the text input area.
    You seem to be trying to reuse the speed and hours variables in your loop. That's probably a mistake at this point. Keep it simpler by defining a loop variable.
    Also I don't see the need for two loops. You just want to show how far the vehicle has traveled for each one-hour increment, assuming constant speed, for the number of hours it has been traveling, right? So a single for loop should be sufficient.

  • How do you use the JSObject class?

    Hello everyone,
    So, I am trying to make a java applet call a java script function and I am having some problems.... I began by looking at the JSObject class.... Does the JSObject class come standard with an installation of java? or do I have to find it separately? Also, does it make a difference as to what operating system I'm compiling my applet one? I have been developing in mac, and I cant get my applet to compile, it claims that the netscape.javascript package can't be found..... Any suggestions on this? I'm kinda new to Java web development, as I have only been doing it for a month or so, so please keep any answers simple. Also, any other suggestions by which an applet can call a javascript function are greatly appreciated. Thanks beforehand.

    >
    So, I am trying to make a java applet call a java script function and I am having some problems.... I began by looking at the JSObject class.... Does the JSObject class come standard with an installation of java? or do I have to find it separately? >It is included in the JRE, but 'well hidden'.
    >
    Also, does it make a difference as to what operating system I'm compiling my applet one? >Quite possibly. The Win version puts the main classes into rt.jar, but the netscape classes are in plugin.jar. These are both in the general path ${java.home}/lib/.
    >
    ..I have been developing in mac, and I cant get my applet to compile, it claims that the netscape.javascript package can't be found..... Any suggestions on this? >Add the classes (once you locate them), onto the compile time classpath. I could give you links to documentation on how to do that for either *nix or Windows, but I am not sure how Mac does it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to use the Rectangle class to draw an image and center it in a JPanel

    I sent an earlier post on how to center an image in a JPanel using the Rectangle class. I was asked to send an executable code which will show the malfunction. The code below is an executable code and a small part of a very big project. To simplifiy things, it is just a JFrame and a JPanel with an open dialog. Once executed the JFrame and the FileDialog will open. You can then navigate to a .gif or a .jpg picture and open it. What I want is for the picture to be centered in the middle of the JPanel and not the upper left corner. It is also important to stress that, I am usinig the Rectangle class to draw the Image. The region of interest is where the rectangle is created. In the constructor of the CenterRect class, I initialize the Rectangle class. Then I use paintComponent in the CenterRect class to draw the Image. The other classes are just support classes. The MyImage class is an extended image class which also has a draw() method. Any assistance in getting the Rectangle to show at the center of the JPanel without affecting the size and shape of the image will be greatly appreciated.
    I have divided the code into three parts. They are all supposed to be on one file in order to execute.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class CenterRect extends JPanel {
        public static Rectangle srcRect;
        Insets insets = null;
        Image image;
        MyImage imp;
        private double magnification;
        private int dstWidth, dstHeight;
        public CenterRect(MyImage imp){
            insets = getInsets();
            this.imp = imp;
            int width = imp.getWidth();
            int height = imp.getHeight();
            ImagePanel.init();
            srcRect = new Rectangle(0,0, width, height);
            srcRect.setLocation(0,0);
            setDrawingSize(width, height);
            magnification = 1.0;
        public void setDrawingSize(int width, int height) {
            dstWidth = width;
            dstHeight = height;
            setSize(dstWidth, dstHeight);
        public void paintComponent(Graphics g) {
            Image img = imp.getImage();
         try {
                if (img!=null)
                    g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
              srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);
            catch(OutOfMemoryError e) {e.printStackTrace();}
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Opener().openImage();
    class Opener{
        private String dir;
        private String name;
        private static String defaultDirectory;
        JFrame parent;
        public Opener() {
            initComponents();
         public void initComponents(){
            parent = new JFrame();
            parent.setContentPane(ImagePanel.panel);
            parent.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            parent.setExtendedState(JFrame.MAXIMIZED_BOTH);
            parent.setVisible(true);
        public void openDialog(String title, String path){
            if (path==null || path.equals("")) {
                FileDialog fd = new FileDialog(parent, title);
                defaultDirectory = "dir.image";
                if (defaultDirectory!=null)
                    fd.setDirectory(defaultDirectory);
                fd.setVisible(true);
                name = fd.getFile();
                if (name!=null) {
                    dir = fd.getDirectory();
                    defaultDirectory = dir;
                fd.dispose();
                if (parent==null)
                    return;
            } else {
                int i = path.lastIndexOf('/');
                if (i==-1)
                    i = path.lastIndexOf('\\');
                if (i>0) {
                    dir = path.substring(0, i+1);
                    name = path.substring(i+1);
                } else {
                    dir = "";
                    name = path;
        public MyImage openImage(String directory, String name) {
            MyImage imp = openJpegOrGif(dir, name);
            return imp;
        public void openImage() {
            openDialog("Open...", "");
            String directory = dir;
            String name = this.name;
            if (name==null)
                return;
            MyImage imp = openImage(directory, name);
            if (imp!=null) imp.show();
        MyImage openJpegOrGif(String dir, String name) {
                MyImage imp = null;
                Image img = Toolkit.getDefaultToolkit().getImage(dir+name);
                if (img!=null) {
                    imp = new MyImage(name, img);
                    FileInfo fi = new FileInfo();
                    fi.fileFormat = fi.GIF_OR_JPG;
                    fi.fileName = name;
                    fi.directory = dir;
                    imp.setFileInfo(fi);
                return imp;
    }

    This is the second part. It is a continuation of the first part. They are all supposed to be on one file.
    class MyImage implements ImageObserver{
        private int imageUpdateY, imageUpdateW,width,height;
        private boolean imageLoaded;
        private static int currentID = -1;
        private int ID;
        private static Component comp;
        protected ImageProcessor ip;
        private String title;
        protected Image img;
        private static int xbase = -1;
        private static int ybase,xloc,yloc;
        private static int count = 0;
        private static final int XINC = 8;
        private static final int YINC = 12;
        private int originalScale = 1;
        private FileInfo fileInfo;
        ImagePanel win;
        /** Constructs an ImagePlus from an AWT Image. The first argument
         * will be used as the title of the window that displays the image. */
        public MyImage(String title, Image img) {
            this.title = title;
             ID = --currentID;
            if (img!=null)
                setImage(img);
        public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
             imageUpdateY = y;
             imageUpdateW = w;
             imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
         return !imageLoaded;
        public int getWidth() {
             return width;
        public int getHeight() {
             return height;
        /** Replaces the ImageProcessor, if any, with the one specified.
         * Set 'title' to null to leave the image title unchanged. */
        public void setProcessor(String title, ImageProcessor ip) {
            if (title!=null) this.title = title;
            this.ip = ip;
            img = ip.createImage();
            boolean newSize = width!=ip.getWidth() || height!=ip.getHeight();
         width = ip.getWidth();
         height = ip.getHeight();
         if (win!=null && newSize) {
                win = new ImagePanel(this);
        public void draw(){
            CenterRect ic = null;
            win = new ImagePanel(this);
            if (win!=null){
                win.addIC(this);
                win.getCanvas().repaint();
                ic = win .getCanvas();
                win.panel.add(ic);
                int width = win.imp.getWidth();
                int height = win.imp.getHeight();
                Point ijLoc = new Point(10,32);
                if (xbase==-1) {
                    xbase = 5;
                    ybase = ijLoc.y;
                    xloc = xbase;
                    yloc = ybase;
                if ((xloc+width)>ijLoc.x && yloc<(ybase+20))
                    yloc = ybase+20;
                    int x = xloc;
                    int y = yloc;
                    xloc += XINC;
                    yloc += YINC;
                    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                    count++;
                    if (count%6==0) {
                        xloc = xbase;
                        yloc = ybase;
                    int scale = 1;
                    while (xbase+XINC*4+width/scale>screen.width || ybase+YINC*4+height/scale>screen.height)
                        if (scale>1) {
                   originalScale = scale;
                   ic.setDrawingSize(width/scale, height/scale);
        /** Returns the current AWT image. */
        public Image getImage() {
            if (img==null && ip!=null)
                img = ip.createImage();
            return img;
        /** Replaces the AWT image, if any, with the one specified. */
        public void setImage(Image img) {
            waitForImage(img);
            this.img = img;
            JPanel panel = ImagePanel.panel;
            width = img.getWidth(panel);
            height = img.getHeight(panel);
            ip = null;
        /** Opens a window to display this image and clears the status bar. */
        public void show() {
            show("");
        /** Opens a window to display this image and displays
         * 'statusMessage' in the status bar. */
        public void show(String statusMessage) {
            if (img==null && ip!=null){
                img = ip.createImage();
            if ((img!=null) && (width>=0) && (height>=0)) {
                win = new ImagePanel(this);
                draw();
        private void waitForImage(Image img) {
        if (comp==null) {
            comp = ImagePanel.panel;
            if (comp==null)
                comp = new JPanel();
        imageLoaded = false;
        if (!comp.prepareImage(img, this)) {
            double progress;
            while (!imageLoaded) {
                if (imageUpdateW>1) {
                    progress = (double)imageUpdateY/imageUpdateW;
                    if (!(progress<1.0)) {
                        progress = 1.0 - (progress-1.0);
                        if (progress<0.0) progress = 0.9;
    public void setFileInfo(FileInfo fi) {
        fi.pixels = null;
        fileInfo = fi;
    }

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • How to use the implementation class in propetty pallete

    Hi,
    I am using forms 10g....I have to insert horizontal scroll bar in text item..
    I have only class files instead of jar files ...how cani place the class file instead of jar file...
    How to use the implementation class in property palette to display the PJC
    Thanks,
    Ansaf.

    The Implementation Class must reflect the full name of the class. For instance, if the full class name is : xx.yyy.zz.class_name, then put this in the Implementation Class property of the corresponding item.
    Also, the class must be stored in the equivalent directory structure, so that, in my example: <DEV_HOME>/forms/java/xx/yyy/zz
    Francois

  • How can I use the Epson scanner Perfection V600 Photo in Photoshop cs5.1

    How can I use the Epson scanner Perfection V600 Photo in Photoshop cs5.1
    I am not able to see the scanner in photoshop. 

    Are you using a mac or windows? And what version?

  • Where we use the window class in the sql and how to use it

    where we use the window class in the sql and how to use it

    http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm#SQLRF06174
    Regards
    Etbin

  • How to use the message class CL_BSP_MESSAGES in the event handler?

    Hiii,
    I need to use the message class CL_BSP_MESSAGES in the even handler, because I need to use the Condition co_cancel_event_prefix to prevent saving in the method
    global_messages->add_message(
                                            condition = co_cancel_event_prefix
                                            message   = TEXT-010
                                            severity  = cl_bsp_messages=>co_severity_error ).
                                            dummy     = ME->COMPONENT_ID ).
    Can anybody explain me how to use this method?
    Kind Regards,
    John

    solved

  • HT204266 how do i get an app to be recognized under the camera setting to be able to use the scanner?

    I have an app called goodreads and an in order to use the scanner it says I need to let the camera have access. to do so it is saying to go to settings, privacy camera and allow access to the app well I do that but under the camera it doesn't have that app listed and I don't know how to get it so it is there? I have tried deleting the application and reloading it and still nothing. any advice?

    TThat means you're allowing access to your camera roll when you access the app - like Instagram.
    doesnt mean when you open the camera roll - good read will be an option like Facebook, Flickr, twitter...
    refer to the good read support pade

  • I want to use the scanner... how do I get this ap?cc=us

    I am trying to use the scanner feature and cannot figure out the process. Thanks for your help.

    lamourtoujours wrote:
    It used to do it with the mailto: extension which doesn't work anymore.
    It can be done because it was done.
    You could have made your question here much easier to understand. You mentioned none of this in your first two posts.
    There's a fairly recent version of that extension for Safari, here: https://code.google.com/p/mailto-chromeextension/downloads/list
    If that doesn't work, maybe you should try using the Chrome version.
    Good luck.

  • C7280 how to downlaod info to be able to use the scanner.

    Very new to this and am now in need to use the scanner on this printer. do not have the disc anymore to download. please help as need to use the scanner for this printer.

    Hi Linsky68, welcome to the forums!
    Here is the download page for the different operating systems for you printer:  http://h10025.www1.hp.com/ewfrf/wc/softwareCategor​y?cc=us&lc=en&product=3204785
    This is the printers main support page: http://h10025.www1.hp.com/ewfrf/wc/product?cc=us&d​lc=en&lc=en&product=3204785
    And here is the link to all the different scanning methods: http://h10025.www1.hp.com/ewfrf/wc/documentSubCate​gory?tmp_rule=35674&tmp_task=useCategory&cc=us&dlc​...
    Please feel free to repost if you have any other questions
    *** If my reply was helpful, please click on the "Kudos Thumbs-Up" on the right, as a way to say "Thanks!".
    If this reply also fixed your issue - please click the "Accept as Solution" button, so that others can find the same answer. ***

  • How can I use the button in one panel to control the other panel's appearing and disappearing?

    How can I use the button in one panel to control the other panel's
    appearing and disappearing? What I want is when I push the button on
    one button . another panel appears to display something and when I
    push it again, that the second panel disappears.

    > How can I use the button in one panel to control the other panel's
    > appearing and disappearing? What I want is when I push the button on
    > one button . another panel appears to display something and when I
    > push it again, that the second panel disappears.
    >
    You want to use a combination of three features, a button on the panel,
    code to notice value changes using either polling in a state machine of
    some sort or an event structure, and a VI Server property node to set
    the Visible property of the VI being opened and closed.
    The button exists on the controlling panel. The code to notice value
    changes is probably on the controlling panel's diagram, and this diagram
    sets the Visible property node of a VI class property node to FALSE or
    TRUE to show or
    hide the panel. To get the VI reference to wire to the
    property node, you probably want to use the Open VI Reference node with
    the VI name.
    Greg McKaskle

Maybe you are looking for