How do I loop my main method in a way? - java

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);
}

Related

if and else statements JAVA

I'm practicing if and else statements and i did a guess your password string, if you input the right password a congratulation message appears but if you enter the wrong one another message appears that says "Please try again" the issue that im having is that i dont know how to set another congratulation message if the user guess the right password on try again.
public static void main(String[] args) {
String password = "Shippuden345";
System.out.println("Enter or guess the password: ");
Scanner scanner = new Scanner(System.in);
String guess = scanner.nextLine();
System.out.println(password.equals(guess));
if (password.equals(guess)) {
System.out.println("Your guess was correct");
return;
}
else;
{
System.out.println("Please try again: ");
Scanner scanner1 = new Scanner(System.in);
String again = scanner1.nextLine();
}
}
}
i want to set another message in here, if the user guess the password correctly after trying again.
else;
{
System.out.println("Please try again: ");
Scanner scanner1 = new Scanner(System.in);
String again = scanner1.nextLine();
}
}
}
It would be best if you used a do while loop:
public static void main(String[] args) {
String password = "Shippuden345";
String guess;
do{
System.out.println("Enter or guess the password: ");
guess = scanner.nextLine();
System.out.println(password.equals(guess));
if (password.equals(guess)) {
System.out.println("Your guess was correct");
return;
}
else {
System.out.println("Please try again: ");
}
}while(!password.equals(guess));
}
I have edited your code. However, I have added it to a static void:
I have also added an int to be shown if the first attempt was incorrect. Hope you like it.
class s{
public static void check(){
int attempts = 0;
String password = "Shippuden345";
System.out.println("Enter or guess the password: ");
Scanner scanner = new Scanner(System.in);
String guess = scanner.nextLine();
System.out.println(password.equals(guess));
while(attempts < 5){
if (password.equals(guess) && attempts == 0) {
System.out.println("Your guess was correct");
return;
}
else
if (password.equals(guess) && attempts > 0) {
System.out.println("Attempt number "+attempts+" was correct.");
return;
}
else{
System.out.println("Please try again: ");
attempts++;
guess = scanner.nextLine();
}
}
}
public static void main(String[] args) {
check();
}
}```
You can put the input and processing of the input value inside an infinite loop (e.g. while(true){}) which you can break on the correct input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String password = "Shippuden345";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter or guess the password: ");
String guess = scanner.nextLine();
if (password.equals(guess)) {
System.out.println("Your guess was correct");
break;
} else {
System.out.println("Please try again: ");
}
}
}
}
A sample run:
Enter or guess the password: aSD
Please try again:
Enter or guess the password: 12H
Please try again:
Enter or guess the password: Shippuden345
Your guess was correct
You can use a loop that starts after the first guess of passwords if the guess is incorrect and continues the loop if passwords entered in the following trials are incorrect.
Then breaks the loop when the password matches and prints the congratulate message.

Is it possible detect single enterkey with java.util.Scanner?

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));
}

How to get and print string in java

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);
}
}

How to validate string from user input to pre defined name [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
Hello all I am trying to write a loop in my code that would prompt user if they enter something other than what I have predefined. I am somewhat familiar with this done to user input that is not specific word or int but not sure when user has three choices to choose from.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
// this class will instantiates player object
public class Adventure {
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
List<String> names = Arrays.asList("mage","archer","warrior");
String userinput;
while (myinput.hasNext()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "
+ gameplayer.getClassName()+ ". What health do you have?");
}
}
int healthofPlayer ;
while (myinput.hasNextInt()){
healthofPlayer = myinput.nextInt();
if ((!myinput.hasNextInt())){
System.out.println("I'm sorry, what was that?");
}
else {
gameplayer.setHealth(healthofPlayer);
System.out.println("Very good. Now let's get started on your adventure.");
System.out.println("You awake alone, disoriented, and locked in the CS1331 TA Lab.");
}
return;
}
}
}
try out this, it should work out the rest.
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
List<String> names = Arrays.asList("mage","archer","warrior");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
String userinput;
while (myinput.hasNext() || myinput.hasNextInt()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "+ gameplayer.getClassName()+ ". What health do you have?");
int numberofHealth = myinput.nextInt();
}
System.out.println("Very good. Now let's get started on your adventure.");
gameplayer.setHealth(numberofHealth);
return;
}
}
There's no need loop for this. It'll be easier to delegate to a function as you'll see.
List<String> acceptable = Arrays.asList("mage", "archer", "warrior");
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
gameplayer.setclassName(promptFor(acceptable));
// having a function for this encapsulates the looping and the checking
// as well as the reprompting - it also means we can leave the loop
// with the right answer
String promptFor(Set<String> acceptable) {
while(true) { // while true sucks, but you've asked for an indefinite loop
String next = myinput.next().toLowerCase();
if (acceptable.contains(next)) {
return next;
}
// so it was a bad input
System.out.println("I'm sorry, what was that?");
} // loop some more
return null; // unreachable code
}

Java - Trouble with brackets

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();
}
}
}

Categories