How to ignore lettercase? [duplicate] - java

This question already has answers here:
Case insensitive matching in Java switch-case statement
(5 answers)
Closed 2 years ago.
So, I'm trying to make a simple menu with switches.
I have a letter choice inside it. I'm using next().charAt(0); to scan a letter.
It worked well, but I want to simplify it. you see, I have to make a case each choice both uppercase and lowercase.
So how to ignore case so I don't have to make both cases?
Also note: I'm using the old version of Java and Netbeans 8.2 as my IDE. (because my college keeps insisting not to use the newer one. Probably because they don't have the textbook yet.), so probably newer syntax wouldn't work.
my code:
import java.util.Scanner;
public class NewClass2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
char milk;
int s, h, price;
h = 0;
price = 0;
String type, size;
System.out.println("NutMart");
System.out.println("Milk selections:\n A. Milk A \n\t 1. Regular ($10) \n\t 2. Medium ($20) \n\t 3. Large ($30)");
System.out.println(" B. Milk B \n\t 1. Regular ($15) \n\t 2. Medium ($30) \n\t 3. Large ($45)");
System.out.println(" C. Milk C \n\t 1. Regular ($20) \n\t 2. Medium ($40) \n\t 3. Large ($60)");
System.out.println("Insert Milk Type: ");
milk = input.next().charAt(0);
switch(milk){
case 'a':
type = "Milk A";
h = 10;
break;
case 'b':
type = "Milk B";
h = 15;
break;
case 'c':
type = "Milk C";
h = 20;
break;
case 'A':
type = "Milk A";
h = 10;
break;
case 'B':
type = "Milk B";
h = 15;
break;
case 'C':
type = "Milk C";
h = 20;
break;
default:
System.out.println("Invalid!");
System.out.println("Please select the correct choice: ");
milk = input.next().charAt(0);
break;
}
System.out.println("Select the size: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
switch(s){
case 1:
size = "Regular";
price = h * 1;
break;
case 2:
size = "Medium";
price = h * 2;
break;
case 3:
size = "Large";
price = h * 3;
break;
default:
System.out.println("Invalid");
System.out.println("Please select the correct choice: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
break;
}
System.out.println("Individual Price: $" + price);
System.out.println("Please insert the quantity: ");
while (!input .hasNextInt()) input .next();
int quantity = input.nextInt();
int total = price * quantity;
System.out.println("Your total will be $" + total );
}
}

Note, that in this case converting to a consistent case is the best was to achieve your goal. But when you have a variety of results for dissimilar inputs in a switch statement you can do the following for case constructs.
case 'a':
case 'A:
type = "Milk A";
h = 10;
break;
...
The case will simply fall thru whether 'a' or 'A' was provided.

Related

How to organize my Java code into classes

