I was able to get invalid major when I put a letter that is not listed major, but if I put t2, I would only get invalid major and not (invalid major, sophomore). Can someone detect the code and tell me where I went wrong.
// Enter two characters
System.out.print("Enter two characters: ");
String status = in.next();
char major = Character.toUpperCase(status.charAt(0));
char year = status.charAt(1);
String courseName = "";
String yearName = "";
// majors
if (major == 'B' || major == 'I' || major == 'C')
{
switch(major)
{
case 'B':
courseName = "Biology"; break;
case 'C':
courseName = "Computer Science"; break;
case 'I':
courseName = "Information Technology"; break;
default:System.out.println("Invaild major"); break;
}
// year
switch(year)
{
case '1':
yearName = "Freshman"; break;
case '2':
yearName = "Sophmore"; break;
case '3':
yearName = "Junior"; break;
case '4':
yearName = "Senior"; break;
default: System.out.println("Invalid year status"); break;
}
System.out.printf("%s %s%n", courseName, yearName);
}
else{
System.out.printf("Invalid input.%n");
}
}
}
Remove:
if (major == 'B' || major == 'I' || major == 'C')
{
and
else{
System.out.printf("Invalid input.%n");
}
Your 'if statement' is preventing you from getting the desired output.
Related
The program ask for a month and it could be a string or int. In the isDigitsOrSpecial method, it works and it has the same format in my method isString. The difference is that when I want to enter the month in a string way (ex.january), it will ask me twice. So, I don't know what to do. I tried a lot of ways but it doesn't work. Do you have any suggestions?
Here's my full code. You can try to run it, and see the problem where you have to input twice the name of the month in a string way.
I would really appreciate any of your suggestions.
package Electronic_payment_process;
import java.util.InputMismatchException;
import java.util.Scanner;
public class practice {
static String s;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float current = 0, recent = 0, difference, multiply;
String month, recents, currents = null;
System.out.println("The month could be a number or a name.");
System.out.println("Example: (01-12) or (JAN – dec)");
// for the validation of due month user’s input
do {
System.out.print("\nEnter a month: ");
month = scan.next();
if (isDigitsOrSpecial(month)) {
System.out.print("proceed");
break;
} else if (isString(month)) {
System.out.print("proceed");
break;
}
} while (true);
// for the validation of current meter reading
do {
System.out.print("\nEnter current reading: ");
try {
current = scan.nextFloat();
System.out.println("proceed");
currents = String.format("%.2f", current);
if (current <= 0) {
System.out.println("Invalid input");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (current <= 0);
// for the validation of recent meter reading
do {
System.out.print("Enter recent reading: ");
try {
recent = scan.nextFloat();
if (recent < current) {
System.out.println("proceed");
recents = String.format("%.2f", recent);
break;
} else {
System.out.println("recent must be less than current");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (true);
difference = current - recent;
multiply = difference * 50;
System.out.println("====================================================================================");
System.out.println("MONTH " + " RECENT " + "CURRENT " + "TOTAL USAGE " + "Price per unit " + "TOTAL AMOUNT ");
System.out.println((s + (" ") + recents + (" kW") + (" ") + currents + (" kW") + (" ") + difference + (" ") + ("50php") + (" ") + multiply));
}
public static boolean isDigitsOrSpecial(String month) {
Scanner scan = new Scanner(System.in);
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
s = Integer.toString(we);
if (null == month) {
s = scan.nextLine();
} else switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
}
return true;
}
public static boolean isString(String month) {
Scanner scan = new Scanner(System.in);
if (null != month) {
char[] chars = month.toCharArray();
s = scan.nextLine();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
} else if (month.startsWith("jan") || month.startsWith("JAN") || month.startsWith("Jan")) {
s = "January";
}
return true;
}
}
I see we have added additional scanner statements inside isDigit or isString methods. I have removed them and it looks good to me.
public static boolean isDigitsOrSpecial(String month) {
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
return false;
}
return true;
}
public static boolean isString(String month)
{
if (null != month) {
char[] chars = month.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
}
return true;
}
Im trying to replace each letter with a digit using the international standard letter/number mapping. I got my output to run correctly however, how do get the dashes in the phone number to appear automatically in the output? For example, if I enter 1800Flowers it prints out as 18003569377. How do I get it to print out as 1-800-3569377 without using regular expressions?
import java.util.Scanner;
public class PhoneKeypad {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//while loop keeps the program running until the user enters quit
while (true) {
System.out.println("\nEnter a phone number or quit to exit:");
String phoneNumber = input.next();
if (phoneNumber.equalsIgnoreCase("quit")) {
System.out.print("\nProgrammed by me");
return;
}
//checks if the phone number entered is at least 8 digits
if (phoneNumber.length() < 8) {
System.out.println("Invalid Phone Number");
} else {
System.out.println(getNumber(phoneNumber));
}
}
}
//method converts all letters in the phone number to digits
public static String getNumber(String phoneNumber) {
int keypadNum = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
char letter = phoneNumber.charAt(i);
if (Character.isAlphabetic(letter)) {
letter = Character.toUpperCase(letter);
switch (letter) {
case 'A':
case 'B':
case 'C':
keypadNum = 2;
break;
case 'D':
case 'E':
case 'F':
keypadNum = 3;
break;
case 'G':
case 'H':
case 'I':
keypadNum = 4;
break;
case 'J':
case 'K':
case 'L':
keypadNum = 5;
break;
case 'M':
case 'N':
case 'O':
keypadNum = 6;
break;
case 'P':
case 'Q':
case 'R':
case 'S':
keypadNum = 7;
break;
case 'T':
case 'U':
case 'V':
keypadNum = 8;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
keypadNum = 9;
break;
default:
System.out.println("Invalid phone number");
}
phoneNumber = phoneNumber.substring(0, i) + keypadNum + phoneNumber.substring(i + 1);
}
}
return phoneNumber;
}
}
Expected Output:
You could use a regular expression with String.replaceAll. Remove the leading one, group the first three digits, the second three digits and the final group of digits. Something like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return phoneNumber.replaceAll("(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
or
public static String formatNumber(String phoneNumber) {
return phoneNumber.replaceAll("1(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
And then call it like
System.out.println(formatNumber(getNumber(phoneNumber)));
I ran it with 1800flowers and got (as expected)
1-800-356-9377
or without regular expressions like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return "1-".concat(phoneNumber.substring(0, 3)) //
.concat("-").concat(phoneNumber.substring(3, 6)) //
.concat("-").concat(phoneNumber.substring(6));
}
Before calling formatNumber, you can remove the dashes to normalize it with something like
public static String removeDashes(String phoneNumber) {
StringBuilder sb = new StringBuilder();
for (char ch : phoneNumber.toCharArray()) {
if (ch != '-') {
sb.append(ch);
}
}
return sb.toString();
}
Then
System.out.println(formatNumber(removeDashes(getNumber(phoneNumber))));
I have this program which can make some singular nouns plural (I know I'm missing a lot, but that's aside the point). When I enter in a word such as "man-of-war" it returns as "mans-of-war" instead of "men-of-war". How do I fix this? My code can already make man to men, just not in the case I mentioned. Also for this program every compound word will have the dash, it is simply for practice.
public class LanguageUtils {
static boolean checkException(String noun){
String[] exceptions = {"fish", "fox", "deer", "moose", "sheep", "cattle","pants","scissors"};
for(int i=0;i<exceptions.length;i++) {
if(exceptions[i].equals(noun))
return true;
}
return false;
}
static boolean EnglishConsonant(char ch) {
switch (Character.toLowerCase(ch)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return false;
default:
return true;
}
}
static String makePlural (String noun){
String pluralWord = "";
int length = noun.length();
String strippedWord = noun.substring(0, noun.length()-1);
char lastLetter = noun.charAt(noun.length()-1);
if(noun.contains("-")){
String nounsaver = noun.substring(noun.indexOf('-'), noun.length());
pluralWord = noun.substring(0,noun.indexOf('-')) + "s" + nounsaver;
}
else{
switch (lastLetter){
case 's':
case 'x':
case 'z':
if(noun.equals("ox")){
pluralWord = noun + "en";
break;
}
else{
pluralWord = noun + "es";
break;
}
case 'o':
if(EnglishConsonant(noun.charAt(noun.length()-2))){
pluralWord = strippedWord + "oes";
break;
}
case 'e':
char f = noun.charAt(noun.length()-2);
String prec = noun.substring(0, noun.length()-2);
if(f == 'f'){
pluralWord = prec + "ves";
break;
}
if(noun.equals("goose")){
pluralWord = "geese";
break;
}
else{
pluralWord = noun + "s";
break;
}
case 'h':
if ((noun.charAt(noun.length()-2)== 'c') || (noun.charAt(noun.length()-2)== 's')) {
pluralWord = noun + "es";
break;
}
case 'f':
if (EnglishConsonant(noun.charAt(noun.length()-2))) {
pluralWord = strippedWord + "ves";
break;
}
case 'y':
if (EnglishConsonant(noun.charAt(noun.length()-2))) {
pluralWord = strippedWord + "ies";
break;
}
default:
if(noun.equals("foot")){
pluralWord = "feet";
break;
}
if(noun.endsWith("man")){
pluralWord = noun.substring(0, noun.length()-3)+"men";
break;
}
else{
pluralWord = noun + "s";
break;
}
}
}
if (length == 1){
pluralWord = noun + "'s";
}
if(checkException(noun)){
pluralWord = noun;
}
return pluralWord;
}
}
When dealing with a compound word, if you need to pluralize a part, call a function designed to do just that: makePlural.
If you have - then break the words and call the makePlural for those words again.
You can use String#replace:
if (noun.contains("man")) {
pluralWord = noun.replace("man", "men");
break;
}
I have a code that has 4 cases and I am trying to break the loop and if the 'f' case is chosen. and then choose from that case. When i try to do the if statement with the break over 30 errors but when I take it away the code is fine.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
}
if (case == 'f')
{
break;
}
}
You would use a Java label (see this code example named BreakWithLabelDemo.java) to tell your code where to break.
myloop:
while ( true ){
switch( choice ){
case 'f':
friendsList();
break myloop;
}
}
For your implementation, it would make sense to break on a specific case before even entering the switch statement. For example:
char choice = one.charAt(0);
if (choice == 'f') break;
switch(choice)
This seems to be a pretty simple way to exit the while loop without conflicting with the break statements of the switch statement.
Or if you still need to call the friendsList method when choice is 'f' you can move that if statement to after the switch statement.
Note: With this you should also remove the if statement at the bottom of your code example.
if (case == 'f')
What is case in this statement? You should replace that with choice.
if (choice == 'f')
you need to put if inside while loop.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
if (choice == 'f')
{
break;
}
}
The if statement should be moved inside of the while loop to be effective, and case inside the if statement should be changed to choice.
so
While(yea==true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
if(choice == 'F')
{
break;
}
switch(choice)
{
//cases
}
}
I am trying to change this from an input box into a Scanner class, but i am having trouble doing so.
Its a program that takes words and makes them into a phone number here is the code that does so. Any help would be greatly appreciated and if there is something that i can do in return i would gladly do so.
// declare imports
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.*;
public class Telephone {
public static void main(String[] args) {
// ask for the phone number (in letters)
char letter;
String inputMessage = "Please enter the number in Letters " + "or enter '#' to stop the program ";
String inputString = JOptionPane.showInputDialog(inputMessage);
String outputString = "";
String outputMessage = "";
int digit = 0;
int x = 0;
for (int i = 0; i < inputString.length(); i++)
System.out.print(inputString.charAt(x)); {
while (inputString.charAt(x) != '#') {
letter = Character.toUpperCase(inputString.charAt(x));
x++;
// make sure its not a number
if (letter >= 'a' && letter <= 'z') if (letter >= 'A' && letter <= 'Z') {
digit++;
switch (letter) {
case 'A':
case 'B':
case 'C':
outputString += "2";
break;
case 'D':
case 'E':
case 'F':
outputString += "3";
break;
case 'G':
case 'H':
case 'I':
outputString += "4";
break;
case 'J':
case 'K':
case 'L':
outputString += "5";
break;
case 'M':
case 'N':
case 'O':
outputString += "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
outputString += "7";
break;
case 'T':
case 'U':
case 'V':
outputString += "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
outputString += "9";
}
if (digit == 7) {
break;
}
if (digit == 3) {
outputString += "-";
}
}
inputMessage = "Enter another set of telephone letters";
}
JOptionPane.showMessageDialog(null, outputString, "Telephone Program", JOptionPane.PLAIN_MESSAGE);
}
Modify the line where you show the JOptionPane as follows,
//String inputString = JOptionPane.showInputDialog(inputMessage);
System.out.println(inputMessage);
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
so you could do the following,
package test;
import java.util.Scanner;
public class Telephone {
public static void main(String[] args) {
// ask for the phone number (in letters)
char letter;
String inputMessage = "Please enter the number in Letters " + "or enter '#' to stop the program ";
// String inputString = JOptionPane.showInputDialog(inputMessage);
System.out.println(inputMessage);
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
String outputString = "";
String outputMessage = "";
int digit = 0;
int x = 0;
for (int i = 0; i < inputString.length(); i++) {
System.out.print(inputString.charAt(x));
}
while (inputString != null && inputString.trim().length() > 0 && inputString.charAt(x) != '#') {
letter = Character.toUpperCase(inputString.charAt(x));
x++;
// make sure its not a number
// if (letter >= 'a' && letter <= 'z') {
if (x >= inputString.length()) {
x = 0;
System.out.println("\n" + outputString);
// JOptionPane.showMessageDialog(null, outputString, "Telephone Program", JOptionPane.PLAIN_MESSAGE);
// inputString = JOptionPane.showInputDialog(inputMessage);
System.out.println(inputMessage);
inputString = sc.nextLine();
} else if (letter >= 'A' && letter <= 'Z') {
digit++;
switch (letter) {
case 'A':
case 'B':
case 'C':
outputString += "2";
break;
case 'D':
case 'E':
case 'F':
outputString += "3";
break;
case 'G':
case 'H':
case 'I':
outputString += "4";
break;
case 'J':
case 'K':
case 'L':
outputString += "5";
break;
case 'M':
case 'N':
case 'O':
outputString += "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
outputString += "7";
break;
case 'T':
case 'U':
case 'V':
outputString += "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
outputString += "9";
}
if (digit == 7) {
break;
}
if (digit == 3) {
outputString += "-";
}
}
// }
inputMessage = "Enter another set of telephone letters";
}
System.out.println("\n" + outputString);
// JOptionPane.showMessageDialog(null, outputString, "Telephone Program", JOptionPane.PLAIN_MESSAGE);
}
}