I'm working on a program and I'm stuck. This particular program is supposed to prompt the user to input either an uppercase or lowercase Y to process a phone number, they are then prompted to enter the character representation of a phone number (like CALL HOME would be 225-5466), this repeats until the user enters something other than the letter Y. All of the words entered are to be stored into a single array. The program is then to convert these words in the array to actual phone numbers. I'm kind of confused as to how to set this up. Here is what I have so far.
import java.util.*;
public class Program1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String begin;
int phoneNumber = number.convertNum();
System.out.println("Please enter an uppercase or lowercase Y when you are ready to enter a telephone number: ");
begin = input.next();
while (begin.equals("y") || begin.equals("Y")) {
System.out.println("Please enter a telephone number expressed in letters: ");
String letters = input.next();
char[] phoneArray = letters.toCharArray();
System.out.println("Please enter an uppercase or lowercase Y when you are ready to enter a telephone number: ");
begin = input.next();
}
System.out.println("Here is the numeric representation of the phone number(s) you entered");
}
public static int convertNum(char[] phoneArray) {
return number;
}
}
I realize that the second method doesn't have anything to return yet, I just wanted to put that in there while I was doing things that I actually know how to do ha. The convertNum() method is supposed to be the method with which the array of characters is converted to phone numbers.
I'm still trying to think my way through this. I would think it'd be easier to store the inputs from the user as individual letters rather than words for the sake of converting to phone numbers.
Also, we are only supposed to recognize the first 7 letters of each word that is entered, like the CALL HOME example, there are 8 letters but it's still a seven digit phone number, so I'm not sure how that would work.
Also, when printing the phone numbers after they've been converted, we're supposed to print the hyphen after the third number, I have no clue how that would be done from an array.
I was actually feeling pretty good about this program until I reached this point ha. Any help would be greatly appreciated.
To translate a character to it's proper number, you can use a map, where the key is a character, and the value is the digit (in string form) that it represents.
Map<Character,String> charToPhoneDigitMap = new HashMap<Character,String>();
charToPhoneDigitMap.put('A', "2");
charToPhoneDigitMap.put('B', "2");
charToPhoneDigitMap.put('C', "2");
charToPhoneDigitMap.put('D', "3");
...
charToPhoneDigitMap.put('W', "9");
charToPhoneDigitMap.put('X', "9");
charToPhoneDigitMap.put('Y', "9");
charToPhoneDigitMap.put('Z', null);
So, for each character in the input string, ignoring any spaces and dashes, get it's digit:
String digitStr = charToPhoneDigitMap.get(inputChar);
if(digitStr == null) {
throw new IllegalArgumentException("'" + inputChar + "' has no corresponding phone number digit.");
}
phoneNumString += digitStr;
When the length of phoneNumString reaches 7, stop.
As far as displaying the dash: Don't store the dash, just store the raw digits.
Create a getPhoneNumberWithDash(raw_phoneNumStr) function, that returns it with the dash in the right place.
Now, if you also want to store the letter-representation, then you might want an array of a PhoneNumbers, instead of just a string-array containing only the raw phone numbers (seven digits each):
public class PhoneNumber {
private final String digits;
private final String letters;
public PhoneNumber(String digits, String letters) {
this.digits = digits;
this.letters = letters;
}
public String getLetters() {
return letters;
}
String getDigits() {
return digits;
}
}
A better approach to this would be to make a class called PhoneNumber for example :
public class PhoneNumber {
String name; //the representation like "Call Home"
String number;//the actual phone number like "225-5466"
//constructor ...
}
and then store create instances of PhoneNumber and store them in a List or ArrayList
public static void main(String args[]){
ArrayList<PhoneNumber> numbersList = new ArrayList();
String name;
String number;
Scanner input = new Scanner(System.in);
System.out.println("input number representation");
name=input.nextLine();
System.out.println("input number ");
number=input.nextLine();
numbersList.add(new PhoneNumber(name,number));
System.out.println(numbersList.get(0).name+" represents :"+numbersList.get(0).number);
}
Related
I want the user to input a String, lets say his or her name. The name can be Jessica or Steve. I want the program to recognize the string but only output the first three letters. It can really be any number of letters I decide I want to output (in this case 3), and yes, I have tried
charAt();
However, I do not want to hard code a string in the program, I want a user input. So it throws me an error. The code below is what I have.
public static void main(String args[]){
Scanner Name = new Scanner(System.in);
System.out.print("Insert Name here ");
System.out.print(Name.nextLine());
System.out.println();
for(int i=0; i<=2; i++){
System.out.println(Name.next(i));
}
}
the error occurs at
System.out.println(Name.next(i)); it underlines the .next area and it gives me an error that states,
"The Method next(String) in the type Scanner is not applicable for arguments (int)"
Now I know my output is supposed to be a of a string type for every iteration it should be a int, such that 0 is the first index of the string 1 should be the second and 2 should be the third index, but its a char creating a string and I get confused.
System.out.println("Enter string");
Scanner name = new Scanner(System.in);
String str= name.next();
System.out.println("Enter number of chars to be displayed");
Scanner chars = new Scanner(System.in);
int a = chars.nextInt();
System.out.println(str.substring(0, Math.min(str.length(), a)));
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.
Instead, use code point integer numbers to work with individual characters.
Call String#codePoints to get an IntStream of the code point for each character.
Truncate the stream by calling limit while passing the number of characters you want.
Build a new String with resulting text by passing references to methods found on the StringBuilder class.
int limit = 3 ; // How many characters to pull from each name.
String output =
"Jessica"
.codePoints()
.limit( limit )
.collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
)
.toString()
;
Jes
When you take entry from a User it's always a good idea to validate the input to ensure it will meet the rules of your code so as not to initiate Exceptions (errors). If the entry by the User is found to be invalid then provide the opportunity for the User to enter a correct response, for example:
Scanner userInput = new Scanner(System.in);
String name = "";
// Prompt loop....
while (name.isEmpty()) {
System.out.print("Please enter Name here: --> ");
/* Get the name entry from User and trim the entry
of any possible leading or triling whitespaces. */
name = userInput.nextLine().trim();
/* Validate Entry...
If the entry is blank, just one or more whitespaces,
or is less than 3 characters in length then inform
the User of an invalid entry an to try again. */
if (name.isEmpty() || name.length() < 3) {
System.out.println("Invalid Entry (" + name + ")!\n"
+ "Name must be at least 3 characters in length!\n"
+ "Try Again...\n");
name = "";
}
}
/* If we get to this point then the entry meets our
validation rules. Now we get the first three
characters from the input name and display it. */
String shortName = name.substring(0, 3);
System.out.println();
System.out.println("Name supplied: --> " + name);
System.out.println("Short Name: --> " + shortName);
As you can see in the code above the String#substring() method is used to get the first three characters of the string (name) entered by the User.
this is my code....and problem I need to have an input from user where the first letter is used , then from the second user input from 0 to 5 the characters are used, and finally generate a random number....I have tried everything for the second portion (0 to 5 characters) and I've searched the internet for different answers but nothing works.
here is the source code :
//********************************************************************
// NameNumberConverter.java Java Foundations
//
//
//********************************************************************
import java.lang.*;
import java.util.Scanner;
import java.util.*;
public class NameNumberConverter
{
//-----------------------------------------------------------------
// First the user inputs their first and last names
//-----------------------------------------------------------------
public static void main(String[] args)
{
Scanner sc = new Scanner( System.in );
System.out.println ("Please insert your first name : ");
String Firstname=sc.next();
System.out.println ("Please insert your last name : ");
String Lastname=sc.next();
char end = Firstname.charAt(0);
char end2 = Lastname.charAt(0, 5);
System.out.println ("The converted result is: " + end + end2);
sc.close();
}
}
Thanks for anything that can be helpful. as I am a student and definitely not a pro....
Unfortunately charAt(int) only takes one integer parameter.
I think what you are looking for is the range of characters for the last name. You can do something like this to get characters within a specific range for a string.
// string variable for example
String exampleString = "J. Smith";
// here is how to get a range of characters with substring(int,int)
String lastName = exmapleString.substring(3,7);
// print out "Smith"
System.out.println(lastName);
Now remember that the index value of strings starts at [0]
I'm new to programming and we were given our first assignment! My whole code is working fine, but here is my problem:
We have to prompt the user to enter in an account ID that consists of 2 letters followed by 3 digits.
So far I only have a basic input/output prompt
//variables
String myID;
//inputs
System.out.println("Enter your ID:");
myID = input.nextLine();
So all it does is let the user enter in how many letters and digits they want, in any order and length. I don't understand how to "control" the user's input even more.
As you said you are not aware of regex ,I have written this code to iterate by while loop and check if each character is a alphabet or digit. User is prompted to provide account number till the valid one is entered
import java.util.Scanner;
class LinearArray{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
boolean isIdValid = false;
String myId;
do{
System.out.println("account ID that consists of 2 letters followed by 3 digits");
myId = input.nextLine();
//Check if the length is 5
if (myId.length() == 5) {
//Check first two letters are character and next three are digits
if(Character.isAlphabetic(myId.charAt(0))
&& Character.isAlphabetic(myId.charAt(1))
&& Character.isDigit(myId.charAt(2))
&& Character.isDigit(myId.charAt(3))
&& Character.isDigit(myId.charAt(4))) {
isIdValid = true;
}
}
}while(!isIdValid);
}
}
I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.
I am working on some data structures in java and I am a little stuck on how to split this string into two integers. Basically the user will enter a string like '1200:10'. I used indexOf to check if there is a : present, but now I need to take the number before the colon and set it to val and set the other number to rad. I think I should be using the substring or parseInt methods, but am unsure. The code below can also be viewed at http://pastebin.com/pJH76QBb
import java.util.Scanner; // Needed for accepting input
public class ProjectOneAndreD
{
public static void main(String[] args)
{
String input1;
char coln = ':';
int val=0, rad=0, answer=0, check1=0;
Scanner keyboard = new Scanner(System.in); //creates new scanner class
do
{
System.out.println("****************************************************");
System.out.println(" This is Project 1. Enjoy! "); //title
System.out.println("****************************************************\n\n");
System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
System.out.println("INPUT EXAMPLE: 160:2 {ENTER} "); //example
System.out.print("INPUT: "); //prompts user input.
input1 = keyboard.nextLine(); //assigns input to string input1
check1=input1.indexOf(coln);
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
System.out.println("found ':'");
}
}while(check1==-1);
}
}
Substring would work, but I would recommend looking into String.split.
The split command will make an array of Strings, which you can then use parseInt to get the integer value of.
String.split takes a regex string, so you may not want to just throw in any string in it.
Try something like this:
"Your|String".split("\\|");, where | is the character that splits the two portions of the string.
The two backslashes will tell Java you want that exact character, not the regex interpretation of |. This only really matters for some characters, but it's safer.
Source: http://www.rgagnon.com/javadetails/java-0438.html
Hopefully this gets you started.
make this
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method
//will
// return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
System.out.print("first number = "+ numbers[0]);
System.out.print("Second number = "+ numbers[1]);
}
You knew where : is occurs using indexOf. Let's say string length is n and the : occurred at index i. Then ask for substring(int beginIndex, int endIndex) from 0 to i-1 and i+1 to n-1. Even simpler is to use String::split