How to display the middle digit in java - java

I am trying to get java to display the middle digit of a 1-4 digit integer, and if the integer has an even number of digits i would get it to display that there is no middle digit.
I can get the program to take get the integer from the user but am pretty clueless as how to get it to pick out the middle digit or differentiate between different lengths of integer.
thanks

Hint: Convert the integer to a String.
Java int to String - Integer.toString(i) vs new Integer(i).toString()
You may also find the methods String.length and String.charAt useful.

This sounds like it might be homework, so I will stay away from giving an exact answer. This is much more about how to display characters than it is about integers. Think about how you might do this if the questions was to display the middle letter of a word.

Something like this?
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (!s.hasNextInt()) {
s.next();
System.out.println("Please enter an integer.");
}
String intStr = "" + s.nextInt();
int len = intStr.length();
if (len % 2 == 0)
System.out.println("Integer has even number of digits.");
else
System.out.println("Middle digit: " + intStr.charAt(len / 2));
}
}
Uhm, I realized I might just have done someones homework... :-/ I usually try to avoid it. I'll blame the OP for not being clear in this case

Related

I'm not understanding what I'm doing wrong. How do you store an int in a String and not get an erro?

I'm using java to write a program for class. I have the first portion of code written but I can't quite figure out what I'm doing wrong. When I run the program it lets me enter a card number but then it gives me an error. My professor said that it's because for this program the card number is too long to be stored as an int. I understand that, so it's being stored in a String. But I'm still getting an error. Help please.
package creditCard;
import java.util.Scanner;
public class Card {
public static void main(String[] args) {
//Set up a scanner
Scanner in = new Scanner(System.in);
//Set up a boolean named creditCard and set it to false
boolean validCreditCard = false;
//Loop while not a valid credit card
while (!validCreditCard) {
//Prompt the user for a potential credit card number
System.out.print("Please enter a card number: ");
//Get the credit card number as a String - store in potentialCCN
String potentialCCN = in.next();
//Use Luhn to validate a credit card
//Store the digit as an int for later use in lastDigit
int lastDigit = Integer.parseInt(potentialCCN);
//Test then comment out! -check the last digit
System.out.println(lastDigit+"Check the last digit");
//Remove the last digit from potentialCCN and store in potentialCCN using String's substring
potentialCCN = potentialCCN.substring(15);
//Test then comment out! - check potential credit card number
System.out.println(potentialCCN);
}
}
}
If you want the last digit, you've got your substring backwards, it's removing everything up to that digit, then storing it back in your card number variable.
You're also parsing the entire number rather than getting the last digit
Try the following
String potentialCCN = in.nextLine();
//Use Luhn to validate a credit card
//Store the digit as an int for later use in lastDigit
int lastDigit = Integer.parseInt(potentialCCN.substring(potentialCCN.length()-2);
//Test then comment out! -check the last digit
System.out.println(lastDigit+"Check the last digit");
//Remove the last digit from potentialCCN and store in potentialCCN using String's substring
potentialCCN = potentialCCN.substring(0, potentialCCN.length()-2);
Your problem is with parseInt. You can overcome this problem using BigInteger, like
BigInteger bi = new BigInteger(potentialCCN);
or you can use regular expressions to validate that potentialCCN is a 16 digit number, like
^[0-9]{16,16}$
If the number you entered as a card number is larger than Integer.MAX_VALUE that has a value of 2147483647, then this line of code (copied below) is always going to throw you a NumberFormatException.
int lastDigit = Integer.parseInt(potentialCCN);
The reason for it is that int is not able to hold such a value, but is restricted to 2^31 − 1 or as written above, 2147483647. Therefore, if you are eligible to enter such values as card numbers you should use some type that does not have such constraints.
You're never going to be treating a credit card number as a numerical value, even though it's all digits, so keep it as a String.
I have the same opinion as Andreas.
You can do a substring operation to get the part of the cardNumber that you want to validate, and then do a Long.parseLong()
Other thingys that I saw in your code:
prefer BufferedReader and InputStream (https://stackoverflow.com/a/34955813/7192651) over Scanner because it is more faster
write as few comments as possible as clean code principles suggest, because comments become outdated, if you forget to change them, after changing your source code. If you added them specifically for stackoverflow users sake then that is not a problem ;)

JAVA: verify user input for one character

this is my first time asking a question. If I'm breaking any rules let me know please :)
I want to verify that the user only types in only one character and store in a variable I have already declared initially. As well, loop back the question for user to type in again if they did not do what they are asked for
Here is a what I have done so far
import java.util.Scanner;
public class arraytesting {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int user_Choice;
int rowAndcolumns;
char[][] user_Array;
char user_Char;
do {
System.out.print("Enter your choice (1 to 9): ");
user_Choice = myKeyboard.nextInt();
if (user_Choice < 1 || user_Choice > 9)
System.out.println("Illegal choice, please try again.");
} while (user_Choice < 1 || user_Choice > 9);
switch (user_Choice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (rowAndcolumns < 1 || rowAndcolumns > 9)
System.out.println("Illegal choice, please try again.");
} while (rowAndcolumns < 4 || rowAndcolumns > 20);
do {
System.out.print("Which character do you want to fill your square with? (only one character)");
user_Char = myKeyboard.next().charAt(0);
if () // error message for user if they did not type correctly, Idk what to put in the
System.out.println("Illegal choice, please try again.");// boolean for it to compare
System.out.print(user_Char);
} while (); // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
}
I know I can put both of them in one do-while loop, but I want to focus on getting the boolean to check for user input.
edit: I would only like the user to enter only one single character
ex. '#' or 'a'
whereas "##" or "i am typing something that is not one character" is wrong
inside the spaces of if and while are how I want it to be verified
There is no need to do any check for "only 1 character entered". That makes no sense. You can't predict the future, so you cannot know if a user will enter more characters after 1 character has been entered. You will either just take the first character entered and work with it and ignore any potential additional characters - or you have to wait for more than 1 character, essentially breaking the program for users who do the right thing (enter only one character), just to be able to give them an error message when they finally do the wrong thing (enter another character).
That being said, this code:
user_Char = myKeyboard.next().charAt(0);
will actually wait for several characters to be entered until some kind of delimiter (per default some whitespace character, e.g. newline) is entered. That's exactly what you do not want.
You want to get one character from input, and one only. You don't have to care about more characters being entered after that:
user_Char = myKeyboard.next(".").charAt(0);
This tells myKeyboard to return the next String that matches the regex ".", which is any character, and only 1 character.
If you want to validate the entered character, e.g. only alphanumeric characters allowed, you can update your if and while to something like this:
if (!Pattern.matches("[a-zA-Z0-9]", new String(user_Char)))
or even better, use the String returned by myKeyboard.next("."):
String user_String = myKeyboard.next(".");
user_Char = user_String.charAt(0);
if (!Pattern.matches("[a-zA-Z0-9]", user_String))
or you could directly tell myKeyboard to only allow valid characters and skip the entire do/if/while error handling:
user_Char = myKeyboard.next("[a-zA-Z0-9]").charAt(0);
Edit
One thing your code doesn't handle right now is invalid inputs, e.g. letters when you call nextInt. This will actually throw a java.util.InputMismatchException, and you might want to wrap your nextInt() and next(...) calls in try-catch blocks to handle these exceptions.
Please check the code below, based on the discussion with Max, I used the .length() method to check the lenght of the string that the user typed.
You can check the type of the character to avoid the runtime exception in the first if statement using some methods in Character class that you use to check if the input is digit/letter or not ?
Character.isDigit(char)
Character.isLetter(char)
Character.isLetterOrDigit(char)
I also changed some variable names, Java is following the camel case style and class name has to be capitalized. I also refactored some code to check the range of the numbers to git rid of repeating same code on and on, check the method betweenExclusive
package stackoverflow.q2;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int userChoice;
int rowAndcolumns;
char[][] user_Array;
char userChar;
do {
System.out.print("Enter your choice (1 to 9): ");
userChoice = myKeyboard.nextInt();
if ( !betweenExclusive(userChoice, 1,9) )
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(userChoice, 1,9));
switch (userChoice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (!betweenExclusive(rowAndcolumns ,1 , 9))
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(rowAndcolumns ,4 , 20));
String input;
while (true){
System.out.print("Which character do you want to fill your square with? (only one character)");
input = myKeyboard.next();
// error message for user if they did not type correctly, Idk what to put in the
// boolean for it to compare
if ( input.length()>1){
System.out.print("Illegal character, try again please !!! ");
}else{
userChar = input.charAt(0);
System.out.print(userChar);
break;
}
} // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
public static boolean betweenExclusive(int x, int min, int max)
{
return x>=min && x<=max;
}
}

