Input with spacing will show error - java

I have a problem with this java script if I enter the input with spacing cant work. without spacing no problem. I have try a lot of edit but still cannot solve this problem, I wrote getloan will show the result, but if I write
get loan with spacing will show error. what I should add on to solve this?
Scanner read = new Scanner(System.in);
{
System.out.println("Enter the phone number: ");
String telLetter = read.next();
telLetter = telLetter.toUpperCase();
String telNumber = " ";
int count = 0;
int i = 0;
while (count <7)
{
switch (telLetter.charAt(i))
{
case 'A':case 'B':case 'C':
telNumber += "2";
count++;
break;
case 'D':case 'E':case 'F':
telNumber += "3";
count++;
break;
case 'G':case 'H':case 'I':
telNumber += "4";
count++;
break;
case 'J':case 'K':case 'L':
telNumber += "5";
count++;
break;
case 'M':case 'N':case 'O':
telNumber += "6";
count++;
break;
case 'P':case 'R':case 'Q':case 'S':
telNumber += "7";
count++;
break;
case 'T':case 'U':case 'V':
telNumber += "8";
count++;
break;
case 'W':case 'X':case 'Y':case 'Z':
telNumber += "9";
count++;
break;
}
if (count == 3)
telNumber += "-";
i++;
}
System.out.println(telNumber);
}

It fails because Scanner.next() will give you get and not get loan and you have hardcoded your loop to process 7 valid letters. Scanner by default delimits on whitespace.

You should probably use nextLine() instead of next() if you want to delimit on the new line.

Related

Converting all letters in the phone number to digits

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

How do you place a class in the default package in netbeans for Mac?

My instructor requires us to take the package from our code and make it a default package. The only problem is he taught us how to do that through Windows and I have a MacBook so his way isn't working. I can't figure out how to do it. I've attached the code to the bottom in case that will help.
package romannumeralcalculator;
import java.util.*;
public class RomanNumeralCalculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int integer;
do {
System.out.print("Please enter an interger from 1 to 5999. Enter a negative number to exit. \n ->");
integer = input.nextInt();
} while (integer >= 6000);
while (integer == 0) {
System.out.println("");
break;
}
String results = "";
int ones = integer % 10;
int tens = (integer / 10) % 10;
int hundreds = (integer / 100) % 10;
int thousands = (integer / 1000) % 1000;
switch (thousands) {
case 1:
results += "M";
break;
case 2:
results += "MM";
break;
case 3:
results += "MMM";
break;
case 4:
results += "MMMM";
break;
case 5:
results += "MMMMM";
break;
default:
System.out.println("");
}
switch (hundreds) {
case 1:
results += "C";
break;
case 2:
results += "CC";
break;
case 3:
results += "CCC";
break;
case 4:
results += "CD";
break;
case 5:
results += "D";
break;
case 6:
results += "DC";
break;
case 7:
results += "DCC";
break;
case 8:
results += "DCCC";
break;
case 9:
results += "CM";
break;
default:
System.out.println("");
}
switch (tens) {
case 1:
results += "X";
break;
case 2:
results += "XX";
break;
case 3:
results += "XXX";
break;
case 4:
results += "XL";
break;
case 5:
results += "L";
break;
case 6:
results += "LX";
break;
case 7:
results += "LXX";
break;
case 8:
results += "LXXX";
break;
case 9:
results += "XC";
break;
default:
System.out.println("");
}
switch (ones) {
case 1:
results += "I";
break;
case 2:
results += "II";
break;
case 3:
results += "III";
break;
case 4:
results += "IV";
break;
case 5:
results += "V";
break;
case 6:
results += "VI";
break;
case 7:
results += "VII";
break;
case 8:
results += "VIII";
break;
case 9:
results += "IX";
break;
default:
System.out.println("");
}
System.out.println(results);
}
}
In the projects tab of Netbeans in the top-left:
Expand the tree for your Project.
Expand the Source Packages folder.
Expand the package with your java file.
Drag the java file from under the package to the Source Packages folder.
A dialog box will pop up with the title Move Class. On that dialog click the Refactor button.
This should be the same procedure in Windows. I am not sure why your professor told you something different.

String index out of range with word to phone number convertion

