0

I am trying a simple menu based accept and display string code in java.Here if I want to accept and display just a single string per line of input I am able to do with next(),but for space separated string as input I am not able to accept and display as intended.

this is the code:

import java.util.Scanner;

class Trial
{
    String c,l;
    public static void main(String[] args)
    {
        Trial t=new Trial();
        int ch=0;
        Scanner sc=new Scanner(System.in);

        while(ch!=3)
        {
            System.out.println("1.acc");
            System.out.println("2.dis");
            System.out.println("3.exit");
            System.out.println("enter ch");
            ch=Integer.parseInt(sc.next());

            switch(ch)
            {
                case 1:
                    System.out.println("enter C");   
                    t.c=sc.nextLine();  

                    System.out.println("enter L");    
                    t.l=sc.nextLine();      
                    sc.nextLine();

                    break;
                case 2:
                    System.out.println("c = "+t.c); 
                    System.out.println("l = "+t.l);
                    break;
            }
        }
    }

}

this is the output that i am getting:

------------------------output------------

1.acc

2.dis

3.exit

enter ch

1

enter C

enter L

www eee

rrr ttt

1.acc

2.dis

3.exit

enter ch

2

c =

l = www eee

------------------output ends---------

whereas I want the output to be

c = www eee" and l = "rrr ttt.

thanks

A Sdi
  • 657
  • 2
  • 9
  • 23
Ranjit
  • 1
  • `nextline()` will read until the `\n`. Maybe you should try changing the [Scanner delimiters](http://stackoverflow.com/questions/28766377/how-do-i-use-a-delimiter-in-java-scanner) – Chauã Queirolo Dec 05 '16 at 12:00

1 Answers1

1

put sc.nextLine() after ch=Integer.parseInt(sc.next());

See this: How do you keep scanner.next() from including newline?

Community
  • 1
  • 1
Azodious
  • 13,385
  • 1
  • 32
  • 68