Java if statement after switch - java

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

Related

I had error in Department constructor in if else in dept function

I had an error in the Department constructor in the if else statement in dept() method. How can I solve this?
I tried several tries by making the function abstract using different function name but it doesn't work.
class Book
import java.util.*;
class Book
{
int Book_id;
String Book_Name;
String Author_Name;
int pages;
float prices;
void getbook()
{
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Book ID");
Book_id=SC.nextInt();
System.out.println("Enter the Book Name");
Book_Name=SC.next();
System.out.println("Enter the Author Name");
Author_Name=SC.next();
System.out.println("Enter the pages");
pages=SC.nextInt();
System.out.println("Enter the prices");
prices=SC.nextFloat();
}
void display()
{
System.out.println("Book Id"+Book_id);
System.out.println("Book Name"+Book_Name);
System.out.println("Author Name"+Author_Name);
System.out.println("Pages"+pages);
System.out.println("Prices"+prices);
}
}
class Student
class Student extends Book
{
String Student_N;
int roll_no;
}
class Department
class Department extends Student
{
int choice;
String Dept_Code;
Department(int roll,String C)
{
System.out.println(""+C+""+roll_no);
}
void dept()
{
Scanner SC=new Scanner(System.in);
System.out.println("1.Civil Enginerring");
System.out.println("2.Computer Enginerring");
System.out.println("3.Information Tecnology");
System.out.println("4.Mechanical Engineering");
System.out.println("5.Electorics Enginerring");
System.out.println("6.Electrical Enginerring");
System.out.println("Enter the choice");
choice=SC.nextInt();
switch (choice)
{
case 1:
dept_data();
break;
case 2:
dept_data();
break;
case 3:
dept_data();
break;
case 4:
dept_data();
break;
case 5:
dept_data();
break;
case 6:
dept_data();
break;
}
}
void dept_data()
{
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Student Details");
System.out.println("Enter the Student Name");
SC.next();
System.out.println("Enter the Student Roll No");
SC.nextInt();
System.out.println("Enter the Book ID");
SC.nextInt();
System.out.println("Enter the Book Name");
SC.next();
}
int dept_del(String C)
{
Scanner SC=new Scanner(System.in);
if(C.compareTo("ci")==0||C.compareTo("CI")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("IT")==0||C.compareTo("it")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("CO")==0||C.compareTo("co")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("ME")==0||C.compareTo("me")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("EC")==0||C.compareTo("ec")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("EE")==0||C.compareTo("ee")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
}
}
class Project
class Project
{
public static void main(String[] args)
{
int i=1,flag=0;
Department A[]=new Department[100];
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Choice");
System.out.println("1.Add a Book\n2.Display the Book");
while(flag==0)
{
int choice=SC.nextInt();
switch (choice)
{
case 1 :
A[i].getbook();
i++;
case 2:
int n=i;
for(i=0;i<n;i++)
A[i].display();
case 3:
flag=1;
break;
default:
System.out.println("Wrong Choice");
}
}
}
}
The problem in your constructor is that it receives int roll, String C and does nothig with them and the instance vars int choice& String Dept_Codeare not defined after the constructor executes.
Maybe you wanted to do:
Department(int choice, String Dept_Code) {
this.choice = choice;
this.Dept_Code = Dept_Code;
System.out.println("" + Dept_Code + " - " + choice);
}
In the switch(choice) some breaks are missing after case 1 & 2 if you want to separate add a book fom display the book and from case 3:
switch(choice) {
case 1 :
A[i].getbook();
i++;
break;
case 2:
int n=i;
for(i=0;i<n;i++)
A[i].display();
break;
case 3:
flag=1;
break;
default:
System.out.println("Wrong Choice");
}
And in the other switch it makes no sense to create a switch if all the cases just execute the same dept_data()
code.
And as a suggestion it's better to always use the constant first when comparing to prevent from possible null pointers:
"ci".compareTo(C) is better than C.compareTo("ci") as the second option could throw a null pointer exception if C is undefined. Also, have a look at naming conventions: https://www.geeksforgeeks.org/java-naming-conventions/

Passing user input between cases in switch java

I have a small problem with this code. I added lecturer in case 1 and I trying to add books to this lecturer in case 3. problem is that it seems that case 3 doesn't recognize the created lecturer.
Is there any way to pass this value.
The solution is probably very simple but at this hour I just can not get it...
public class Menu {
static Scanner in = new Scanner (System.in);
LectureList lec = new LectureList(100);
BookList bl = new BookList(0);
public Menu(){
}
public int mainMenu(){
int option = 0;
System.out.println("---------------------------------------------------------");
System.out.println(" Lecturer Menue ");
System.out.println("*********************************************************");
System.out.println("1) Add Lecturer");
System.out.println("2) Find Lecturer by ID");
System.out.println("3) Add book to Lecturer BookList");
System.out.println("4) Remove book from Lecturer BookList ");
System.out.println("5) Search for a book using the ISBN number");
System.out.println("6) Calculate the yearly book payment");
System.out.println("7) Output all of the book details in the system to a file");
System.out.println("8) Exit");
boolean selected = false;
while (selected == false)
{
try
{
option = in.nextInt();
in.nextLine();
if
((option == 8)){
System.out.println("Goodbye!");
System.exit(0);}
else if
((option <= 0) || (option > 8))
System.out.println("Sorry but you have to choose an option between 1 and 8");
else
selected = true;
}
catch (InputMismatchException e)
{
System.out.println("Sorry you did not enter a valid option");
in.next();
}
}
return option;
}
public void menuSwitch(){
boolean finish = false;
if (finish == false){
int option = mainMenu();
switch (option){
case 1:
String LecName = " ";
System.out.println("Please enter Lecturer's name");
LecName = in.nextLine();
Lecturer l = new Lecturer(LecName);
lec.add(l);
break;
case 2:
break;
case 3:
String name = "";
Double price = 00.00 ;
String isbn ="";
String author = "";
System.out.println("Please enter Book title ");
name = in.nextLine();
System.out.println("Please enter Book's price ");
price = in.nextDouble();
System.out.println("Please enter Book's isbn number ");
isbn = in.next();
System.out.println("Please enter book author's name");
author = in.next();
Book b = new Book( name, price, isbn, author);
l.addBook(b);
break;``
default:
finish = true;
break;
}
menuSwitch();
}
}
}
Every case statement in your switch finishes with a break;, and the default case does as well. In that case, for any pass through the switch statement, only a single case label will be executed.
If the first pass executes the first case, and the second pass executes the second case, the variables defined in the first case will no longer be around -- they will have fallen out of scope when the switch statements completes the first time.
Can you get a reference to your Lecturer from the LectureList collection?
In case 1: you can create it and put it in the collection; in case 3: you can obtain it back from the collection and update it.

Java if else with nested loop

I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?
Error message that i got
Enter your selection:
1
You have selected No.1
Please enter your age**Exception in thread "main"
java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Assignment.main(Assignment.java:48)**
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println(
"1. Add player" + "\n" +
"2.Display transaction" + "\n" +
"3.Begin the ride");
System.out.println("");
System.out.println("Enter your selection: ");
char selection = sc.findInLine(".").charAt(0);
sc.close();
switch(selection) {
case '1' :
System.out.println("You have selected No.1");
break;
case '2' :
System.out.println("You have selected No.2" );
break;
case '3' :
System.out.println("You have selected No.3" );
break;
default:
System.out.println("Please make a selection");
break;
}
if (selection=='1') {
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt();
while (age<100) {
age+=age;
}
}
else if (selection=='2') {
System.out.println("Display daily transaction");
}
else if (selection=='3') {
System.out.println("Begin the ride");
}
else {
System.out.println("Please enter a valid input");
}
}
Please read basic Java so that you can learn programs better.
you can reduce this code to a very good extent, i haven't removed nested-if statements, which you can by moving all execution under case statements.
This program will terminate if option entered is not a number, this can also be improved by reading it as a string and checking is its one of the valid options (map's key set).
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class SwitchCase {
public static Map<Integer, String> options = new LinkedHashMap<Integer, String>();
static {
options.put(1, "Add player");
options.put(2, "Display transaction");
options.put(3, "Begin the ride");
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
for (Integer option : options.keySet()) {
System.out.println(option + ". " + options.get(option));
}
System.out.println("Enter your selection: ");
int selection = sc.nextInt();
switch (selection) {
case 1:
case 2:
case 3:
System.out.println("You have selected No." + selection);
break;
default:
System.out.println("Please make a selection");
break;
}
if (selection == 1) {
int age = 0;
System.out.print("Please enter your age : ");
age = sc.nextInt();
while (age < 100) {
age += age;
}
System.out.println(age);
} else if (selection == 2) {
System.out.println(options.get(selection));
} else if (selection == 3) {
System.out.println(options.get(selection));
} else {
System.out.println("Please enter a valid input!");
}
}
}
switch case is a type of nested if else.we can use switch in place of nested if else.you need not to use both switch case and nested if else simultaneously.
you can write your code like this.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("1. Add player" + "\n" +
"2.Display transaction" + "\n" +
"3.Begin the ride");
System.out.println("");
System.out.println("Enter your selection: ");
char selection = sc.findInLine(".").charAt(0);
switch(selection) {
case '1' :
System.out.println("You have selected No.1");
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt();
while (age<100) {
age+=age;
}
System.out.print(age);
break;
case '2' :
System.out.println("You have selected No.2" );
System.out.println("Display daily transaction");
break;
case '3' :
System.out.println("You have selected No.3" );
System.out.println("Begin the ride");
break;
default:
System.out.println("Please make a selection");
System.out.println("Please enter a valid input");
break;
}
sc.close();
}
The exception is pretty clear on the problem: java.lang.IllegalStateException: Scanner closed
Before your code enters the switch, you're closing the scanner with sc.close();. But later on you're trying to read from it again:
if (selection=='1') {
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt(); // <---- Here
while (age<100) {
age+=age;
}
}
But this will fail if the scanner is already closed. To solve this, you can simply put the line sc.close() to the end of your main.
As an alternative you could wrap everything into a try-with-resources block, so that you don't have to care about closing the scanner anymore because it will be closed automatically after leaving the block.

