Letters to numbers java

Phone Numbers from letters to digits

Hello, I have to write a program that prompts the user to enter a phone number expressed in letters and outputs the corresponding phone numbers in digits. The user can use lowercase and uppercase letters, as well as spaces between words. And I am supposed to use the charAt method to extract each character. I figured I can use each charAt position in a switch and check each letter from there, but the coding get’s to long. But I wanted to ask if there is a better way to code this, using a loop maybe to increment each character and just one switch statement. This is what I have so far. Thank you.

import java.util.*; public class phoneDigits < static Scanner console = new Scanner(System.in); public static void main(String[] args) < String str; char letter; System.out.println("Enter phone number expressed in letters: "); str = console.next(); System.out.println(); if ((letter >= 'A' || letter >= 'a') && (letter switch (str.charAt(1)) < case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': System.out.print("2"); break; case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': System.out.print("3"); break; case 'G': case 'g': case 'H': case 'h': case 'I': case 'i': System.out.print("4"); break; case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': System.out.print("5"); break; case 'M': case 'm': case 'N': case 'n': case 'O': case 'o': System.out.print("6"); break; case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': System.out.print("7"); break; case 'T': case 't': case 'U': case 'u': case 'V': case 'v': System.out.print("8"); break; case 'W': case 'w': case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z': System.out.print("9"); break; default: System.out.print(" "); >switch (str.charAt(2)) < case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': System.out.print("2"); break; case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': System.out.print("3"); break; case 'G': case 'g': case 'H': case 'h': case 'I': case 'i': System.out.print("4"); break; case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': System.out.print("5"); break; case 'M': case 'm': case 'N': case 'n': case 'O': case 'o': System.out.print("6"); break; case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': System.out.print("7"); break; case 'T': case 't': case 'U': case 'u': case 'V': case 'v': System.out.print("8"); break; case 'W': case 'w': case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z': System.out.print("9"); break; default: System.out.print(" "); >> else System.out.println("Invalid input"); > > 

Источник

Convert Roman letters to Integer :

2. Using traditional for-loop and if-else construct :

ConvertRomanLettersToInteger.java

package in.bench.resources.arrays.find.number; import java.util.LinkedHashMap; import java.util.Map; public class ConvertRomanLettersToInteger < // main() method public static void main(String[] args) < // test Roman letters System.out.println("Integer/Number for Roman letter IV :- " + getIntegerForRomanLetter("IV")); System.out.println("Integer/Number for Roman letter XVII :- " + getIntegerForRomanLetter("XVII")); System.out.println("Integer/Number for Roman letter LIX :- " + getIntegerForRomanLetter("LIX")); System.out.println("Integer/Number for Roman letter CLVIII :- " + getIntegerForRomanLetter("CLVIII")); System.out.println("Integer/Number for Roman letter DI :- " + getIntegerForRomanLetter("DI")); System.out.println("Integer/Number for Roman letter MDCCCCXXXXVII :- " + getIntegerForRomanLetter("MDCCCCXXXXVII")); System.out.print("Integer/Number for Roman letter MMXXII :- " + getIntegerForRomanLetter("MMXXII")); >/** * 1. This method converts Roman letter to Integer/Number * * @param str * @return */ private static int getIntegerForRomanLetter(String str) < // local variable int number = 0; // get Roman to Integer Map Mapmap = romanToIntegerMap(); for (int i = 0; i < str.length(); i++) < if (i+1 == str.length() || map.get(str.charAt(i)) >= map.get(str.charAt(i + 1))) < number += map.get(str.charAt(i)); >else < number -= map.get(str.charAt(i)); >> // return converted integer/number return number; > /** * 2. This method returns Roman to Integer conversion * * @return */ private static Map romanToIntegerMap() < // create Map to store Roman letter to Integer Mapmap = new LinkedHashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); // return map return map; > >

Output:

Integer/Number for Roman letter IV :- 4 Integer/Number for Roman letter XVII :- 17 Integer/Number for Roman letter LIX :- 59 Integer/Number for Roman letter CLVIII :- 158 Integer/Number for Roman letter DI :- 501 Integer/Number for Roman letter MDCCCCXXXXVII :- 1947 Integer/Number for Roman letter MMXXII :- 2022
  • Java – To print first N natural numbers
  • Java – Swapping two numbers without temporary variable
  • Java – Swapping two numbers using third or temporary variable
  • Java – Check whether the given number is Armstrong number or Not ?
  • Java – Check whether number is Positive or Negative or Zero ?
  • Java – Check whether number is Even or Odd ?
  • Java – How to Reverse a Number in different ways ?
  • Java – Check whether number is Prime or Not ?
  • Java – Print Prime numbers between specified range or interval
  • Java – How to find/remove first and last digit of a number ?
  • Java – How to generate Fibonacci numbers using Stream ?
  • Java – How to convert Roman letter/numbers to Integer ?
  • Java – How to convert Celsius to Fahrenheit and vice-versa ?
Читайте также:  Python serialize with json

References :

Happy Coding !!
Happy Learning !!

Источник

Converting Letters to Numbers

What your doing is creating an array of alphabets and then using the callback in function and returning the respective indexes of the letter as the indices start from Question: I’m a beginner in Java and I’m trying to find out how to create a segment of code that can allow a user to enter a number between 1 and 26, and have the corresponding number of sequential letters to appear? Question: I’m trying to figure out the way to convert letter into number and split it according to n-digits.

Converting Letters to Numbers

Let’s say I have a program which converts letters to numbers such that:

  1. How can I convert abcd to 1234 efficiently
  2. and how can I extract every individual char from the token

By the way, this is not homework. (this is for fun)

This is what I have so far:

String s = "abcd"; StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) < sb.append((char)(c - 'a' + 1)); >// provided your string contains only lower case non-unicode (ASCII) characters. 

Have a map defined with keys as a,b,c etc with values 1,2,3 etc. Whenever you receive a token take that from the map and print.

Uppercase the letter, convert it to ASCII, subtract ‘A’, then add 1. If you’re handling multi-character inputs, then iterate over the string. As you calculate as per the previous recommendation, multiply the previous sum by 10, then add the new value.

Derp, I read the whole question wrong. My bad.

What you could do, is that you have a conversion algorithm I suppose. Each letter in the alphabet could have a value from the alphabet.

Then all you need to do, is match the letter you find, with a letter from you a string array, get it’s index, and add 1 to it. Then you got the value. If that’s how you wanna play.

Читайте также:  But got java lang class

Java-Android How to convert letters in a string to, An example of the numerical assignment for alphabetic characters is shown below: 1 = A I J Q Y 2 = B K R 3 = C G L S 4 = D M T 5 = E H N X 6 = U V W …

Java convert letter to number then put all values into array

I’m trying to figure out the way to convert letter into number and split it according to n-digits.

For example, I have words: TOMORROW BEGIN

Then, I convert it to number like in ASCII. So, the converting number must be: 8479777982827987326669717378

After that, all number will be converted to n-digits and put it in one dimensional array.

Let’s say the number split to 3 digits each block. Result must be: 847 977 798 282 798 732 666 971 737 8

They’re all in array: arr[0] = 847, arr[1] = 977, arr[2] = 798. arr[n]

I already tried to solve it in java. But so far, I can just converting the string to number.

Here is part of code I’ve tried:

 String words = "TOMORROW BEGIN"; int sa; char c; for(int i = 0; i

Well, it successfully converted to number: 8479777982827987326669717378

But, I confuse how to split the number into blocks of n-digits (let’s say 3 digits per block) then put the value of all blocks into array.

What must I do to solve this?

You can create such method:

public static int[] splitString(String str, int length) < int size=str.length()/length; if( str.length() % length != 0) size++; int[] arr = new int[size]; int a=0; for (int i= 0; i < str.length(); i+=length) < if(i+length < str.length()) arr[a++]=Integer.parseInt(str.substring(i, i+length)); else arr[a++]=Integer.parseInt(str.substring(i, str.length())); >return arr; > 

At your main method you can just call:

String str = "8479777982827987326669717378"; System.out.println(Arrays.toString(splitString(str,3))); 
[847, 977, 798, 282, 798, 732, 666, 971, 737, 8] 

You can even specify to store 2 digit int into array

System.out.println(Arrays.toString(splitString(str, 2))); 
[84, 79, 77, 79, 82, 82, 79, 87, 32, 66, 69, 71, 73, 78] 

One solution would be to take substring on every three characters and convert each substring back using Integer.parseInt() .

You can use substring method for splitting a string

public static void main(String[] args) < String words = "TOMORROW BEGIN"; StringBuilder builder = new StringBuilder(); for (int idx = 0; idx < words.length(); idx++) < builder.append((int) words.charAt(idx)); >int[] ints = new int[(builder.length() + 2) / 3]; for (int idx = 0; idx < ints.length; idx++) < int from = idx * 3; int to = Math.min(from + 3, builder.length()); ints[idx] = Integer.parseInt(builder.substring(from, to)); >System.out.println(builder); System.out.println(Arrays.toString(ints)); > 
8479777982827987326669717378 [847, 977, 798, 282, 798, 732, 666, 971, 737, 8] 

Convert letter to number in JavaScript, As you can see, the amount of letters is the same, but the base 36 integer is way bigger, in other words, base 36 can store bigger numbers in the …

Convert letter to number in JavaScript

I would like to know how to convert each alphabetic character entered to a number.

In C I had managed to do something similar, by taking a character input and displaying it as an integer. But I’m not sure how I would do this in JavaScript.

If I get you right, the other answers are over complicated:

parseInt('a', 36) - 9; // 1 parseInt('z', 36) - 9; // 26 parseInt('A', 36) - 9; // 1 parseInt('Z', 36) - 9; // 26 

Now, to answer the question you asked in the comments:

function sumChars(s) < var i, n = s.length, acc = 0; for (i = 0; i < n; i++) < acc += parseInt(s[i], 36) - 9; >return acc; > console.log(sumChars("az"))

However, this notation of an integer is space consuming compared to the positional notation. Compare «baz» in both notations:

sumChars("baz") // 29 parseInt("baz", 36) // 14651 

As you can see, the amount of letters is the same, but the base 36 integer is way bigger, in other words, base 36 can store bigger numbers in the same space. Moreover, converting a base 10 integer into base 36 integer is trivial in JavaScript:

Читайте также:  Python последовательность инициализации переменной

Finally, be careful when you want to store the values. Although it sounds counterintuitive, base 2 is more compact than base 36. Indeed, one letter occupies at least 8 bits in memory:

(35).toString(2).length // 6 bits long (35).toString(36).length * 8 // 8 bits long 

Therefore I recommend to use «true» integers for storage, it’s easy to get back to base 36 anyway.

var alphabet = ["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"]; var letter = "h"; var letterPosition = alphabet.indexOf(letter)+1; 

Possibility to calculate the letters inside a string, aa=2, ab=3 etc.

function str_split(string, split_length) < // discuss at: http://phpjs.org/functions/str_split/ // original by: Martijn Wieringa // improved by: Brett Zamir (http://brett-zamir.me) // bugfixed by: Onno Marsman // revised by: Theriault // revised by: Rafał Kukawski (http://blog.kukawski.pl/) // input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/) // example 1: str_split('Hello Friend', 3); // returns 1: ['Hel', 'lo ', 'Fri', 'end'] if (split_length == null) < split_length = 1; >if (string == null || split_length < 1) < return false; >string += ''; var chunks = [], pos = 0, len = string.length; while (pos < len) < chunks.push(string.slice(pos, pos += split_length)); >return chunks; > function count(string) < var alphabet = ["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"]; var splitted_string = str_split(string); var count = 0; for (i = 0; i < splitted_string.length; i++) < var letterPosition = alphabet.indexOf(splitted_string[i])+1; count = count + letterPosition; >return count; > console.log(count("az")); // returns 27 in the console 

In JavaScript characters are not a single byte datatype, so if you want to mimick the workings of C, you need to create a mapping by yourself.

For example using a simple object as a map:

This way var number = charachters[‘a’]; will set number to 1 . The others have provided shorted methods, which are most likely more feasible, this one is mostly aimed for easy understanding.

You could do it like this

function convertToNumbers(str)< var arr = "abcdefghijklmnopqrstuvwxyz".split(""); return str.replace(/[a-z]/ig, function(m)< return arr.indexOf(m.toLowerCase()) + 1 >); > 

What your doing is creating an array of alphabets and then using the callback in String.replace function and returning the respective indexes of the letter +1 as the indices start from 0

Representing letters as numbers in java, 1. In java (and most other language) characters are actually represented as numbers. Google for ‘ascii table’, and you’ll find out lowercase a is …

Java: How to print corresponding alphabets till a number entered by user?

I’m a beginner in Java and I’m trying to find out how to create a segment of code that can allow a user to enter a number between 1 and 26, and have the corresponding number of sequential letters to appear?

For example, if the user enters 3 then the computer would output a, b, c

Update: I wrote the following code but there is an error message stating that the i in the integer conversion part is a duplicate of a local variable?

In another method, the user inputs the number between 1 and 26 and I’m reading that input as the String variable «num».

public String getChar (int i) < String num;String text = mini1Num.getText();Integer i = Integer.valueOf(text);return i >0 && i

This gives you what you need.

EDIT
The error in your code lies in the return statement.

The value of (i + ‘A’ -1) is of type char . So the type casting basically takes the form of (char) char instead of (char) int , which is problematic.

Java Program For Converting Roman Numerals To, Algorithm to convert Roman Numerals to Integer Number: Split the Roman Numeral string into Roman Symbols (character). Convert each symbol of …

Источник

Оцените статью