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));
}
Related
package stringvars;
import java.util.Scanner;
public class ConcertID {
public static void main(String[] args) {
try (Scanner userInput = new Scanner (System.in)) {
String yourName;
System.out.print ("enter the last letter of your second name: ");
yourName = userInput.next();
String yourDOB;
System.out.print ("enter your Year Of Birth: ");
yourDOB = userInput.next();
String ConcertID;
ConcertID = yourName + " " + yourDOB;
System.out.println("your concert ID is " + ConcertID);
}
}
}
I'm trying to get the code to take the user input, add a number between 1 and 10 at the end and print it as Y18867. Currently it prints as Y 1886.
(And I've yet to figure out the math.random part.)
Let me recommend you start using the StringBuilder class to create concatenated strings. It has a better performance regarding time consuming to concatenate strings.
The following code generates the random number as well as the concertId string that you are trying to get.
public class ConcertID
{
public static void main(String[] args)
{
try (Scanner userInput = new Scanner(System.in))
{
String yourName;
System.out.print("Enter the last letter of your second name: ");
yourName = userInput.nextLine();
String yearOfBirth;
System.out.print("Enter your Year of Birth: ");
yearOfBirth = userInput.nextLine();
StringBuilder concertId = new StringBuilder();
concertId.append(yourName);
concertId.append(yearOfBirth);
concertId.append(generateNumber());
System.out.println(concertId.toString());
}
}
public static int generateNumber()
{
int number = 0;
Random random = new Random();
number = random.nextInt(1, 10);
return number;
}
}
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);
}
}
Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.
Well for instance, the program will ask the user for input, then it will produce some output then it's done, but how can I make it loop again if the user wants to through the main method?
Here's my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
printSomeInfoAbout(hisName);
}
How will I make it run again if the user decides to again?
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
printSomeInfoAbout(hisName);
System.out.print("AGAIN (Y/N) : "); // ask the input from user
String var= sc.next();
if(var.equalsIgnoreCase("Y")){// Matches "Y" or "y"
main(null); // if input is Y then call main again.
}
}
String x=null;
Scanner sc = new Scanner(System. in );
String hisName=null;
do{
System.out.print("Please enter the first name of the person you would love to know about : ");
hisName = sc.next();
printSomeInfoAbout(hisName);
System.out.print("y/n");
x=sc.next();
}while(x.equals("y"));
boolean exit = false;
while(!exit){
Scanner sc = new Scanner(System. in );
System.out.print("Please enter 'exit' to exit or, the first name of the person you would love to know about : ");
String hisName = sc.next();
if(!"exit".equals(hisName)) {
printSomeInfoAbout(hisName);
}else{
exit = true;
}
}
create a method for getting the input and call on it if the user chooses to input another name
A simple loop that will check whatever the user put an empty string as the first name it will exit.
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
do {
System.out.print("Please enter the first name of the person you would love to know about : ");
String hisName = sc.next();
if (hisName.equals("")) {
printSomeInfoAbout(hisName);
}
} while (!hisName.equals(""));
}
Please find below code segment, It might help you..
public static void main(String[] args) {
String name;
Scanner scn = new Scanner(System.in);
boolean flag = false;
do {
System.out.println("Please enter the first name of the person you would love to know about : ");
name = scn.next();
System.out.println("Your friend " +name+ " is a great guy..!");
System.out.println();
System.out.println("Enter 1 to continue giving other" +
" names or Enter 2. to quit");
System.out.println();
int choice = scn.nextInt();
if( choice == 1 ) {
flag = true;
} else {
System.out.println("ThankU.. Bye");
flag = false;
}
} while(flag);
}
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();
}
}
}