I will show you my code without any classes.
I need it divided in 3 classes which are Main class , First class , Second class.
for example ,
the main class
products class
and coding class maybe
package vending.machine.project;
import java.util.Scanner;
public class VendingMachineProject {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n=1;
int x=1;
int exit=0;
double price = 0;
double tax = 0.15;
char choice;
double finPrice=0;
while(exit!=-1)
{
while(n!=5)
{
if(n>0&&n<5)
{
System.out.print("1.Hot Drinks\n2.Soft Drinks\n"
+ "3.Chips\n4.Sweets\n5.Exit\n\n");
System.out.print("Choose one of the types above: ");
n = keyboard.nextInt();
switch(n)
{
case 1:
System.out.print("1.Hot Chocolate (5$)\t\t\t2.Tea (2$)\n3.Caramel Latté (7$)\t\t\t"
+ "4.Turkish Coffee (6$)\n5.Espresso (8$)\t\t\t\t6.Green Tea (3$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 5;
break;
case 2:
price = price + 2;
break;
case 3:
price = price + 7;
break;
case 4:
price = price + 6;
break;
case 5:
price = price + 8;
break;
case 6:
price = price + 3;
break;
}
}
else
System.out.print("Please choose one of"
+ " the hot drinks above Sir: ");
}while(!(x>0&&x<7));
break;
case 2:
System.out.print("1.Cocacola (2$)\t\t\t2.PEPSI (3$)\n3.Seven UP (1$)\t\t\t"
+ "4.Code Red (4$)\n5.Sprite (1$)\t\t\t6.Mirinda (2$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 2;
break;
case 2:
price = price + 3;
break;
case 3:
price = price + 1;
break;
case 4:
price = price + 4;
break;
case 5:
price = price + 1;
break;
case 6:
price = price + 2;
break;
}
}
else
System.out.print("Please choose one of"
+ " the soft drinks above Sir: ");
}while(!(x>0&&x<7));
break;
case 3:
System.out.print("1.Lays (1$)\t\t\t2.Chips Oman (3$)\n3.Cheetos (3$)\t\t\t"
+ "4.Doritos (2$)\n5.Bugles (2$)\t\t\t6.AL Batal (1$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 1;
break;
case 2:
price = price + 3;
break;
case 3:
price = price + 3;
break;
case 4:
price = price + 2;
break;
case 5:
price = price + 2;
break;
case 6:
price = price + 1;
break;
}
}
else
System.out.print("Please choose one of"
+ " the Chips above Sir: ");
}while(!(x>0&&x<7));
break;
case 4:
System.out.print("1.Oreo (1$)\t\t\t2.Kinder (4$)\n3.Bounty (3$)\t\t\t"
+ "4.Twix (3$)\n5.Galaxy (2$)\t\t\t6.Biscream (1$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 1;
break;
case 2:
price = price + 4;
break;
case 3:
price = price + 3;
break;
case 4:
price = price + 3;
break;
case 5:
price = price + 2;
break;
case 6:
price = price + 1;
break;
}
}
else
System.out.print("Please choose one of"
+ " the sweets above Sir: ");
}while(!(x>0&&x<7));
break;
case 5:
exit = -1;
break;
}
System.out.print("Do you want to order anything more Sir?"
+ "type (y). If not Type (n) to Exit: ");
do{
choice = keyboard.next().charAt(0);
Character.toLowerCase(choice);
if(choice=='n'){
n = 5;
exit = -1;
}
else if(choice!='y'){
System.out.print("Please Sir choose (y) or (n): ");
}
}while(choice!='y'&&choice!='n'&&n!=5);
}
else {
System.out.print("Please choose from the list Above: ");
n = keyboard.nextInt();
}
}
}
}
}
You need to study the basics of object-oriented programming.
There is no one exact best way to organize your code into classes. Even separating the better ways from the less optimal ways takes more information about the business that you have given here. But let's walk though the basics to get you going.
Look for the things, the entities, from the real world that you are modeling in your app. Then list the attributes, the properties, that describe each particular entity.
I see products (food items) as an entity. Each product has a name, a price, and a category (hot drink, cold drink, chips, candy, and so on, as its attributes.
So write a class called Product to represent each product you are selling. In Java 16 and later, you might use a record to more briefly write the class. A record is appropriate only for a class whose main purpose is to merely communicate data transparently and immutably, with a focus on state rather than behavior, and no inheritance.
public record Product ( String name , int price , String category ) {}
If you were further advanced, I'd suggest an enum for the category. But for now use a String with text.
Instantiate your products.
Product oreo = new Product( "Oreo" , 1 , "Cookie" ) ;
Another entity is the vending machine. The vending machine holds a list of products. Make another class for this.
public class VendingMachine
{
// Member fields.
final private List< Product > products ;
…
// Constructor.
public VendingMachine()
{
this.products =
List.of(
new Product( "Oreo" , 1 , "Cookie" ) ,
new Product( "Turkish Coffee" , 6 , "Hot drink" ) ,
…
)
;
…
}
// Methods.
…
public List< Product > getProductsForCategory( String category )
{
… Loop all the products to find the ones whose assigned category matches this desired category.
}
}
That vending machine object knows how to search its list of products to produce a subset of products by category. So we have the getProductsForCategory method. That method returns an ordered collection, a List.
VendingMachine vendingMachine = new VendingMachine() ;
…
List< Product > cookies = vendingMachine.getProductsForCategory( "Cookie" ) ;
You might want a sort-order field, just an integer number, as another member field on your Product class if the business (your client) wants to list certain products ahead of others. With such a field, the getProductsForCategory method could sort the products.
Next we need to present each category’s list of products to the user. So we need a user-interface.
Make another class to interact with the user via the console. The UI class knows about public interface of the vending machine object, but the vending machine does not know about the console nor the user. The vending machine only knows about the products it offers.
The UI object will access each category of products from the vending machine, getting a list. The UI object will loop through those objects to present a menu to user. Based on user's feedback, the UI object builds a collection of the products and quantities ordered by the user. You might write another class for this "shopping cart" or "order pad" of the user's choices, with a total price calculated.
In more realistic work, a vending machine would also need to manage its inventory. But I suppose that aspect is outside the scope of your schoolwork assignment.

I am creating a simple calculator in switch statement using methods but it straight goes to default, even if i press correct case

I am making this simple calculator program using switch statements and methods. But when the user presses any option (which is correct), it does not read the case and goes straight to the default case.
I've done the same thing before, but without any class file or methods. I'm new to methods so I just tried to do the same thing but it's not working properly.
NewClass cal = new NewClass();
Scanner in = new Scanner(System.in);
System.out.println("Press 1 for Division.\nPress 2 for Multiplication.\nPress 3 for Addition.\nPress 4 for Substraction.");
char c = in.next().charAt(0);
System.out.println("Enter First Value : ");
int a = in.nextInt();
System.out.println("Enter Second Value : ");
int b = in.nextInt();
switch (c){
case 1:
cal.division(a, b);
break;
case 2:
cal.division(a, b);
break;
case 3:
cal.add(a, b);
break;
case 4:
cal.sub(a, b);
break;
default:
System.out.println("Invalid entry.");
break;
}
output:
Press 1 for Division.
Press 2 for Multiplication.
Press 3 for Addition.
Press 4 for Substraction.
Enter your selection : 3
Enter First Value :
4
Enter Second Value :
5
Invalid entry.
BUILD SUCCESSFUL (total time: 9 seconds)
There is no need to convert user input to a char, as java switches can handle ints. The following code will fix your issue:
NewClass cal = new NewClass();
Scanner in = new Scanner(System.in);
System.out.println("Press 1 for Division.\nPress 2 for Multiplication.\nPress 3 for Addition.\nPress 4 for Substraction.");
int c = in.nextInt();
System.out.println("Enter First Value : ");
int a = in.nextInt();
System.out.println("Enter Second Value : ");
int b = in.nextInt();
switch (c){
case 1:
cal.division(a, b);
break;
case 2:
cal.division(a, b);
break;
case 3:
cal.add(a, b);
break;
case 4:
cal.sub(a, b);
break;
default:
System.out.println("Invalid entry.");
break;
}

Java - Assign a number and a word to a string of inputted characters

I am new to Java and I am trying to make a program that will take a string, such as 'asdfg', and print words and a total number that are associated with these letters.
So 'a' would be 'apple' and its assigned number is 10, 's' would be spinach, and its assigned number is 5, 'd' would be 'dog' and its assigned number would be 15, 'f' would be 'frog' and its assigned number would be 20 and 'g' would be 'goat' and its assigned number would be 25. The output would look something like 'apple spinach dog frog goat 75'.
The code I have so far is
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
public class PizzaTwo {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the details of your order");
String myList = scan.nextLine();
for (int i = 0; i < myList.length(); i++) {
int letNum = 0;
switch (myList.charAt(i)) {
case 'a':
System.out.println("apple" + letNum);
letNum += 10;
break;
case 's':
System.out.println("spinach" + letNum);
letNum += 5;
break;
case 'd':
System.out.println("dog" + letNum);
letNum += 15;
break;
case 'f':
System.out.println("frog" + letNum);
letNum += 20;
break;
case 'g':
System.out.println("goat", letNum);
letNum += 25;
break;
default:
System.out.println("Nothing..");
break;
}
}
}
}
Thank you for any help.
First of all, I'd like to suggest you use better names for variables.
You were resetting the "letNum" in each loop, then I've moved it out of the loop.
I recommend read about String and StringBuilder.
String objects are immutable, so instead to create more variables to concatenate "flavors", I used StringBuilder that are mutable.
Strings are constant; their values cannot be changed after they are created
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type
import java.util.Scanner;
public class PizzaTwo {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the details of your order");
String flavors = scan.nextLine();
int price = 0;
StringBuilder order = new StringBuilder();
for (int i = 0; i < flavors.length(); i++) {
switch (flavors.charAt(i)) {
case 'a':
order.append("apple ");
price += 10;
break;
case 's':
order.append("spinach ");
price += 5;
break;
case 'd':
order.append("dog ");
price += 15;
break;
case 'f':
order.append("frog ");
price += 20;
break;
case 'g':
order.append("goat ");
price += 25;
break;
default:
order.append("No flavor added ");
break;
}
}
System.out.println(order.append(price));
}
}
It looks like you want the numbers to only appear after all the words have been printed, from your description "apple spinach dog frog goat 75", but your code looks like it's trying to append the number to the end of each word.Assuming you want the output to be like your sample output, don't try to print the numbers after each word, instead after all the words have been printed print the variable you've been using to accumulate each letters value, 'letNum' in your code.Also, don't reset 'letNum' each time you deal with a new letter.
Take 2 separate variables, 1 string and another number. Each time concatenate with existing string, means something like String s=""; int n=0; s+="Apple"; n+=10; s+="frog";
....
Now when loop is done print string then the number.

