Java: Number of specific character reports - java

I've made a program to count the number of each letters in a phrase
What I want the resulting text to return is
Enter a phrase
"Cow goes to the market"
There are 1 C('s), 3 O('s), 1 W('s), 1 G('s), 3 E('s), 1 S('s), 3 T('s).. /* you get the gist */ in your phrase.
I want the results to be concatenated into a string instead of just a multi-lined report.
import java.util.*;
public class charCount
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
//Prompt for user entry
System.out.println("Enter a phrase: ");
String letterN = keyboard.nextLine();
charCount(letterN);
}
public static int charCount(String letterN)
{ //variable initializations
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
a = b = c = d = e = f = g = h = i = j = k = l = m = n = o = p = q = r = s = t = u = v = w = x = y = z = 0;
int total = 0;
total += 1;
//for loop
for(int countN = 0; countN < letterN.length(); countN++) {
switch(letterN.charAt(countN)) {
case 'a':
a++;
break;
case 'b':
b++;
break;
case 'c':
c++;
break;
case 'd':
d++;
break;
case 'e':
e++;
break;
case 'f':
f++;
break;
case 'g':
g++;
break;
case 'h':
h++;
break;
case 'i':
i++;
break;
case 'j':
j++;
break;
case 'k':
k++;
break;
case 'l':
l++;
break;
case 'm':
m++;
break;
case 'n':
n++;
break;
case 'o':
o++;
break;
case 'p':
p++;
break;
case 'q':
q++;
break;
case 'r':
r++;
break;
case 's':
s++;
break;
case 't':
t++;
break;
case 'u':
u++;
break;
case 'v':
v++;
break;
case 'w':
w++;
break;
case 'x':
x++;
break;
case 'y':
y++;
break;
case 'z':
z++;
break;
}
}
//Console logs
System.out.println("Below are the individual character counts for your string");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
System.out.println("E: " + e);
System.out.println("F: " + f);
System.out.println("G: " + g);
System.out.println("H: " + h);
System.out.println("I: " + i);
System.out.println("J: " + j);
System.out.println("K: " + k);
System.out.println("L: " + l);
System.out.println("M: " + m);
System.out.println("N: " + n);
System.out.println("O: " + o);
System.out.println("P: " + p);
System.out.println("Q: " + q);
System.out.println("R: " + r);
System.out.println("S: " + s);
System.out.println("T: " + t);
System.out.println("U: " + u);
System.out.println("V: " + v);
System.out.println("W: " + w);
System.out.println("X: " + x);
System.out.println("Y: " + y);
System.out.println("Z: " + z);
return total;
}
}
My problem is, I can of course concatenate a System.out.println(); with the int vars but it simply prints the number of letters. I don't know ahead of time what people will type so I need my program to detect if the letter = true and thus returns the character and number inside the report.
I've looked for solutions and cannot find a thing. I can't wrap my mind around this yet and frankly I have no idea how to word this inquiry.
Thank you guys ahead of time

Use a Map to store the characters you have encountered, and how many times they are seen. Using TreeMap will mean that when you iterate over the map the entries are sorted in natural order
import java.util.*;
public class CharCount {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Prompt for user entry
System.out.println("Enter a phrase: ");
String letterN = keyboard.nextLine();
charCount(letterN);
}
public static void charCount(String letterN) {
Map<Character, Long> charMap = new TreeMap<>();
for (char aChar : letterN.toCharArray()) {
if (charMap.containsKey(aChar)) {
charMap.put(aChar, charMap.get(aChar) + 1);
}
else {
charMap.put(aChar, 1L);
}
// this if/else can be written using the ternary operator as:
// charMap.put(aChar, charMap.containsKey(aChar) ? charMap.get(aChar) + 1 : 1L);
}
for (Character character : charMap.keySet()) {
System.out.println(character + ": " + charMap.get(character));
}
}
}

Related

Java Simple English Calculator, output issue

