charAt never works correctly from Scannner input - java

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]

Related

How can I obtain the first character of a string that is given by a user input in java

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.

Two problems, using charAt for undefined input and looping output

So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using .split. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.
My questions are:
How do I use charAt to identify a character at an undefined index (user input with varying lengths)
How do I stop my sentence from reading back after the user decides to continue.
Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.
To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,
backward = "";
To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,
words[count].charAt(words[count].length() - 1);
Note that count is simply words.length - 1 so this can be changed to your liking.
1) So you have this array of strings words. Before adding each word to the backward string, you can use something like: words[count].chartAt(words[count].length() - 1). It will return you the charater at the last position of this word. Now you are able to do you checking to know wether it is a letter or any special char.
2) The problem is not that it is reading the previous line again, the problem is that the backward string still has the previous result. As you are using a + operator to set the values of the string, it will keep adding it together with the previous result. You should clean it before processing the other input to have the result that you want.
here is your code:
import java.util.*;
public class main{
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String[] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
List<String> items = Arrays.asList(words);
Collections.reverse(items);
System.out.println(generateBackWardResult(items)); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
// i use quals ignore case, makes the code more readable
} while (!sentinel.equalsIgnoreCase("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
static String generateBackWardResult(List<String> input){
String result="";
for (String word:input){
result =result +" "+word;
}
return result;
}
} // end class MyTokenTester][1]][1]
there are also some thing to mention:
* never invent the wheel again! (for reverting an array there are lots of approaches in java util packages, use them.)
*write clean code, do each functionality, i a separate method. in your case you are doing the reverting and showing the result in a single method.

Storing multiple phone numbers in a single array in Java

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

Need help splitting a string into two separate integers for processing

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

How do I create a name generator?

I am creating a program that prompts a first and last name then prints a string composed of the first letter of the user’s first name, followed by the first five characters of the user’s last name, followed by a random number in the range 10 to 99.
I know how to prompt for the name and find the random number but I'm not sure how to
"print a string composed of the first letter of the first name, followed by the first five letters of the last name."
Can anyone help me? I am a very elementary Java programmer.
So I am really close to finishing this but it keeps saying "illegal start of expression" for line 55 and I can't figure it out. Here is my code, sorry, I know it's a mess:
Random generator = new Random();
int num1;
num1 = generator.nextInt(10-99);
line 55: public String substring; <<<
String result;
System.out.println("Result:" + (beginIndex) + (firstname.substring(0,1) + lastname. substring (0,5)) + (num1) );
Seems like homework to me, so I will give a hint. look for the method substring() and charAt() for the first part, and the Random class for the second.
I am a .NET developer so I can't help you with the syntax but you would need to grab the first char of the first name, usually accessible via an indexer - firstName.charAt(0), and a substring of the second one that ranges from the first character (ordinal 0) to the 5th character (ordinal 4), likely something like lastName.substring(0, 4); and concatenate these two strings -
concatenatedName = firstName.charAt(0) + lastName.substring(0, 4);
Something like this will do
import java.lang.String;
import java.io.*;
import java.util.Random;
class Name {
public static void main(String args[]) {
Random rnd = new Random(); // Initialize number generator
String firstname = "Jessica"; // Initialize the strings
String lastname = "Craig";
String result; // We'll be building on this string
// We'll take the first character in the first name
result = Character.toString(firstname.charAt(0)); // First char
if (lastname.length() > 5)
result += lastname.substring(0,5);
else
result += lastname; // You did not specify what to do, if the name is shorter than 5 chars
result += Integer.toString(rnd.nextInt(99));
System.out.println(result);
}
}
You're missing a closing parentheses for println.
I would recommend removing all the parentheses around the string concats they just make it hard to read.
System.out.println("Result:" + beginIndex + firstname.substring(0,1) + lastname.substring(0,5) + num1 );
Also what happens if the user enters a last name with only 4 characters?
Take a look at String.substring()
See how easy it is? I gave 4 simple names which can be replaced with words and such. The "4" in the code represents the number of names in the String. This is about as simple as it gets. And for those who want it even shorter(all I did was decrease the spacing):
import java.util.*;
public class characters{
public static void main(String[] args){
Random generate = new Random();
String[] name = {"John", "Marcus", "Susan", "Henry"};
System.out.println("Customer: " + name[generate.nextInt(4)]); }}

Categories

Resources