On my previous question I've learned that I shouldn't close the System.in, and I also learned that using multiple Scanner together can cause problems.
The problem is that I need some methods recursively to use the Scanner to scan some inputs from the user.
Example
public void usersChoice(){
int choice = 0;
while(true){
try{
Scanner scan = new Scanner(System.in);
System.out.print("Choose an option: ");
choice = scan.nextInt();
break;
}
catch(Exception e){
System.out.println("Invalid Input!\n");
}
}
switch (choice){
case 1:
choiceNewAccount();
break;
case 2:
choiceLogin();
break;
case 3:
choiceRemoveAccount();
break;
case 4:
exit();
break;
default:
System.out.println("Invalid Input!\n");
break;
}
Case 1:
public void createAccount(){
try{
Scanner scan = new Scanner(System.in);
System.out.print("Enter Your Username: ");
String username = scan.next();
if(!isValidUsername(username)) System.out.println("Username Already Exists!");
else{
while(true){
System.out.print("Enter Your Password: ");
String pass1 = scan.next();
System.out.print("Re-Enter Your Passowrd: ");
String pass2 = scan.next();
if(!arePasswordsMatch(pass1,pass2)) System.out.println("Passowrds Don't Match!");
else {
addToAccountsList(username,pass1);
createTheUsersFile(username);
System.out.println("The Account Has Been Successfully Created!");
break;
}
}
}
} catch(Exception e){
System.out.println("Could Not Create Account!");
}
Do I need to create one System.in Object and use it on my whole program? Or is there an other way to work with the System.in Object?
Related
I need help with a if statement.
What I want to do is after the default, put an if statement that basically says
if name equals Mike or lady
then print out "Type a number between 1-3 to see your prize".
And if you type for example 1, it should print out you won a Bicycle.
I know that not that many Pro-programmers use switch but that's all I know for now :)
import java.util.Scanner;
public class Ifwasif {
public static void main (String [] args) {
System.out.println("Welcome to our Store!");
System.out.println("we hope you will find what you're looking for");
Scanner input = new Scanner (System.in);
System.out.print("To check out, please type your name: ");
String name = input.nextLine();
System.out.print("You need to confirm your age, please type your age: ");
int age = input.nextInt();
Scanner input1 = new Scanner (System.in);
System.out.print("You have an award to collect! To collect it type your name: ");
String namee = input1.nextLine();
switch (namee) {
case ("Mike"):
System.out.println("Congrats, you are the Winner!");
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
case ("lady"):
System.out.println("Congrats, you are the Winner!");
break;
default:
System.out.println("Your name is not in the list!");
}
}
}
Rather than an if statement after the switch, combine your 2 "winner" cases into a single case:
switch (namee) {
case ("Mike"):
case ("lady"):
System.out.println("Congrats, you are the Winner!");
// insert code here to prompt for input, read result, compare, and award
// or put that code into a new method
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
default:
System.out.println("Your name is not in the list!");
Should work fine:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Welcome to our Store!");
System.out.println("we hope you will find what you're looking for");
Scanner input = new Scanner(System.in);
System.out.print("To check out, please type your name: ");
String name = input.nextLine();
System.out.print("You need to confirm your age, please type your age: ");
int age = input.nextInt();// variable never used
input.nextLine();
System.out.print("You have an award to collect! To collect it type your name: ");
String namee = input.nextLine();
switch (namee) {
case ("Mike"):
case ("lady"):
System.out.println("Congrats, you are the Winner!");
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
default:
System.out.println("Your name is not in the list!");
break;
}
if("Mike".equals(name) || "lady".equals(name)){
System.out.println("Type a number between 1-3 to see your prize'");
int number = input.nextInt();
switch (number) {
case 1:
System.out.println("You won a Bicycle");
break;
default:
break;
}
}
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have a problem because I do not know how to save the variable. The variable newname and the newpassword deafult are zero. But in case 1 they are changed to the given values, but after case 1 the variables return to the basic values 0. and i cant log in (in case 2) becasue login and password always are 0. How i can globally set this variable on case 1?
String newname = null;
String newpassword = null;
System.out.println("Hello!");
System.out.println();
System.out.println(" ****************************************");
System.out.println(" * MENU *");
System.out.println(" ****************************************");
System.out.println(" 1. Create new account");
System.out.println(" 2. Log in");
System.out.println(" 3. Help");
System.out.println(" 0. End");
Scanner opcje = new Scanner(System.in);
int choose = opcje.nextInt();
switch (choose) {
case 1:
System.out.println("You choose create new acount\n Enter the login");
Scanner nlogin = new Scanner(System.in);
newname = nlogin.nextLine();
System.out.println("Please enter the password ");
Scanner npassword = new Scanner(System.in);
newpassword = npassword.nextLine();
System.out.println("the account has been created\n");
case 2:
Scanner login = new Scanner(System.in);
System.out.println("Login:");
String pass1 = login.nextLine();
System.out.println("Password:");
Scanner password = new Scanner(System.in);
String pass2 = password.nextLine();
if (pass1 == newname & pass2 == newpassword){
System.out.println("you are logged in");
}else{
System.out.println("incorrect passoword or login");
}
break;
case 3:
System.out.println("Help is off");
break;
case 0:
System.out.println("ending");
break;
default:
System.out.println("Select the option by pressing 1,2,3 or 0");
break;
}
}
}
One of the problems is with this line:
if (pass1 == newname & pass2 == newpassword){
System.out.println("you are logged in");
}else{
System.out.println("incorrect passoword or login");
}
If you will debug this code, You will notice that this if statement, doesn't
compare the values of the String. For more details you may visit:
https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
Try this code instead:
if(pass1.equals(newname) && pass2.equals(newpassword))
{
System.out.println("you are logged in");
}else{
System.out.println("incorrect passoword or login");
}
second problem:
you need to put your switch statement in a while loop:
1.This why the program won't end (and this way the variable) will be saved.
2.IF the user input is invalid instead of going to default, the program will also ask again for the user to write a number.
There are so many issues here.
You are missing a break; after the first case
You potentially have a scope issue for your variables if they are simply local variables in the method and you call the method repeatedly then their contents are simply forgotten in between calls.
You are comparing Strings using == , Read More here => Java String Equals
Correct Code:
public class MainClass {
String newname = null;
String newpassword = null;
//continue your code here
//call menu() when required
menu();
}
public void menu()
{
System.out.println("Hello!");
System.out.println();
System.out.println(" ****************************************");
System.out.println(" * MENU *");
System.out.println(" ****************************************");
System.out.println(" 1. Create new account");
System.out.println(" 2. Log in");
System.out.println(" 3. Help");
System.out.println(" 0. End");
Scanner opcje = new Scanner(System.in);
int choose = opcje.nextInt();
switch (choose)
{
case 1:
System.out.println("You choose create new acount\n Enter the login");
Scanner nlogin = new Scanner(System.in);
newname = nlogin.nextLine();
System.out.println("Please enter the password ");
Scanner npassword = new Scanner(System.in);
newpassword = npassword.nextLine();
System.out.println("the account has been created\n");
break;
case 2:
Scanner login = new Scanner(System.in);
System.out.println("Login:");
String pass1 = login.nextLine();
System.out.println("Password:");
Scanner password = new Scanner(System.in);
String pass2 = password.nextLine();
if (pass1.equals(newname) & pass2.equals(newpassword)){
System.out.println("you are logged in");
}else{
System.out.println("incorrect password or login");
}
break;
case 3:
System.out.println("Help is off");
break;
case 0:
System.out.println("ending");
break;
default:
System.out.println("Select the option by pressing 1,2,3 or 0");
break;
}
}
Try changing the way you compare Strings, also use java logical operators instead of Bitwise &.
static String newname = null;
static String newpassword = null;
public static void main(String[] args) {
System.out.println("Hello!");
System.out.println();
System.out.println(" ****************************************");
System.out.println(" * MENU *");
System.out.println(" ****************************************");
System.out.println(" 1. Create new account");
System.out.println(" 2. Log in");
System.out.println(" 3. Help");
System.out.println(" 0. End");
Scanner opcje = new Scanner(System.in);
int choose = opcje.nextInt();
switch (choose) {
case 1:
System.out.println("You choose create new acount\n Enter the login");
Scanner nlogin = new Scanner(System.in);
newname = nlogin.nextLine();
System.out.println("Please enter the password ");
Scanner npassword = new Scanner(System.in);
newpassword = npassword.nextLine();
System.out.println("the account has been created\n");
case 2:
Scanner login = new Scanner(System.in);
System.out.println("Login:");
String pass1 = login.nextLine();
System.out.println("Password:");
Scanner password = new Scanner(System.in);
String pass2 = password.nextLine();
//Java uses equals method to compare Strings
//Java also uses && as the logical operator for "and"
if (pass1.equals(newname) && pass2.equals(newpassword)) {
System.out.println("you are logged in");
} else {
System.out.println("incorrect password or login");
}
break;
case 3:
System.out.println("Help is off");
break;
case 0:
System.out.println("ending");
break;
default:
System.out.println("Select the option by pressing 1,2,3 or 0");
break;
}
}
I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}
public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
int Choice = 0;
do {
try {
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
Choice = Option.nextInt();
switch (Choice) { //used switch statement instead of If else because more effective
case 1:
CreateAccount();
break; //breaks iteration
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
System.out.println("Invalid Entry");
throw new Exception();
}
} catch (Exception e) {
System.err.println("Enter Correct Input");
return;
}
} while (true);
}
I am trying to make it when users enter incorrect input type like a letter , the exception is caught and then returns back to the menus, right now it catches the exception but it doesnt stop running I have to force stop the program. So I added a return but that just displays the exception error and stops, how can I make it return back to the menus?
That is because you're returning from the method itself in the catch block.
And Do not throw exceptions like that. Just use some boolean to know if the choice is valid and loop until the choice is entered correctly.Prefer not to use while(true), instead rely on a boolean flag everytime like below,
public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
int Choice = 0;
boolean isValidChoice = false;
do{
isValidChoice = false;
Choice = 0;
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
if(Option.hasNextInt()){
Choice= Option.nextInt();
isValidChoice = true;
}
switch (Choice)
{
case 1:
CreateAccount();
break;
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
isValidChoice = false; //if invalid choice, then set flag to loop
System.out.println("Invalid Entry");
}
} while (!isValidChoice);
}
Move the "try {" after the "System.out.println("Please choose");" line.
you just need to remove the return in the catch. also just as a tip, you can get rid of the do while and just have a while loop, because the loop is never ending.
} catch (Exception e) {
System.err.println("Enter Correct Input");
}
Okay so I'm pretty sure this should work:
Create a boolean value outside of while loop that is holds if there was a valid input
boolean validInput = true;
In default set this value to false (meaning there is an invalid input)
default:
System.out.println("Invalid Entry");
validInput = false;
throw new Exception();
Make sure the catch statement is still in the do loop because the throw clause will halt normal execution and transition into exception execution. Next the while tester will test if there was a valid input
while(!validInput)
Lastly go up to the top of the do loop and set validInput to true. This will make it so that each time you clear the previous incorrect input.
This should work.
I have been struggling with this for a while. I essentially want to loop through and read in as many strings as determined by num_choices. The following code only executes the else condition.
Scanner s2 = new Scanner(System.in);
for(int i=0; i < this.num_choices; i++)
{
if(s2.hasNext())
{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
}
else
{
System.out.println("Lets end this");
}
}
`
I am getting this: Exception in thread "main" java.util.NoSuchElementException. In the main class, this is where the error points to
choice2 = Integer.parseInt(read_choice2.next());
which is inside a while loop as well. Here is the code for that:
public class Main
{
public static void main(String args[]) throws IOException
{
Vector<Survey> mysurveys = new Vector<Survey>();
boolean carry_on = true;
int choice = 0;
Scanner read_choice = new Scanner(System.in);
System.out.println("Let's begin the Survey/Test application!");
while(carry_on)
{
System.out.println("What would you like to do?");
System.out.println("1. Create a new Survey");
System.out.println("2. Create a new Test");
System.out.println("3. Display a Survey");
System.out.println("4. Display a Test");
System.out.println("5. Save a Survey");
System.out.println("6. Save a Test");
System.out.println("7. Load a Survey");
System.out.println("8. Load a Test");
System.out.println("9. Quit");
System.out.println();
System.out.println("Please enter a number for the operation you want to perform: ");
choice = Integer.parseInt(read_choice.next());
/*try
{
choice = Integer.parseInt(buffer.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice.nextInt();
}*/
switch(choice)
{
case 1:
System.out.println("Please Enter a Name for your Survey");
String in = buffer.readLine();
Survey s1 = new Survey();
s1.CreateNew(in);
mysurveys.add(s1);
////
add_question(s1.type);
break;
case 2:
System.out.println("Please Enter a Name for your Test");
//String in = buffer.readLine();
Test t1 = new Test();
//t1.CreateNew(in);
mysurveys.add(t1);
break;
////
//add_question(t1.type);
case 3:
break;
// call Survey.display()
case 4:
break;
case 5:
Survey s = new Survey();
ReadWriteFiles x = new ReadWriteFiles();
x.SaveSurvey(s);
break;
case 6:
Test t = new Test();
//ReadWriteFiles x = new ReadWriteFiles();
//x.SaveSurvey(t);
break;
case 7:
carry_on = false;
break;
default:
System.out.println("Incorrect Input. Try Again");
System.out.println();
break;
}
}
read_choice.close();
}
public static void add_question(String type) throws IOException, NullPointerException
{
Questions q = null;
boolean carry_on2 = true;
int choice2 = 0;
Scanner read_choice2 = new Scanner(System.in);
//BufferedReader buffer2=new BufferedReader(new InputStreamReader(System.in));
while (carry_on2)
{
//
System.out.println("1. Add a new T/F Question");
System.out.println("2. Add a new Multiple Choice Question");
System.out.println("3. Add a new Short Answer Question");
System.out.println("4. Add a new Essay Question");
System.out.println("5. Add a new Ranking Question");
System.out.println("6. Add a new Matching Question");
System.out.println("7. If you want to stop adding more questions, and go back to the main menu.");
System.out.println("Please enter a number for the operation you want to perform: ");
choice2 = Integer.parseInt(read_choice2.next());
/*try
{
choice2 = Integer.parseInt(buffer2.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice2.nextInt();
}*/
switch(choice2)
{
case 1:
q = new TrueFalse();
break;
case 2:
q = new MultipleChoice();
break;
case 3:
q = new ShortAnswer();
break;
case 4:
q = new Essay();
break;
case 5:
q = new Ranking();
break;
case 6:
q = new Matching();
break;
case 7:
carry_on2 = false;
break;
default:
System.out.println("Incorrect Input.");
break;
}
q.createQuestion(type);
}
}
}
I realize there is a lot of messy code, and I apologize for that. I just wanted to show the entire thing, so it's easier to spot the problem. Help would be appreciated.
In general way, you should add if(read_choice.hasNext()) before invoking read_choice.next(); You have the exception java.util.NoSuchElementException because no elements found to be read. this is a good habit.
About your problem, you are getting error because you has closed scanner before finish reading. Put read_choice.close() outside of loop.
Moreover, for simplify, if you want to read integer, just simple : scanner.nextInt().
read_choice.close();
Don't close the scanner as long as you are not done reading all the inputs. Doing also closes the underlying input stream (System.in), check the documention;
You don't need to initialize the Scanner multiple times. Just create one instance and pass it around (keep using it).
Also,
for(int i=0; i < this.num_choices; i++)
{
//if(s2.hasNext())
//{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
you don't need that condition check. The next() will block until the input is entered.