I am writing a calculator program that takes inputs from 0-9 and outputs the results in both numerical from and in plain english (Ex: Two plus three equals 5). I have gotten it to be able to print out the result in words but I am now stuck on how to get it to print out the original problem in numerical form. The output must include both the result in numbers and in words.
The numbers have already been converted into strings through a switch statement but is there anyway I can print out the original problem? If not would I have to completely restructure this instead? Any help would be appreciated I have been stuck on this for a while now.
Here is my code
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operation;
int num1, num2;
//Asks for user to input first number
System.out.println("Please enter the first number (0-9)");
num1 = input.nextInt();
//Asks user for an operation
System.out.println("Please enter the type of operation that you would like to perform");
operation = input.next().charAt(0);
//Asks user to input the second number
System.out.println("Please enter the second number (0-9)");
num2 = input.nextInt();
//Limits the numbers to the range of 0-9
if(num1 > 9 || num2 > 9){
System.out.println("Invalid Digit!!");
System.exit(0);}
//An array that converts number into a string
String num[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
break;
case '/': //Division conversion
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
break;
case '^': //Exponentiation conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;}
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
break;
default:
System.out.println("Error: Invalid Operation Entered"); }
}
}
Its very simple, I think you are getting confused. Consider following points:
You have original numbers saved in num1 and num2, so if you want to show the original numbers in integer form, then just use num1 instead of num[num1]
You are checking for zero division when finding exponent. You should shift this check to division case.
Replace your switch like this:
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" - "+num2 + " = " + (num1-num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" + "+num2 + " = " + (num1+num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
System.out.println(num1+" * "+num2 + " = " + (num1*num2));
break;
case '/': //Division conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;
}
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
System.out.println(num1+" / "+num2 + " = " + (num1/num2));
break;
case '^': //Exponentiation conversion
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
System.out.println(num1+" ^ "+num2 + " = " + Math.pow(num1,num2));
break;
default:
System.out.println("Error: Invalid Operation Entered");
}
See if the below print statements helps
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" "+operation + " "+num2+ "="+(num1 - num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" "+operation + " "+num2+ "="+(num1 + num2));
break;
is it this what you are looking for? for example for 9 + 9 your output will be:
nine plus nine is 18 9 + 9 = 18
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operation;
int num1, num2;
//Asks for user to input first number
System.out.println("Please enter the first number (0-9)");
num1 = input.nextInt();
//Asks user for an operation
System.out.println("Please enter the type of operation that you would like to perform");
operation = input.next().charAt(0);
//Asks user to input the second number
System.out.println("Please enter the second number (0-9)");
num2 = input.nextInt();
//Limits the numbers to the range of 0-9
if(num1 > 9 || num2 > 9){
System.out.println("Invalid Digit!!");
System.exit(0);}
//An array that converts number into a string
String num[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 - num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 + num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 * num2));
break;
case '/': //Division conversion
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 / num2));
break;
case '^': //Exponentiation conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;}
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(Math.pow(num1,num2)));
break;
default:
System.out.println("Error: Invalid Operation Entered"); }
}
}

Reverse rubik's cube algorithm