orphaned case error in a switch statments

i wrote a small program in java
the user enter a number to get his multiplication table
and then type the maximum length of that table
but in the third case (case r) i got an error orphaned case
and it seems clean code to me
public class JavaApplication2 {
public static void main(String[] args) throws IOException
{
System.out.println("Multiplication Table v1.0");
System.out.println("Developped By Roy Jalbout");
System.out.println("-------------------------");
System.out.println("Type 'E' To Quit The Program\nType 'H' To Read The Help File\nType 'R' To Run The Program");
char act = (char)System.in.read();
switch (act) {
case 'e':
case 'E':
System.exit(0);
break;
case 'h':
case 'H':
System.out.println("The Multiplication Table Version 1.0 Developped By Roy Jalbout is A Simple Program All you have to do is to choose the number that you want to get his multiplication table and then choose the maximum lenght of that table");
System.out.println("----------------------------------");
System.out.println("Type back to go to the main thread");
String mainthread = scn.next();
if ("back".equals(mainthread)){
JavaApplication2.main(args);
break;
case 'r':
case 'R':
Scanner scn = new Scanner(System.in);
System.out.print("Enter A Number To Get His Multiplication Table : ");
int num = scn.nextInt();
System.out.print("Enter The Max Number Of The Multiplication Table : ");
int max = scn.nextInt();
int b=1;
while (b<=max){
System.out.println(num + " * " + b + " = " + b*num);
b++;
JavaApplication2.main(args);
}
default:
System.out.println(act + " is an Invalid Choice");
}
}
}
}
any help???
if ("back".equals(mainthread)){
JavaApplication2.main(args);// you are not closing the brace here..
break;
The problem with the orphaned case, for me, was there was a couple of not closed curly brackets after I began the switch case.
For example, there was a loop inside a case which I had not closed.
Once I closed there was no obstacles

find binary representation in array

i need to make a switch statement that can use the appropriate conversion method. here is my code
public class ExerciseTwo
{
public static void main (Strings[] args)
{
Scanner input = new scanner(system.in);
String[] binary = { "0","1","2","3","4","5","6","7","8"};
for (c = 0; c < array.length; counter++)
binary[] = input.nextInt();
System.out.println("Enter number between 0 and 8");
number = input.nextInt();
system.out.printf("the number", "number_given", "is", "binaryVersion", "binary");
}
}
I'm sorry, but the description wasn't very clear to me. Are you simply trying to convert the input value (between 0 and 8) into a binary format (as in 2 -> 10, 7 -> 111) using a switch statement? If so, this code will work. If not, can you clarify the question for me?
Thanks!
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number between 0 and 8");
int number = input.nextInt();
int binaryRepresentation = -1;
switch (number)
{
case 0:
binaryRepresentation = 0;
break;
case 1:
binaryRepresentation = 1;
break;
case 2:
binaryRepresentation = 10;
break;
case 3:
binaryRepresentation = 11;
break;
case 4:
binaryRepresentation = 100;
break;
case 5:
binaryRepresentation = 101;
break;
case 6:
binaryRepresentation = 110;
break;
case 7:
binaryRepresentation = 111;
break;
case 8:
binaryRepresentation = 1000;
break;
}
System.out.printf("the number " + number + " is " + binaryRepresentation + " in binary (-1 means invalid input)");
}
Do your home work yourself , Look at the http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html switch case definition. If you really want good solution for binary representation then look at API documentation of the Integer class
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html?is-external=true
Using the API doc is one of the first things you need to learn as a Java programmer.

Categories

Resources