System.in.read is causing loop to execute thrice

import java.io.IOException;
import java.io.InputStreamReader;
public class doSwitch {
public static void main(String[] args) throws IOException {
char choice;
do {
System.out.println("Welcome User");
System.out.println("1. Change plan");
System.out.println("2. Pay Bill");
System.out.println("3. Complaints");
System.out.println("4. De-activate account");
System.out.println("Choose one the above option");
choice = (char) System.in.read();
} while (choice < '1' || choice > '4');
System.out.println("User's Choice:" + choice);
///////////////////////////// switch
///////////////////////////// case////////////////////////////////////
switch (choice) {
case '1':
System.out.println("There are different plans than you can opt for");
break;
case '2':
System.out.println("Pay bill using credit card or debit card");
break;
case '3':
System.out.println("In case of complaint call 121");
break;
case '4':
System.out.println("Are you sure you want to discontinue with us");
break;
}
}
}
This codes works properly if i entered values between 1 to 4. But If the value is greater than 4 then its executing the loop 3 times. I figured out its taking the value \n, \r. What i m not getting is how can i avoid it. and why it works for values 1-4
try
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
System.in.read() reads a single byte. In your case it reads the actual inputed character. If the character doesn't equal 1-4, then the loop continues and the next byte will be read, which will be a return character. The scanner objects takes care of this for you.