I have been all day strugglingh through this simple function, but i can't get it working as I would like to. It may seem simple at first, and there is indeed another entry in Stack Overflow which talks about it. However, things get messy when brackets are introduced.
Let's say we can get an algorithm for a Rubiks cube which will look something like
(R U R' U) U' (R U' R')
It is important to note that after every move, whether it has a "'" or not, there is a space, except for those before the end brackets.
Now, for every algorithm on a Rubik's cube there exists its inverse, the one which undoes it. For example, the inverse of R is R' and of U is U, and the inverse of R U is U' R'. Thus, the inverse of the example is:
(R U R') U (U' R U' R')
It is also important to nothe that there are many moves (F, B, D, U, u, f, M, S, x, y, z...)
Also every alg has its own inverse (R has R' and vice versa,
Can you get any function in Java for that?
I have tried infinite loops of ifelse, for, switch...
I will leave some of my tries just for reference
String fullAlg = text.toString() + " ";
String reversedAlg = "hh";
int numSpaces = 1;
int pos1 = 0, pos2 = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' && numSpaces == 0) {
numSpaces++;
pos1 = i;
}
if (text.charAt(i) == ' ' && numSpaces == 1) {
numSpaces++;
pos2 = i;
}
if (numSpaces == 2) {
if (fullAlg.substring(pos1, pos2).matches("[a-zA-Z]+")){
Toast.makeText(this, "YES", Toast.LENGTH_SHORT).show();
}
switch (fullAlg.substring(pos1, pos2)) {
//Begin with (
case "(" + "[a-zA-Z]+":
reversedAlg += ")'" + fullAlg.substring(pos1, pos2).charAt(1);
break;
case "(" + "[a-zA-Z]+" + "\'":
reversedAlg += ")" + fullAlg.substring(pos1, pos2).charAt(1);
break;
case "(" + "[a-zA-Z]+" + "2":
reversedAlg += ")2" + fullAlg.substring(pos1, pos2).charAt(1);
break;
//No ()
case "[a-zA-Z]+":
reversedAlg += " '" + fullAlg.substring(pos1, pos2).charAt(0);
break;
case "[a-zA-Z]+" + "\'":
reversedAlg += " '" + fullAlg.substring(pos1, pos2).charAt(0);
break;
case "[a-zA-Z]+" + "2":
reversedAlg += " 2" + fullAlg.substring(pos1, pos2).charAt(0);
break;
//End with )
case "[a-zA-Z]+" + ")":
reversedAlg += " '" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "[a-zA-Z]+" + "\'" + ")":
reversedAlg += " " + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "[a-zA-Z]+" + "2" + ")":
reversedAlg += " )2" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
//Encapsulated in ()
case "(" + "[a-zA-Z]+" + ")":
reversedAlg += " )'" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "(" + "[a-zA-Z]+" + "\'" + ")":
reversedAlg += " )" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "(" + "[a-zA-Z]+" + "2" + ")":
reversedAlg += " )2" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
}
numSpaces = 0;
}
}
StringBuilder returnAlg = new StringBuilder(reversedAlg).reverse();
algTV.setText(fullAlg.substring(pos1, pos2));
}
Or this one
String fullAlg = text.toString();
String fullAldReversed = "";
int posStart = 0, posEnd = 0;
for (int i = 0; i < fullAlg.length(); i++) {
if (fullAlg.charAt(i) == '('){
posStart = i;
} else if (fullAlg.charAt(i) == ')'){
posEnd = i;
fullAldReversed += "(" + reverseAlg(fullAlg.substring(posStart, posEnd)) + ")";
posStart = 0;
}
}
if (posEnd == 0){
fullAldReversed = "" + reverseAlg(fullAlg);
}
algTV.setText(fullAldReversed);
}
private StringBuilder reverseAlg(CharSequence text) {
StringBuilder builder;
if (!(text.charAt(0) == ' ' || text.charAt(text.length() - 1) == ' ')) {
builder = new StringBuilder(text + " ");
} else {
builder = new StringBuilder(text);
}
int subStart = 0;
StringBuilder auxBuilder;
String substring = "", auxString = "";
for (int i = 0; i < builder.length(); i++) {
substring = "";
int subEnd = i;
int identifierMove = 0;
for (int j = subStart; j <= subEnd; j++) {
if (builder.charAt(j) == '\'')
identifierMove = 1;
else if (builder.charAt(j) == '2')
identifierMove = 2;
else if (identifierMove == 0)
identifierMove = 3;
}
String letterMove;
switch (identifierMove) {
case 1:
letterMove = builder.substring(subStart, subEnd - 1);
subStart = subEnd + 1;
substring = " " + letterMove;
break;
case 2:
letterMove = builder.substring(subStart, subEnd - 1);
subStart = subEnd + 1;
substring = " 2" + letterMove;
break;
case 3:
letterMove = builder.substring(subStart, subEnd);
subStart = subEnd + 1;
substring = " '" + letterMove;
break;
}
auxString += substring;
}
auxBuilder = new StringBuilder(auxString);
auxBuilder.reverse().toString();
return auxBuilder;
}
Thank you!!
Sorry for the delay! Your attempts are quite overcomplicated in my opinion. I thought it was the best choice to make a class to represent the Rubix cube algorithm because it's a bit complicated and the class will also leave room for further expansion. Anyways, the way it works is simple. The class constructor takes a string as an input and converts the text into integers for easier storage and manipulation. From here, reversing the algorithm is super simple! All you have to do is reverse the order of the array and multiply all the integers by -1! (Their opposites i.e. R' are stored as negatives.) Then, if you want to output it as a string, you may use the toStrng() function to display the Algorithm.
import java.util.ArrayList;
import java.util.Arrays;
class RubixAlg {
//We will store our list of moves as integers. (And also parentheses) Any X' is the negative value of X
//For example, U corresponds to 2, and U' corresponds to -2.
ArrayList<Integer> moves = new ArrayList<Integer>();
RubixAlg(String input){
String input1 = input+" ";//Adding a space to the end prevents the algorithm from breaking when it checks for an apostrophe where no text exists.
while(input1.length()>0){
println(input1.charAt(0));
//This part figures out what character is the first in the string, what move that corresponds to, and then deletes it until there's no more characters.
switch(input1.charAt(0)){
case ' ':
input1=input1.substring(1);
break;
case '(':
moves.add(1);
input1=input1.substring(1);
break;
case ')':
moves.add(-1);
input1=input1.substring(1);
break;
case 'U':
if(input1.charAt(1)=='\''){
moves.add(-2);
input1=input1.substring(2);
} else {
moves.add(2);
input1=input1.substring(1);
}
break;
case 'D':
if(input1.charAt(1)=='\''){
moves.add(-3);
input1=input1.substring(2);
} else {
moves.add(3);
input1=input1.substring(1);
}
break;
case 'F':
if(input1.charAt(1)=='\''){
moves.add(-4);
input1=input1.substring(2);
} else {
moves.add(4);
input1=input1.substring(1);
}
break;
case 'B':
if(input1.charAt(1)=='\''){
moves.add(-5);
input1=input1.substring(2);
} else {
moves.add(5);
input1=input1.substring(1);
}
break;
case 'R':
if(input1.charAt(1)=='\''){
moves.add(-6);
input1=input1.substring(2);
} else {
moves.add(6);
input1=input1.substring(1);
}
break;
case 'L':
if(input1.charAt(1)=='\''){
moves.add(-7);
input1=input1.substring(2);
} else {
moves.add(7);
input1=input1.substring(1);
}
break;
default:
input1=input1.substring(1);
break;
}
}
}
String toStrng(){
String output = "";
for(int i=0;i<moves.size();i++){
//println(moves.get(i));
int move = moves.get(i);
switch(move){
case 1:
output+="(";
break;
case -1:
output=output.substring(0,output.length()-1);
output+=")";
break;
case 2:
output+="U ";
break;
case -2:
output+="U\' ";
break;
case 3:
output+="D ";
break;
case -3:
output+="D\' ";
break;
case 4:
output+="F ";
break;
case -4:
output+="F\' ";
break;
case 5:
output+="B ";
break;
case -5:
output+="B\' ";
break;
case 6:
output+="R ";
break;
case -6:
output+="R\' ";
break;
case 7:
output+="L ";
break;
case -7:
output+="L\' ";
break;
default:
break;
}
}
return output;
}
void revers(){
//What this algorithm does is pretty simple. It changes the direction by multiplying all of the stored integers by -1, and then reversing their order.
Integer[] intermediate = new Integer[moves.size()];
intermediate=moves.toArray(new Integer[0]);
intermediate=ReverseNegArray(intermediate);
for(int i=0;i<intermediate.length;i++){
moves.set(i,intermediate[i]);
}
}
}
Integer[] ReverseNegArray(Integer[] x){
Integer[] y = new Integer[x.length];
for(int i = 1;i<=x.length;i++){
println(-x[x.length-i]);
y[i-1]=-x[x.length-i];
}
return y;
}
I have a partial solution, that will be complete if you can convert your String representation into an Algorithm object. This represents a Rubik's cube algorithm as a sequence of individual moves, and other nested algorithms, where each move has a side and a direction (i.e. whether it is inverted or not).
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class Rubiks
{
public static void main(String[] args)
{
// (R U R' U) U' (R U' R')
Instruction g1 = new Algorithm(Move.fore('R'), Move.fore('U'), Move.back('R'), Move.back('U'));
Instruction g2 = new Algorithm(Move.fore('R'), Move.back('U'), Move.back('R'));
Instruction full = new Algorithm(g1, Move.back('U'), g2);
System.out.println("This algorithm: " + full);
System.out.println("Inverts to be: " + full.inverted());
}
}
class Move implements Instruction
{
private final char side;
private final boolean inverse;
private Move(final char side, final boolean inverse)
{
this.side = side;
this.inverse = inverse;
}
public static Move fore(final char side)
{
return new Move(side, false);
}
public static Move back(final char side)
{
return new Move(side, true);
}
public Move inverted()
{
return new Move(side, !inverse);
}
#Override
public String toString()
{
return side + (inverse ? "'" : "");
}
#Override
public String toSubString()
{
return toString();
}
}
class Algorithm implements Instruction
{
private final Deque<Instruction> moves;
private Algorithm(Deque<Instruction> moves)
{
this.moves = moves;
}
public Algorithm(Instruction... moves)
{
this.moves = new ArrayDeque<>(Arrays.asList(moves));
}
public Algorithm inverted()
{
Deque<Instruction> newMoves = new ArrayDeque<>(moves.size());
for (Instruction instruction : (Iterable<Instruction>) moves::descendingIterator)
{
newMoves.add(instruction.inverted());
}
return new Algorithm(newMoves);
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Instruction instruction : moves)
{
if(! first)
{
sb.append(' ');
}
first = false;
sb.append(instruction.toSubString());
}
return sb.toString();
}
}
interface Instruction
{
/**
* Returns the inverse of this instruction
* #return an instruction that undoes this instruction
*/
Instruction inverted();
/**
* Returns the string representation of the instruction, if it were nested in another instruction
* #return the result of toString, with parentheses if this is a complex instruction
*/
default String toSubString()
{
return "(" + toString() + ")";
}
}
I've used the Rubiks class to demonstrate that it works on the initial example you provided. It outputs the following:
This algorithm: (R U R' U') U' (R U' R')
Inverts to be: (R U R') U (U R U' R')
However I realise this answer may require you to implement more complicated logic to convert to this form if you are required to start out with a string representation of your algorithm, as parsing is not a trivial task.
After I read some answers I came up with this. Hope anyone who has the same question can get positive feedback. Thanks to everyone who tried to help me!
private void reverseAlg(CharSequence text) {
StringBuilder fullAlg;
if (!(text.charAt(0) == ' ' || text.charAt(text.length() - 1) == ' ')) {
fullAlg = new StringBuilder(text + " ");
} else {
fullAlg = new StringBuilder(text);
}
StringBuilder reversedAlg = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
if (fullAlg.charAt(i) != '(' && fullAlg.charAt(i) != ')' && fullAlg.charAt(i) != ' '
&& fullAlg.charAt(i) != '\'' && fullAlg.charAt(i) != '2') {
if (fullAlg.charAt(i + 1) == '\'') {
if (fullAlg.charAt(i + 2) == ')') {
reversedAlg.append(fullAlg.charAt(i)).append(")");
} else {
reversedAlg.append(fullAlg.charAt(i));
}
} else if (fullAlg.charAt(i + 1) == ' ') {
reversedAlg.append("\'").append(fullAlg.charAt(i));
} else if (fullAlg.charAt(i + 1) == '2') {
if (fullAlg.charAt(i + 2) == ')') {
reversedAlg.append("2").append(fullAlg.charAt(i)).append(")");
} else {
reversedAlg.append("2").append(fullAlg.charAt(i));
}
} else if (fullAlg.charAt(i + 1) == ')') {
reversedAlg.append("\'").append(fullAlg.charAt(i)).append(")");
}
} else if (fullAlg.charAt(i) == ' ' || fullAlg.charAt(i) == '(') {
reversedAlg.append(fullAlg.charAt(i));
}
}
StringBuilder aux = new StringBuilder(reversedAlg.toString()).reverse();
for (int i = 0; i < aux.length(); i++) {
if (aux.charAt(i) == '(') {
aux.setCharAt(i, ')');
} else if (aux.charAt(i) == ')') {
aux.setCharAt(i, '(');
}
}
algTV.setText(aux);
}

