Validating Scanner to only allow characters - java

Here's my first question. I'm taking an online coding class, and it definitely has some holes in the instruction. We have been tasked with taking 2 different inputs that are one character only, and converting them to ASCII values. I have that down pat, I'm struggling with how I'm supposed to validate the inputs to only allow one character, and not something such as a number or symbol, and then exit the program if such an error arises. Here's my code.
import java.io.*;
import java.util.*;
public class AndrewBrutonMod4TopSecret
{
public static void main(String args[])
{
Scanner kaReader = new Scanner(System.in);
System.out.println("Enter the first initial of your first name:");
String i1 = kaReader.next();
System.out.println("Enter the first initial of your last name:");
String i2 = kaReader.next();
char a = i1.charAt(0);
char b = i2.charAt(0);
char a1 = Character.toUpperCase(a);
char b1 = Character.toUpperCase(b);
int c = (int)a;
int d = (int)b;
System.out.println("Initials: "+a1+" "+b1);
System.out.println("Encrypted Initials: "+c+" "+d);
}
}
Any thoughts?

I'm struggling with how I'm supposed to validate the inputs to only
allow one character, and not something such as a number or symbol
You can use isAlphabetic() method
Javadoc:
Determines if the specified character (Unicode code point) is an
alphabet. A character is considered to be alphabetic if its general
category type, provided by getType(codePoint), is any of the
following:
UPPERCASE_LETTER
LOWERCASE_LETTER
TITLECASE_LETTER
MODIFIER_LETTER
OTHER_LETTER
LETTER_NUMBER
or it has contributory
property Other_Alphabetic as defined by the Unicode Standard.
private static boolean isValidChar(char ch) {
return Character.isAlphabetic(ch);
}
and then exit the program if such an error arises
For example
if (!isValidChar(a))
System.exit(-1);

Related

Changing the letters

Well i'm trying to get a String from user and change each letter to the String "enc" I have down here. So basically if the user input "hello" I want it to return back "xahhi". I am kind of lost and don't know what to do.
String userInput = input.nextLine();
String letters = "abcdefghijklmnopqrstuvwxyz";
String enc = "kngcadsxbvfhjtiumylzqropwe";
int stringLength = userInput.length();
for (int i = 0; i < stringLength; i++) {
if (userInput.charAt(i) == letters.charAt(i)) {
System.out.print(enc.charAt(i));
}
}
What you want to do is have a Map<Character,Character> where key will be correct Character that in the String and the value should be Character that is encoded.
Then you query the Map for the encoding an generate you encoded string.
Code should look like :
Map<Character,Character> myEncodingMap = new HashMap<Character,Character>();
StringBuilder sb = new StringBuilder();
for (Character ch : letters.toCharArray()) {
sb.append(myEncodingMap.get(ch)
}
System.out.print(sb.toString());
Here is one that might be a little simpler if you are just starting out in programming. I have explained what each line does in the code so take a look and try to understand and expand on it! Let me know what you think or if you have any questions.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray(); //Just takes the String and puts it into a array of chars
char[] enc = "kngcadsxbvfhjtiumylzqropwe".toCharArray();
Scanner scan = new Scanner(System.in); //Scanner for user input
System.out.println("enter phrase"); //prompts for user input
String input = scan.next(); //Takes user input and stores it in String input
for(int i = 0; i<input.length(); i++){
char temp = input.charAt(i); //Stores the first Character of the entered phrase in a variable called temp.
int tempNums = (new String(letters).indexOf(temp)); //takes the position in the first array of the first char entered and stores it.
System.out.print(new String(enc).charAt(tempNums)); //prints out the values of the first character according to the second array.
}
}
}
If you want to use String methods only, you're close. However, you need to use two methods from the String class to finish this: indexOf(char) and charAt(int).
indexOf(char) takes a character and returns the index of the first location it appears in the string. For example, if you have a string with contents Hello World, then str.indexOf('l') will return 2, which is the first index in the string that matches the given character.
charAt(int) takes an integer and returns the character in a string at the given index. For example, using the same string as above, calling str.charAt(4) will return 'o'.
Using these two methods can get you an index of one string which you can then use to reference the character of the other.
I'm not going to put the answer in your code (you should learn enough to be able to do it yourself), but I'll give you a skeleton of how I would do this using just the two methods above.
// The two strings used for encoding
String strNormal = "ABCDEF";
String strCode = "UVWXYZ";
// The example string that is input by the user
String input = "BED";
/*** NOTE: This only replaces the first letter of the input string ***/
// Get the first character of the input string
char originalChar = input.charAt(0);
// Get the index of of the corresponding character in the normal string
int searchIndex = strNormal.indexOf(originalChar);
// Get the corresponding character of the encoder string
char encodedChar = strCode.charAt(searchIndex);
// Print out the encoded letter
System.out.print(encodedChar);
Though this approach will work, there are some caveats. The biggest one is performance: Every time you call indexOf or charAt, Java loops through the entire string to find what you're looking for. This isn't a problem for small strings like you'll be dealing with, but imagine a string that's maybe 10,000 characters long... It's possible that you'd have to search every letter in that string 10,000 times! Not super efficient.

To check if a given string is SuperAscii or Not - java.lang.StringIndexOutOfBoundsException

