2

i am a newbie in java and I have written this program to display a flight details

 import java.io.*;
 import java.util.Scanner;
 class Main
{
public static void main(String args[])
{
    int ticket;
    String name,destination;
    float fare;
    char tclass;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter Flight name : ");
    name=in.nextLine();
    System.out.println("Enter Ticket No : ");
    ticket=in.nextInt();
    System.out.println("Enter Flight Fare : ");
    fare=in.nextFloat();
    System.out.println("Enter Travelling Class : ");
    tclass=in.next().charAt(0);
    System.out.println("Enter Source : ");
     String source=in.nextLine();
    System.out.println("Enter Destination : ");
    destination=in.nextLine();
    System.out.println("Flight Details : ");
    System.out.println("Flight Name : "+name);
    System.out.println("Ticket No : "+ticket);
    System.out.println("Flight Fare : "+fare);
    System.out.println("Class : "+tclass);
    System.out.println("Source : "+source);
    System.out.println("Destination : "+destination);
}

}

but i am getting an error while printing output. The source field is empty and the destination field has the data of source

Flight Details : 
Flight Name : Emirates
Ticket No : 43190215
Flight Fare : 19433.94
Class : C
Source : 
Destination : Mumbai

Here mumbai is actually the value for source but its getting displayed in destination field

user-6589801
  • 119
  • 1
  • 14

1 Answers1

2

Use this piece of code in your programm,

    System.out.println("Enter Travelling Class : ");
    tclass = in.next().charAt(0);
    in.nextLine();
    System.out.println("Enter Source : ");
    String source = in.nextLine();

Actually the next() method is not consuming the last newline character, that's why you are facing this problem.

Rishal dev singh
  • 932
  • 8
  • 15