Switch statements gets ignored after my if-else statements

//Scanner
Scanner scan = new Scanner(System.in);
//Variables
double bmi; // Body Mass Index
double weight; // Weight in kilograms
double height; // Height in meters
String[] classification = {"Underweight", "Normal", "Overweight", "Obese"};
System.out.print("Your weight in KG \n");
weight = scan.nextDouble();
System.out.print("Enter height in meters: \n");
height = scan.nextDouble();
bmi = weight / (height * height);
if (bmi < 18.5) {
System.out.print("You're " + classification[0] + "\n");
} else if (bmi < 25) {
System.out.print("You're " + classification[1] + "\n");
} else if (bmi < 30) {
System.out.print("You're " + classification[2] + "\n");
} else {
System.out.print("You're " + classification[3] + "\n");
}
switch (Arrays.toString(classification)) {
case "Underweight":
System.out.println("Underweight");
break;
case "Normal":
System.out.println("Normal");
break;
case "Overweight":
System.out.println("A bit overweighted");
break;
case "Obese":
System.out.println("A bit obese");
break;
default:
System.out.println("Ok");
break;
}
}
output,, my switch statement does not work after the if-else statements. It ignores everything and jumps directly to the default in my switch. While my intentions are to follow up with some text after the if-else. So basically if my calculations show me i'm overweighted than my switch statement must now to jump to case "overweighted" and print out that piece of code.. What am I doing wrong?
The result of Arrays.toString(classification) which is [Underweight, Normal, Overweight, Obese] does not match any switch case.
The solution could be something like this:
String result = null;
if (bmi < 18.5) {
System.out.print("You're " + classification[0] + "\n");
result = classification[0];
} else if (bmi < 25) {
System.out.print("You're " + classification[1] + "\n");
result = classification[1];
} else if (bmi < 30) {
System.out.print("You're " + classification[2] + "\n");
result = classification[2];
} else {
System.out.print("You're " + classification[3] + "\n");
result = classification[3];
}
switch (result) {
case "Underweight":
System.out.println("Underweight");
break;
case "Normal":
System.out.println("Normal");
break;
case "Overweight":
System.out.println("A bit overweighted");
break;
case "Obese":
System.out.println("A bit obese");
break;
default:
System.out.println("Ok");
break;
}

