I want to create id (int), title (String), category (String) and cost (Float) for a class in Java. I used an Scanner object to read them from keyboard. But I can only read the id, after that the console do not allow me to read the title, it goes to category and then cost. Even if I type a float to cost, it throws an exception. Please help me.
package ChuoiTrongJava;
import java.util.Scanner;
public class IndexOf {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("ID: ");
int id = kb.nextInt();
System.out.print("\nTitle: ");
String title = kb.nextLine();
System.out.print("\nCategory: ");
String category = kb.nextLine();
System.out.print("\nCost: ");
Float cost = kb.nextFloat();
}
}
Related
I am trying to write a terminal-based toy app, which allows user to input product category and inventory.
Is it possible to implement a feature of pressing enter key to input the default inventory.
Here is the procedure/steps
app print "product category:"
user input a category, such as shoe
app print "Inventory(press enter key for 999):"
user press enterkey or input another number
app print product_category + product_inventory
here is my code
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
System.out.print("Inventory(press enter key for 999): ");
int product_inventory = scanner.nextInt();
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
this code does not support "enterkey for default" feature.
quesion
is it possible detect single enterkey with java.util.Scanner to implement the default input?
I also tried this code, even worse
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
scanner.close();
System.out.print("Inventory(press enter key for 999): ");
scanner = new Scanner(System.in);
String product_inventory_str = "999";
if(scanner.hasNext()){
System.out.println("hasNext");
product_inventory_str = scanner.nextLine();
}
else{
System.out.println("does not have Next");
}
int product_inventory = 999;
if(product_inventory_str.isEmpty()){
System.out.println("isEmpty");
}
else{
product_inventory = Integer.parseInt(product_inventory_str);
}
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
You could always read an entire line (because user will have to press Enter anyway) and then decide what to do with it, something like this:
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.nextLine();
System.out.print("Inventory(press enter key for 999): ");
String pi_string = scanner.nextLine();
int product_inventory = pi_string.isEmpty()?
999:Integer.parseInt(pi_string);
scanner.close();
System.out.println(String.format("%s, %d",
product_category, product_inventory));
}
I can get and print the integer value in java but I am confuse how to get and print string. Can someone help
package hello;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int integer;
System.out.println("Please Enter Integer");
Scanner sc = new Scanner(System.in);
integer = sc.nextInt();
sc.close();
System.out.println("you entered : " +integer);
}
}
Program output
Please Enter Integer
5
you entered : 5
I am stuck in this program. I don't understand how to get string and print on screen
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextInt();
sc.close();
System.out.println("Your name"+name);
}
}
You need to change your type value name from int to String. And replace sc.nextInt() by sc.nextLine() or sc.next().
Example
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name " + name);
}
Use sc.nextLine() for reading string inputs
or
sc.next() (But this will read only a word before it encounters a space)
You can also use InputStreamReader for this purpose
eg.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in()));
String input = br.readLine();
name = sc.nextInt(); doesn't work for strings, only for integers, you should use sc.nextline instead.
And also you have to change int name to String name, due to other type of variable.
Your code should look like this:
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}
change int name to string name and use sc.nextLine()
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}
import java.util.*;
public class MovieInfo
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the film");
String name = in.nextLine();
System.out.println("Enter the film budget");
int bud = in.nextInt();
System.out.println("Enter the running time");
double time = in.nextDouble();
System.out.println("Enter the film production house");
String s1 = in.nextLine();
System.out.println("Film being screened : "+name);
System.out.println("Budget "+bud+" cores");
System.out.println("Running time "+time+" hours");
System.out.println("Production : "+s1);
}
}
In the output of the above program, it does not take input for String s1.
How do I fix it?
Any help would be appreciated.
Try to put the following additional line:
in.nextLine();
after that line:
double time = in.nextDouble();
to consume new line character (it's created when you accept input double with Enter key) that is not being consumed with .nextDouble() call.
Please refer to link to that question, provided by LenosV, to get detailed information on what's the reason of that behavior of Scanner.
This will work
import java.util.*;
public class MovieInfo
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the film");
String name = in.nextLine();
System.out.println("Enter the film budget");
int bud = in.nextInt();
System.out.println("Enter the running time");
double time = in.nextDouble();
System.out.println("Enter the film production house");
String s1 = in.next();
System.out.println("Film being screened : "+name);
System.out.println("Budget "+bud+" cores");
System.out.println("Running time "+time+" hours");
System.out.println("Production : "+s1);
}
}
I want to be able to get input from the scanner class within one instance method and than pass it to another instance method where I will display it.
Here is an example of my problem
import java.io.*;
import java.util.*;
class TestScanner
{
public static void main (String args[])
{
TestScanner disInput = new TestScanner();
TestScanner gInput = new TestScanner();
gInput.grabInput();
disInput.displayInput();
}
void displayInput()
{
System.out.println("Scanner Input here: ");
System.out.println("What is my age: ");
// How do I get age here
System.out.println("What is 2 +2: ");
// How do I get math here
}
void grabInput()
{
int age, math;
Scanner stdin = new Scanner(System.in);
System.out.println("What is my age: ");
age = stdin.nextInt();
System.out.println("What is 2 +2: ");
math = stdin.nextInt();
}
}
You only need one scanner to get input, and you need to close the scanner when you are done:
int grabInput(String question)
{
// Display a question to user
System.out.println(question);
// Read a response from user
Scanner stdin = new Scanner(System.in);
int input = stdin.nextInt();
stdin.close();
// Return the response
return input;
}
You don't need any scanners at all to show output:
int displayOutput(String message, int response)
{
System.out.println(message);
System.out.println(response);
}
Here is what your main looks like with these changes:
public static void main (String args[])
{
String ageQuestion = "What is my age?";
int ageAnswer = grabInput(ageQuestion);
String mathQuestion = "What is 2 + 2?";
int mathAnswer = grabInput(mathQuestion);
displayOutput(ageQuestion, ageAnswer);
displayOutput(mathQuestion, mathAnswer);
}
The trick is to return the responses to main because you need access to them in another function, and to bury the Scanner logic in one function so that you don't have to worry about it anywhere else.
The BAD and AVOID WHILE LEARNING solution: Move age and math local variables as static fields in the class.
The class will look like this:
public class TestScanner {
static int age;
static int math;
//rest of your class...
//in method grabInput
static void grabInput() {
//comment the variables
//int age, math;
}
}
The code above will work due to the usage of static fields. First understand what static means and be careful when using it.
You should ask yourself the following questions:
Should I have a method to display the fields of TestScanner inside the same class?
Should I create a new instance of TestScanner just to display the values of another instance of TestScanner?
In case you answer yes to both questions, then you can create a method that receives an instance of TestScanner and prints its contents. This is how your class will look like:
public class TestScanner {
//Note: they're not static anymore (yay!)
int age;
int math;
public static void main (String args[]) {
TestScanner disInput = new TestScanner();
TestScanner gInput = new TestScanner();
gInput.grabInput();
//note that now we need to pass the instance of TestScanner
//in order to print its contents
disInput.displayInput(gInput);
}
//method for display purposes
void displayInput(TestScanner testScanner) {
System.out.println("Scanner Input here: ");
System.out.println("What is my age: ");
System.out.println(testScanner.age);
System.out.println("What is 2 +2: ");
System.out.println(testScanner.math);
}
void grabInput() {
Scanner stdin = new Scanner(System.in);
System.out.println("What is my age: ");
this.age = stdin.nextInt();
System.out.println("What is 2 +2: ");
this.math = stdin.nextInt();
}
}
Now ask yourself: do I need all this? Is this a good design? Can I perform changes easily or will it take more time and effort to, for example, add a new variable, fill it and display it?
The main problem here is called cohesion. This is, the degree of functionalities within a class. As you can see, TestScanner itself has many responsibilities:
Store age and math
Read it from user input
Display the data to the user
A better approach will be to separate these functionalities in two classes:
Person (or another name) that will store the data from user input. Based on the names of age and math fields, I thought a proper name of the class could be Person. This class will be in charge to store the data and provide it for different usage e.g. store user input and then use it for display purposes.
A TestScanner class where you will test the usage of Scanner to read the data from user input and display data to user.
The design will look like this:
class Person {
private int age;
private int math;
public Person(int age, int math) {
this.age = age;
this.math = math;
}
public int getAge() {
return this.age;
}
public int getMath() {
return this.math;
}
//setters avoided for this case
}
class TestScanner {
Scanner scanner;
public TestScanner(Scanner scanner) {
this.scanner = scanner;
}
public Person grabInput() {
System.out.println("What is my age: ");
int age = stdin.nextInt();
System.out.println("What is 2 +2: ");
int math = stdin.nextInt();
return new Person(age, math);
}
public void displayInput(Person person) {
System.out.print("My age: ");
System.out.println(person.getAge());
System.out.print("My value of 2 +2: ");
System.out.println(person.getMath());
}
public static void main(String[] args) {
TestScanner testScanner = new TestScanner(new Scanner(System.in));
Person person = testScanner.grabInput();
testScanner.displayInput(person);
}
}
Note: Links provided in questions are not for decoration purposes.
You can make a static variable in your TestScanner class, and every instance of your class will have access to that variable. Note that the variable will have the same value for each instance of your class.
import java.io.*;
import java.util.*;
class TestScanner
{
public static Integer age;
public static Integer math;
public static void main (String args[])
{
TestScanner disInput = new TestScanner();
TestScanner gInput = new TestScanner();
gInput.grabInput();
disInput.displayInput();
}
void displayInput()
{
System.out.println("Scanner Input here: ");
System.out.println("What is my age: ");
// How do I get age here
System.out.pritln(age);
System.out.println("What is 2 +2: ");
// How do I get math here
System.out.pritln(math);
}
void grabInput()
{
Scanner stdin = new Scanner(System.in);
System.out.println("What is my age: ");
age = stdin.nextInt();
System.out.println("What is 2 +2: ");
math = stdin.nextInt();
}
}
You can take a look at what static variables are in java here.
I am having some trouble with the placing of brackets. I wanted to write a few methods within the confines of my main method, but I always end up with with a bunch of red lines and errors telling me "Multiple markers at this line
- Syntax error on token "void", # expected
- addVehicleBooking cannot be resolved to a type"
I don't want my methods to return anything, I just want them to execute some code and print some stuff on the screen.
EDIT:
This is the start of the code, no need to worry about unused variables and such. Thanks for everyone's help =].
import java.util.Scanner;
public class FerryMenu {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
public static void addVehicleBooking()
{
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
}
String menu_choice = "";
while(!"X".equals(menu_choice)){
System.out.println("*** Ferry Ticketing System Menu ***");
System.out.println("A - Add Vehicle Booking");
System.out.println("B - Display Booking Info");
System.out.println("C - Update Insurance Status");
System.out.println("D - Display Booking Summary");
System.out.println("X - Exit");
System.out.print("Enter your selection: ");
menu_choice = input.next();
}
}
}
You can't declare methods inside a method.. It's not about brackets.. It's about syntax.
Ok, Dean, here I'll describe it once again..
First thing, throw away the code that you have written.. Lets start fresh..
Follow these steps to approach your problem: -
Create a class say Demo
Add a method to that class, getUserInput()
Add main method also to your class.
Have a constructor (0-arg)
Now, your program starts executing from main().. If you want to take user input.. Call your getUserInput() method from here.. As the first statement..
In your getUserInputMethod(), after reading all the input, invoke your constructor to initialize your instance variables..
After this, your getUserInput() will return control to your main() method.. You can proceed with your code from there..
You can not define a method inside a method. Declare it outside the method and inside the class.
public class FerryMenu {
public static void addVehicleBooking()
{
//...
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
// just call the method here
addVehicleBooking();
//...
}
}
you are writing your addvehicalBooking method inside your main method.
thus those red line :remove that method from main.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
}
public static void addVehicleBooking()
{
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
}
Try taking out addVehicleBooking() outside main and call it and declare the variables in a constructor
You have a static method inside your main static method which is probably causing the problems. Have you tried moving the addVehicleBooking() method to the space between public class FerryMenu and the main method? (the addVehicleBooking() method should be a member of the class FerryMenu, not the main method)
Why are you making a static method inside public static void main. I dont think that there is a need to make it.
Remove the word static from "static void addVehicleBooking".
I'll edit this answer and add the corrected code asap.
you can not define method in method.
you can define it in class like this:
import java.util.Scanner;
public class FerryMenu {
static Scanner input = new Scanner(System.in);
static Scanner scan = new Scanner(System.in);
public static void addVehicleBooking()
{
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
}
public static void main(String[] args)
{
String menu_choice = "";
while(!"X".equals(menu_choice)){
System.out.println("*** Ferry Ticketing System Menu ***");
System.out.println("A - Add Vehicle Booking");
System.out.println("B - Display Booking Info");
System.out.println("C - Update Insurance Status");
System.out.println("D - Display Booking Summary");
System.out.println("X - Exit");
System.out.print("Enter your selection: ");
menu_choice = input.next();
}
}
}
and fields "input" and "scan" must be defined as static because you are invoking them as static
The addVehicleBooking should be placed outside main. BTW: I hope that you're using somewhere the variables used for user's input because in the code posted are unused.
The refactored code should look like:
import java.util.Scanner;
public class FerryMenu {
public static void main(String[] args) {
addVehicleBooking();
}
public static void addVehicleBooking() {
String menu_choice = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
while (!"X".equals(menu_choice)) {
System.out.println("*** Ferry Ticketing System Menu ***");
System.out.println("A - Add Vehicle Booking");
System.out.println("B - Display Booking Info");
System.out.println("C - Update Insurance Status");
System.out.println("D - Display Booking Summary");
System.out.println("X - Exit");
System.out.print("Enter your selection: ");
menu_choice = input.next();
}
}
}