The problem goes like this:
If a is assigned the value 1, b=2,c=3,...z=26, check if a given string is a Super Ascii String or not. A string is said to be a Super Ascii String, if the number of times a character is repeated matches its value. The string must be only in lowercase letters
Eg. abbccc is super ascii because a=1,b=2,c=3. Similarly, bab, "bb a ccc"
This is my attempt in solving the problem
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
public class SuperAsciiNew
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
String input = in.nextLine();
char[] inputArray = input.replaceAll("\\s+","").toCharArray();
Arrays.sort(inputArray);
String customInput = new String(inputArray);
char currentChar = customInput.charAt(0);
int increment=0;
Map<Character, Integer> characterMap = new HashMap<Character, Integer>();
char a='a';
boolean superascii = true;
for(int i=1;a<='z';i++,a++)
characterMap.put(new Character(a), new Integer(i));
while(increment<=customInput.length())
{
int nooftimes = customInput.lastIndexOf(currentChar) - customInput.indexOf(currentChar) + 1;
if(characterMap.get(currentChar) == nooftimes)
{
System.out.println("The character "+currentChar+" is repeated "+nooftimes);
increment += nooftimes;
currentChar = customInput.charAt(increment);
}
else
{
superascii = false;
break;
}
}
if(superascii == true)
System.out.println("The given string "+input+" is a Super Ascii string");
else
System.out.println("The given string "+input+" is not a Super Ascii string");
}
}
Here, first I am removing spaces (if any), sorting the string. Then, I find the first character in the string, what is its value and how many times is it repeated. If these two values are not equal then the loop is broken else, the number of times the character is repeated is incremented in increment variable and the next character is found.
The output I get for various test cases:
java SuperAsciiNew
Enter a string : abb ccc
The character a is repeated 1
The character b is repeated 2
The character c is repeated 3
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : bab
The character a is repeated 1
The character b is repeated 2
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : hello world
The given string hello world is not a Super Ascii string
When the string "hello world" is given, the output is generated without any exceptions. What is the issue here?
I have one more doubt in Java:
What is the difference between importing individual classes like java.util.Scanner and importing the package as whole java.util.*? Are there any performance issues? What I feel is, the second one might consume more memory while the first, the system has to search the appropriate class and include it. Am I right in my thinking?
You are checking for a character one too many times.
Use the following condition:
while(increment<=customInput.length()-1)
instead of:
while(increment<=customInput.length())
Edit: the reason you are not getting the error on "hello world" is because it fails before reaching that extra char, thus not throwing an exception.

How to convert user inputted char to its numerical position in Java? [duplicate]

This question already has answers here:
How to map character to numeric position in java?
(7 answers)
Closed 5 years ago.
So I'm stuck on this problem in my Java intro class. I'm a complete newbie at this stuff, so any help is appreciated. I have to design and create a program that accepts a user inputted letter (which should be either a-z or A-Z) and determine what position it holds in the alphabet. (so a would equal 0) I keep having issues with string to char and char to int conversions. Any tips or leads on how to design this program would be much appreciated. I've been working on this program literally all day and haven't had made any discernible progress.
Just subtract the char constant 'a' from your input char.
Try the following code:
char c = 'b';
System.out.println(c - 'a' + 1);
The output will be 2.
In order to get a user inputted anything use a Scanner. In this case the following code will prompt the user for a character then assign that to a variable called 'c'.
import java.util.*;
// assuming that the rest of this code is inside of the main method or wherever
// you want to put it.
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
char c = Character.valueOf(input.next());
Then using this code use whatever method you like to convert to alphabetical position. Hope that helps!
I think it was answered already but putting it all together:
/**
* Gets the numerical position of the given character.
*/
private static final int convertToPosition(final char c) {
return c - 'A' + 1;
}
public static void main(String[] args) throws Exception {
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
if (input.hasNext()) { // if there is an input
String inStr = input.next().toUpperCase();
if (inStr.length() != 1) {
System.out.println("Unknown letter");
return;
}
char c = inStr.charAt(0);
int pos = convertToPosition(c);
System.out.println("Position: " + pos);
} else {
System.out.println("no input");
}
}

How do I ignore characters entered by the user via Scanner?

Im working right now on a program that can divide, add, ect, but, im also making it for others, so, the problems usually have letters as well. What code could I implement so that my program ignores characters, and just focuses on numbers?
import static java.lang.System.out;
import java.util.Scanner;
public class Trinomial {
public static void main(final String args[]) {
final Scanner first = new Scanner(System.in);
out.print("Enter the first number: ");
final int First = first.nextInt();
final Scanner second = new Scanner(System.in);
out.print("Enter the second number: ");
final int Second = second.nextInt();
final Scanner third = new Scanner(System.in);
out.print("Enter the third number: ");
final int Third = third.nextInt();
numFactors(First);
}
}
You can have your program check whether each character it looks at is a digit using Character.isDigit()
http://www.tutorialspoint.com/java/character_isdigit.htm
You probably also want to allow your math operators through, e.g.
if (Character.isDigit(input) || input == '+' ||
input == '-' || input == '/' || input == '*')
{
// Do something with input
}
If that's not what you're looking for, please improve your question to be more specific.
Firstly, you will have to use next() method from the scanner, as nextInt() will return an exception if the next token contains non-digit characters. This will read the token as a String. Then you can get rid of non-digit characters by, for example, creating an empty String (for performance reasons StringBuilder can be better, but that makes it more complex), looping through the original string and using the already mentioned isDigit() method to determine whether the character is a digit. If it is, add it to your new string. Once you have a string containing only digits, use Integer.parseInt(string) method to get the integer value.
I am not quite sure, why you initialise a new Scanner every time, I think you should be able to use the first one throughout your program.

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

Categories

Resources