So i have created this code to convert words into phone numbers, but when i try to run this code with letters under 7 word it will display string index out of range. But 7 or more is fine. How do i fix this? If so how do i set the string range?
{
System.out.println("Enter a word to be converted: ");
String telLetter = console.next ();
telLetter = telLetter.toUpperCase();
String telNumber="7";
int count=0;
int i=0;
while(count <7)
{switch(telLetter.charAt(i))
{case 'A':case 'B':case 'C': case 'a': case 'b': case 'c':
telNumber += "2";
count++;
break;
case 'D':case 'E':case 'F': case 'd': case 'e': case 'f':
telNumber += "3";
count++;
break;
case 'G':case 'H':case 'I': case 'g': case 'h': case 'i':
telNumber += "4";
count++;
break;
case 'J':case 'K':case 'L': case 'j': case 'k': case 'l':
telNumber += "5";
count++;
break;
case 'M':case 'N':case 'O': case 'm': case 'n': case 'o':
telNumber += "6";
count++;
break;
case 'P':case 'R':case 'S': case 'p': case 'r': case 's':
telNumber += "7";
count++;
break;
case 'T':case 'U':case 'V': case 't': case 'u': case 'v':
telNumber += "8";
count++;
break;
case 'W':case 'X':case 'Y':case 'Z': case 'w': case 'x': case 'y': case 'z':
telNumber += "9";
count++;
break;
}
if( count==3) {
telNumber += "-";
}
i++;
}
System.out.println( telNumber );
}
}}
Fixes in code:
Use while(count < telLetter.length()) in place of while(count <7)...
telLetter.charAt(i) can be removed by (telLetter.charAt(count))... By doing this you don't need to create an extra variable int i = 0;... Its a good practice to keep variable minimum.
Use a scanner to get the input... Like.. Scanner sc = new Scanner(System.in); String telLetter = sc.next();...
After you used your resources do close them by using sc.close();....
Also i can see that you are appending 7 at the begining of every number... if that's a requirement then its ok.. other wise you can use... String telNumber="";
I would recommend using StringBuilder because in one object you can do it all.. While appending a character every time in string you are continuously creating a new string and giving it the reference of telNumber.
Also in your code either remove telLetter = telLetter.toUpperCase(); or remove the cases with lowercase alphabets.. because on making toUpperCase() you are just writing extra lines by writing cases for lowercase characters that are not needed...
System.out.println("Enter a word to be converted: ");
Scanner scan=new Scanner(System.in);
String telLetter = scan.next ();
int stringLength=telLetter.length();
telLetter = telLetter.toUpperCase();
String telNumber="7";
while(count <stringLength)
{
switch(telLetter.charAt(count))
Change your code like this.
But as per your code, the 7 is always prefixed in the converted phone number.
String telNumber=""; telNumber should be declared with empty string.
while(count <7)
Your code won't end until it has run through 7 characters. Try using while(count < telLetter.length())
Your while loop condition needs to check for the length of the telLetter string.
while (count <7 && count < telLetter.length())

Number to Word Conversion in Java

I have this homework assignment for this class I'm retaking, the problem I'm running into is that I'm over-thinking the solution. I have to create a program that converts a four digit number to words.
(Example: 1134 becomes "One One Three Four")
I have a basic code, but it's bulky and ugly. I'm also only allowed to use basic if and switch statements, we have to use a switch statement as well.
Am I over thinking this? I can't figure out how to make this code shorter and I only want to use one switch statement without a while loop. Is it even possible or is this as short as it gets.
Here's my code.
import java.util.Scanner;
public class NumberToWords {
public static void main(String[] args) {
//Set up scanner.
Scanner kb = new Scanner(System.in);
//Ask for a 4 digit integer.
System.out.println("Enter a 4 digit number.");
//Store 4 digit number into a variable
int number = kb.nextInt();
//Seperate number into digits.
int digit4 = number%10;
number = number/10;
int digit3 = number%10;
number = number/10;
int digit2 = number%10;
number = number/10;
int digit1 = number%10;
number = number/10;
//Set up a switch statement to read through the number.
switch (digit1)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit2)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit3)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit4)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
}
}
First, write a method to convert a single digit to a word. Something like,
private static String digitToWord(char ch) {
switch(ch) {
case '0': return "Zero";
case '1': return "One";
case '2': return "Two";
case '3': return "Three";
case '4': return "Four";
case '5': return "Five";
case '6': return "Six";
case '7': return "Seven";
case '8': return "Eight";
case '9': return "Nine";
}
return "Unknown (" + ch + ")";
}
Then you can get the String value of your int. And get the four characters from that String. Something like,
int number = kb.nextInt();
String str = String.format("%04d", number);
StringBuilder sb = new StringBuilder();
sb.append(digitToWord(str.charAt(0)).append(' ');
sb.append(digitToWord(str.charAt(1)).append(' ');
sb.append(digitToWord(str.charAt(2)).append(' ');
sb.append(digitToWord(str.charAt(3));
System.out.println(sb.toString());
Or,
String str = String.format("%04d", kb.nextInt());
System.out.printf("%s %s %s %s%n", digitToWord(str.charAt(0)),
digitToWord(str.charAt(1)), digitToWord(str.charAt(2)),
digitToWord(str.charAt(3)));
this might help
public class NumbersInWords {
public static void main(String[] args) {
String number = "153";
int numLength = number.length();
System.out.println(numLength);
String numberToWord = "";
for (int j = 0; j < numLength; j++) {
switch (number.charAt(j)) {
case '1': {
numberToWord = numberToWord + "one";
break;
}
case '2': {
numberToWord = numberToWord + "two";
break;
}
case '3': {
numberToWord = numberToWord + "three";
break;
}
case '4': {
numberToWord = numberToWord + "four";
break;
}
case '5': {
numberToWord = numberToWord + "five";
break;
}
case '6': {
numberToWord = numberToWord + "six";
break;
}
case '7': {
numberToWord = numberToWord + "seven";
break;
}
case '8': {
numberToWord = numberToWord + "eight";
break;
}
case '9': {
numberToWord = numberToWord + "nine";
break;
}
default: {
numberToWord = numberToWord + "zero";
}
}
}
System.out.println(numberToWord);
}
}
Yeah, you can simply do that operation in a for loop, executed 4 times. The division and mod is consistent at 10. Something like
For i = 0; i < 4; i++
Number/10%10
Condition to check number
Save number in array or print
Copy pasting code and names with numbers should be a red flag to use a loop (or something more is worng).
private static final String[] DIGIT_NAMES = new String[] {"Zero ", "One ", "Two ",
"Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = 0;
do {
// ask for a 4 digit integer
System.out.println("Enter a 4 digit number: ");
try {
number = input.nextInt();
} catch (InputMismatchException ignore) {
System.out.println("Recieved non integer input");
input.next(); // clear bad input
}
} while (number < 1000 || number > 9999);
String result = "";
while (number != 0) {
result = DIGIT_NAMES[number % 10] + result;
number = number / 10;
}
System.out.println(result);
input.close();
}

Changing from an input to a Scanner

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

Categories