Check String is in a range of numbers Java

Trying to design a simple lottery program. Everything works except checking if the numbers entered are between 1 to 59.
Exercise says the numbers must be stored in a String variable.
so
if(num<0 || num>59) //wont work for me
Tried making another variable
int numConverted = Integer.parseInt(num)
We haven't covered converting String to int in class though so I don't think this is what expected. Got confused trying that way anyway so probably this is wrong.
Here is the code I have currently.
{
Scanner scan = new Scanner(System.in);
String num=""; //num variable is empty untill user inputs numbers
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
num = num +" "+ scan.nextLine();
}
System.out.println("Ticket printed £2. Your numbers are " + num);
}
In your posted code it's obvious that you want the User to supply 6 specific numerical values. These values are appended to the String variable named num (space delimited). You need to obviously do a few things here:
1) Make sure the value supplied by the user is indeed a numerical value;
2) Make sure the numerical values supplied fall within the minimum and maximum scope of the lottery itself (which you have stated is: 1 to 59);
3) Make sure the number entered by the User hasn't been supplied already.
You've been tasked to store the entered values into a String data type variable and that is all fine but at some point you want to carry out value comparisons to make sure that all the entered values actually play within the limits of the lottery.
When the User completes his/her entries, you end up with a space delimited string held in the num string variable. You now need to make sure that these values entered are indeed....numbers from 1 to 59 and none contain alpha characters.
In my opinion (and this is only because you need to store entered values into a String variable), it's best to use your String variable to gather User input, then test the input to make sure it is indeed a string representation of an actual integer number. Once this is established then we test to make sure if falls within the value min/max limits (1-59). Now we need to test to make sure the number entered hasn't already been entered before for this ticket.
Of course with each test described above, if one fails then the User should be prompted to re-enter a proper value. You can do this by utilizing a while loop. Plenty examples of this in StackOverflow but here's a quick example:
Scanner scan = new Scanner(System.in);
String ticketNumbers = "";
for(int i = 0; i < 6; i++) {
Boolean isOK = false;
while (!isOK) {
System.out.println("\nPlease enter your desired 6 ticket numbers:\n"
+ "(from 1 to 59 only)");
String num = scan.nextLine();
//Is the string entered an actual integer number?
//We use the String.matches() method for this with
//a regular expression.
if(!num.matches("\\d+")) {
System.out.println("You must supply a numerical value! "
+ "Try Again...");
continue;
}
if (ticketNumbers.contains(num + " ")) {
System.out.println("The number you supplied has already been chosen!"
+ " Try Again...");
continue;
}
if (Integer.parseInt(num) >= 1 && Integer.parseInt(num) <= 59) {
ticketNumbers+= num + " ";
isOK = true;
}
else {
System.out.println("The number you supply must be from "
+ "1 to 59! Try Again...");
}
}
}
System.out.println("Ticket printed £2. Your numbers are " + ticketNumbers);
How about -
if(Integer.parseInt(num) < 0 || Integer.parseInt(num) > 59)
This should work, place it after the input.
If it works, please mark this as correct, I need the rep!!!
Easy way would be add available numbers (suppose it wont grow more than 60. You can use a loop to add to this as well)
String numbers[] = {"1","2","3", "..."};
Then inside the loop
Arrays.asList(numbers).contains(num);
You can remove prefixing zero in order avoid conflicts with values like '02'
Here everything is String related.
If you don't want to explicitly convert to int, you could use a regular expression.
if (num.matches("[1-5]?[0-9]")) {
...
This checks whether the String consists of (1) maybe a digit from 1 to 5, followed by (2) definitely a digit from 0 to 9. That'll match any number in the range 0-59.
If you've got a whole series of numbers separated by spaces, you could expand this to cover a whole series like this.
if (num.matches("([1-5]?[0-9]\\s+)*[1-5]?[0-9]")) {
This matches any number of repetitions (including zero) of "a number followed by spaces", followed by a single repetition without a space. The "\\s" means "any whitespace character", the "+" after it means "one or more of what precedes", and the "*" means "zero more of what precedes" - which in this case is the term in parentheses.
Oh I see what you are trying to do
This is what you want
Scanner scan = new Scanner(System.in);
String allNums = "";
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
int num = scan.nextInt();//Take the number in as an int
if(num >0 && num < 59)//Check if it is in range
{
allNums += num + " ";//if it is add it to a string
}
else
{
System.out.println("Number not in range");
i--;//go back one iteration if its not in range
}
}
System.out.println("Ticket printed £2. Your numbers are " + allNums);

Counting characters in a word

I want to create a program to output the number of occurrences of a letter in a word. Basicaly the output has to look like this:
Please enter a word—howdy
The word howdy has five characters.
What letter would you like to guess? (enter zero to quit) a
There are 0 A’s.
What letter would you like to guess? (enter zero to quit) b
There are 0 B’s.
This is what I got so far:
import java.util.Scanner;
public class LetterOccurence
{
public static void main(String[]args)
{
Scanner input=new Scanner(System.in);
String word;
String letter;
int letterNumber;
boolean [] alphabet = new boolean [27];
System.out.println("Please enter a word- ");
word=input.next();
System.out.println("The word "+ word + " has " + word.length() + " letters\n");
String lower = word.toLowerCase();
for(letterNumber=0;letterNumber<lower.length();letterNumber++)
{
alphabet[lower.charAt(letterNumber) - 'a'] = true;
}
//do
//{
System.out.println("What letter would you like to guess? (enter 0 to quit) ");
letter = input.next();
if (alphabet[letter.charAt(0)-'a'] = true)
{
System.out.printf("There are %s's\n",letter.charAt(0));
}
else
{
System.out.printf("There are 0 %s's\n",letter.charAt(0));
}
//}while(Character.isLetter(letter.charAt(0)));
}
}
I am now stuck, any ideas on how to continue?
For a start, booleans only hold a true or false value, you can't count with them. Rather than in your loop setting each element in the array that maps to a certain character to true, you could simply increment the counter.
In this case you're going to require an int as opposed to a boolean. And to print out the amount of occurrences for a specific letter, you obviously just print out the int value at that specific index of the array.
An alternative is also a Map<Character,Integer>, rather than calculating the index for specific chars in your array.
EDIT: As Dave mentioned, your if statement is also broken.
If nothing else, that if statement in your commented-out do/while is using a single = (assignment) instead of == (comparison).
All you really need to do is keep a single count per guess, initialize it to zero, and each time you encounter the guessed letter, increment it.
If you're trying to do all that work "up front" before guessing, then you don't really need a map of booleans, you need a map of ints, one per lower-case letter, initialized to zero, and incremented each time its corresponding letter is guessed.
You're very close.
You don't want a boolean array for alphabet -- that only tells you what letters appear in the word, but not how many of each. Try this instead:
boolean [] alphabet = new boolean [27];
for(letterNumber=0;letterNumber<lower.length();letterNumber++)
{
++alphabet[lower.charAt(letterNumber) - 'a'];
}
Then later:
System.out.printf("There are %d %s's\n",alphabet[letter.charAt(0) - 'a'], letter.charAt(0));

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