While loop wont repeat itself

I need to let the user input an operand, input 2 integers, display the result, and repeat. It wont repeat and when you input an integer to continue, it terminates. Any help would be appreciated, Ive been stuck for a while now! Thanks.
package lab03;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
*/
public class Lab03 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int n, p, q = 1;
boolean run = true;
String operator;
while (run == true) {
operator = JOptionPane.showInputDialog("Enter one of + - * / ");
String trimOperator = operator.trim();
char m = trimOperator.charAt(0);
String firstOperand = JOptionPane
.showInputDialog("Enter first integer operand: ");
n = Integer.parseInt(firstOperand);
String secondOperand = JOptionPane
.showInputDialog("Enter second integer operand: ");
p = Integer.parseInt(secondOperand);
switch (m) {
case '+':
System.out.println(n + " plus " + p + " is " + (n + p));
run = false;
break;
case '-':
System.out.println(n + " minus " + p + " is " + (n - p));
run = false;
break;
case '*':
System.out
.println(n + " multiplied by " + p + " is " + (n * p));
run = false;
break;
case '/':
System.out.println(n + " divided by " + p + " is " + (n / p)
+ " with remainder " + (n % p));
run = false;
break;
default:
System.out.println("Invalid character");
run = false;
break;
}
String lastInteger = JOptionPane
.showInputDialog("Enter 0 to quit, or any other integer to continue. ");
q = Integer.parseInt(lastInteger);
System.out.println(q);
System.exit(0);
continue;
}
}
Sorry for lack of comments.