Restrict Switch Statement order

I am writing a menu in java using a switch statement and while loop. I am looking to find a way of ensuring the user completes menu one before proceeding to menu two.
Here is an example piece of code:
(Please note I normally pass data using setters and getters, this is just a quick program I wrote for this question)
package menuOrder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int option = 0;
String Fname = null;
String Sname = null;
int Age = 0;
while(option !=5){
System.out.println("1. Enter Firstname");
System.out.println("2. Enter Surname");
System.out.println("3. Enter Age");
System.out.println("4. Display Details");
System.out.println("5. System Exit");
option = sc.nextInt();
switch(option){
case 1:
System.out.println("Please enter your Firstname >");
Fname = sc.next();
break;
case 2:
System.out.println("Please enter your Surname >");
Sname = sc.next();
break;
case 3:
System.out.println("Please enter your Age >");
Age = sc.nextInt();
break;
case 4:
System.out.println("Firstname = " + Fname + "\nSurname = " + Sname + "\nAge = " + Age);
break;
case 5:
System.out.println("You have chosen to System Exit!!!");
System.exit(0);
break;
default:
System.out.println("Invalid Entry!! \nPlease try again");
}
}
}
}
I am trying to prevent the use from entering their Surname before their Firstname.
Can someone please help?
Thanks
First show only the first name. Then when the user enters first name call surname method from that method.Use method calls instead of switch case.

Categories

Resources