unreachable statement switch

I have a POS program that is not working it says switch(food) unreachable statement
import javax.swing.*;
import java.awt.*;
public class sari{
public static void One()
{
int choice=0,food=0,c=0,con,x=1,y=1,z=1,q=1,trans=0,price=0 ,qty,gtotal=0,ptotal=0,pay,change,total=0,ord;
String order="",bibilhin="",transaction="",A;
ImageIcon welcome = new ImageIcon("welcome.jpg");
ImageIcon chip = new ImageIcon("chip.jpg");
ImageIcon rc = new ImageIcon("rc.jpg");
ImageIcon stick = new ImageIcon("stick.jpg");
ImageIcon pancit = new ImageIcon("pancit.jpg");
ImageIcon jampong = new ImageIcon("jampong.jpg");
ImageIcon chups = new ImageIcon("chups.jpg");
ImageIcon egg = new ImageIcon("egg.jpg");
A=JOptionPane.showInputDialog("Enter your name:"); ImageIcon hansel = new ImageIcon("hansel.jpg");
JOptionPane.showMessageDialog(null,"Sir/Ma`am \n "+A+"\n Welcome\n to Mang Inasal\n Please Choose The\n product you want to buy","Welcome" ,JOptionPane.PLAIN_MESSAGE,welcome);
while(x==1)
{
c=Integer.parseInt(JOptionPane.showInputDialog(" Categories" + "\n" +"[1] Drinks" + "\n" + "[2] Foods"));
if(c==1)
{choice=Integer.parseInt(JOptionPane.showInputDialog("DRINKS" +"\n"
+ "[1] Lemonade" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
if(c==2)
food=Integer.parseInt(JOptionPane.showInputDialog("Food" +"\n"
+ "[1] L" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
}
switch(choice)
{
case 1:
price = 20;
bibilhin= " Lemonade";
break;
case 2:
price = 20;
bibilhin= "Coca Cola ";
break;
case 3:
price =820;
bibilhin = "Sprite";
break;
case 4:
price =205;
bibilhin= "Mountain dew";
break;
case 5:
price =20;
bibilhin= "Pepsi";
break;
case 6:
price =25;
bibilhin= "Cofee ";
break;
case 7:
price =25;
bibilhin= "Hot Choco";
break;
case 8:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 9:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
break;
switch(food)
{
case 11:
price = 20;
bibilhin= " Lemonade";
break;
case 12:
price = 20;
bibilhin= "Coca Cola ";
break;
case 13:
price =820;
bibilhin = "Sprite";
break;
case 14:
price =205;
bibilhin= "Mountain dew";
break;
case 15:
price =20;
bibilhin= "Pepsi";
break;
case 16:
price =25;
bibilhin= "Cofee ";
break;
case 17:
price =25;
bibilhin= "Hot Choco";
break;
case 18:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 19:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
continue;
}
}
}
You have an unconditional break right before the switch in question.
As an aside, I think this is the perfect time to learn about functions and how to use them to make code more modular.
comment the break statement
import javax.swing.;
import java.awt.;
public class Test{
public static void main(String[] args)
{
int choice=0,food=0,c=0,con,x=1,y=1,z=1,q=1,trans=0,price=0 ,qty,gtotal=0,ptotal=0,pay,change,total=0,ord;
String order="",bibilhin="",transaction="",A;
ImageIcon welcome = new ImageIcon("welcome.jpg");
ImageIcon chip = new ImageIcon("chip.jpg");
ImageIcon rc = new ImageIcon("rc.jpg");
ImageIcon stick = new ImageIcon("stick.jpg");
ImageIcon pancit = new ImageIcon("pancit.jpg");
ImageIcon jampong = new ImageIcon("jampong.jpg");
ImageIcon chups = new ImageIcon("chups.jpg");
ImageIcon egg = new ImageIcon("egg.jpg");
A=JOptionPane.showInputDialog("Enter your name:"); ImageIcon hansel = new ImageIcon("hansel.jpg");
JOptionPane.showMessageDialog(null,"Sir/Ma`am \n "+A+"\n Welcome\n to Mang Inasal\n Please Choose The\n product you want to buy","Welcome" ,JOptionPane.PLAIN_MESSAGE,welcome);
while(x==1)
{
c=Integer.parseInt(JOptionPane.showInputDialog(" Categories" + "\n" +"[1] Drinks" + "\n" + "[2] Foods"));
if(c==1)
{choice=Integer.parseInt(JOptionPane.showInputDialog("DRINKS" +"\n"
+ "[1] Lemonade" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
if(c==2)
food=Integer.parseInt(JOptionPane.showInputDialog("Food" +"\n"
+ "[1] L" + "\n"
+ "[2] Coca Cola" + "\n"
+ "[3] Sprite" + "\n"
+ "[4] Mountain Dew" + "\n"
+ "[5] Pepsi" + "\n"
+ "[6] Cofee" +"\n"
+ "[7] Hot Choco" + "\n"
+ "[8] Nestie Iced Tea" +"\n"
+ "[9] Exit" +"\n"
+ "Enter Your Choice:"));
}
switch(choice)
{
case 1:
price = 20;
bibilhin= " Lemonade";
break;
case 2:
price = 20;
bibilhin= "Coca Cola ";
break;
case 3:
price =820;
bibilhin = "Sprite";
break;
case 4:
price =205;
bibilhin= "Mountain dew";
break;
case 5:
price =20;
bibilhin= "Pepsi";
break;
case 6:
price =25;
bibilhin= "Cofee ";
break;
case 7:
price =25;
bibilhin= "Hot Choco";
break;
case 8:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 9:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
// break;
switch(food)
{
case 11:
price = 20;
bibilhin= " Lemonade";
break;
case 12:
price = 20;
bibilhin= "Coca Cola ";
break;
case 13:
price =820;
bibilhin = "Sprite";
break;
case 14:
price =205;
bibilhin= "Mountain dew";
break;
case 15:
price =20;
bibilhin= "Pepsi";
break;
case 16:
price =25;
bibilhin= "Cofee ";
break;
case 17:
price =25;
bibilhin= "Hot Choco";
break;
case 18:
price = 20;
bibilhin= "Nestie Ice tea";
break;
case 19:
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"You are about to exit!","Exit",JOptionPane.WARNING_MESSAGE);
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Are you sure you want to exit?\n[1] Yes\n[0] No"));
if(con==1)
System.exit(0);
else if(con==1)
{
JOptionPane.showMessageDialog(null,"THANK YOU!\nGood Bye!","Exit",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
con=1;
}
}while(con==1);
continue;
default:
JOptionPane.showMessageDialog(null,"Invalid Choice!","ERROR",JOptionPane.ERROR_MESSAGE);
}
do{//do1
qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity:"));
if (qty>0)
break;
else
{
JOptionPane.showMessageDialog(null,"Invalid Input!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(q==1);//end do1
total = price * qty;
ptotal = ptotal+total;
order = order +bibilhin+" "+qty+" "+price+"="+total+"\n";
do {//do2
con = Integer.parseInt(JOptionPane.showInputDialog("Continue?[1] yes [0] no"));
if(con==1)
{
break;
}
else if(con==0)
{
do{
pay = Integer.parseInt(JOptionPane.showInputDialog(order+"Total " +ptotal+"\nEnter Payment:"));
if(pay>=ptotal)
{
change = pay-ptotal;
JOptionPane.showMessageDialog(null," \t Mang Inasal"+
"\n\t 14 T molina st purok 6-B "+
"\n\t Alabang Muntinlupa City "+
"\nOperator: Micko Mendoza"+
"\n\t----------------------------------------------------------------"+
"\n\n\t "+order+"\nTotal "+ptotal+
"\nCash "+pay+
"\nChange "+change+
"\n----------------------------------------------------------------"+
"\n\n \t Thanks For buying!!!!!"+
"\n\t This Serve as an official reciept DTSN:41D983"+
"\n \t For Delivery Dial (519-6936)"+
"\n \t Feedbacks"+
"\n \t micko.mendoza#yahoo.com"
);
y=0;
z=0;
x=1;
gtotal = gtotal+ptotal;
trans++;
order="";
transaction = transaction+"Transaction "+ trans+ " "+ptotal+"\n";//No of transactions
ptotal = 0;
do{
con=Integer.parseInt(JOptionPane.showInputDialog("Next Customer?\n[1] Yes\n[0] No"));
if(con==1)
break;
else if(con==0)
{
JOptionPane.showMessageDialog(null,transaction+"Total sales: " + gtotal,"Transactions",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Choice!","Error",JOptionPane.ERROR_MESSAGE);
continue;
}
}while(con==1);
break;
}
else
{
JOptionPane.showMessageDialog(null,"Kulang pera mo");
continue;
}
}while(z==1);//do3
}
else
{
JOptionPane.showMessageDialog(null,"Intiger lang pwede","Continue",JOptionPane.ERROR_MESSAGE);
y=1;
continue;
}
} while(y==1);//do2
continue;
}
}
}

Categories