Converting Strings to Uppercase with charAt - java

I'm writing a program that asks the user to enter their last name in lower case and asks them if they want it outputted as all caps or with just the first letter capitalised. The problem I'm having is using charAt with toUpperCase.
import java.util.Scanner;
//This imports the scanner class
public class ChangeCase {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
//This allows me to use the term scan to indicate when to scan
String lastName;
//sets the variable lastName to a string
int Option;
System.out.println("Please enter your last name");
//Prints out a line
lastName = scan.nextLine();
//scans the next line of input and assigns it to the lastName variable
System.out.println("Please select an option:"+'\n'+"1. Make all leters Capitalised"+'\n'+ "2. Make the First letter Capitalised");
Option = scan.nextInt();
if (Option == 1){
System.out.println(lastName.toUpperCase());
}
if (Option == 2){
System.out.println(lastName.charAt(0).toUpperCase());
}
}
}
I get an error saying "Cannot invoke toUpperCase() on the primitive type char"

You can't apply String.toUpperChase on a char like your error is saying. In the case where you want to make the first letter uppercase you can do something like:
String lastName = "hill";
String newLastName = lastName.substring(0, 1).toUpperCase() + lastName.substring(1);
System.out.println(newLastName);
A sample run of this:
run:
Hill
BUILD SUCCESSFUL (total time: 0 seconds)
In the case where you want all the letters uppercase, it's as simple as
newLastName = lastName.toUpperCase();
System.out.println(newLastName);
A sample run of this:
run:
HILL
BUILD SUCCESSFUL (total time: 0 seconds)

I used to try this in C programming in college. Should work here as well.
(char)(lastName.charAt(i) - 32)
Try the above in System.out.println
The code when we deduct 32 from character it reduces ascii value by 32 and hence gets upper case letter. Just refer an ascii table to understand what I am trying to tell by deduction of 32 places in the table.

As your error is telling you, you can't invoke String.toUpperCase() on a primitive char type.
System.out.println(lastName.charAt(0).toUpperCase());
But, you can invoke Character.toUpperCase(char) like
System.out.println(Character.toUpperCase(lastName.charAt(0)));
Or, call String.toUpperCase() and then take the first character. Like,
System.out.println(lastName.toUpperCase().charAt(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.

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

Difference between next( ) and next( ).CharAt(0);

I have created an abstract class Employee which displays and calculates the Details of Weekly and Hourly Employee.In the main method i have used switch case for a menu and do while to continue using the program as long as the user want.But I'm getting an Error when compiling the code.:
*javac "AbstractDemo.java" (in directory: /home/user/Desktop)
AbstractDemo.java:52: error: incompatible types
ch=s.next();
^
required: char
found: String
1 error
Compilation failed.*
This is the Source Code:
import java.util.*;
abstract class Employee{
Employee(float amt,int n){
float sal;
System.out.println("The amount paid to Employee is:"+amt);
sal=amt*n;
System.out.println("Total Salary is:"+sal);
}
}
class WeeklyEmployee extends Employee{
WeeklyEmployee(float a,int n){
super(a,n);
}
}
class HourlyEmployee extends Employee{
HourlyEmployee(float amt,int hrs){
super(amt,hrs);
}
}
public class AbstractDemo {
public static void main (String args[]) {
int a;
char ch;
float amount;
int hours;
int weeks;
Scanner s=new Scanner(System.in);
do{
System.out.println("Enter the choice");
a=s.nextInt();
switch (a) {
case 1 :
System.out.println("Enter the salary of weekly employee(Per Week):");
amount=s.nextFloat();
System.out.println("Enter the total no of week");
weeks=s.nextInt();
Employee W=new WeeklyEmployee(amount,weeks);break;
case 2:
System.out.println("Enter the salary of hourly employee(Per hour):");
amount=s.nextFloat();
System.out.println("Enter the total no of hours");
hours=s.nextInt();
Employee H=new HourlyEmployee(amount,hours);break;
default:System.out.println("Error invalid Choice");
}
System.out.println("Do you wish to continue?(Y/N)");
ch=s.next();
}while (ch== 'y'||ch== 'Y');
}
}
But When i use s.next().ChatAt(0); the code compiles successfully.Could somebody explain why this is happening?Is Char taking input as String?Or if it is a string why its showing an Error when i edit the while condition to while(ch=="y"||ch=="Y"); ?
ch is a char. s.next() returns a String. You can't assign a String to a char. You can assign the first character of the String to a char, which is what you do in ch = s.next().charAt(0);.
It's a good thing you are not trying while(ch=="y"||ch=="Y"), since that would fail even if you changed ch to be a String (which would allow it to pass compilation, but wouldn't give the expected result), since you can't compare Strings in Java with == (you should use equals instead).
s.next() returns the next String object. But s.next().charAt(0) returns the first character of the next String object. Hence its expecting character and throwing error
the method next() of the Scanner object returns a String. So in order for your assignment to work, you need to extract the first character from this string using the charAt() method.
And since ch is a character not String, while(ch == "y" || ch == "Y") won't work.
Use while(ch == 'y' || ch == 'Y') instead.
(single quotes = character, double quotes = string)
This because ch is char and your idea is input single letter Y or N to stop or continue your program. But, you use method next() of Scanner that return a String. That's main reason why you get this
*javac "AbstractDemo.java" (in directory: /home/user/Desktop)
AbstractDemo.java:52: error: incompatible types
ch=s.next();
^
required: char
found: String
1 error
Compilation failed.*
When you try to use s.next().ChatAt(0). It mean that you try to get first character from input.
-> this is just imcompatible types error when you try to assign String to Char without converting it.
When you use s.next(), it is read as a string. That's why you get an error with ch=s.next()
However, s.next().charAt(0) will return a char value which can be used by your variable.
Likewise, when you compare char ch to 'y', it compares two chars, but "y" reads as a string and would cause a type mismatch.

Checking Multiple strings with if, else if statement

I am creating a simple lift programme in java. I want to to have four users that are allowed to use the lift i have already got it working for 1 but i cant figure out how to check multiple strings using the one if statement.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
String name;
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry "))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
Check out this related question:
Test if a string contains any of the strings from an array
Basically, put the names into an Array of strings, and compare the name entered with each name in the Array.
Use the OR symbol "||" or "|".
Such as if (name.equals("barry ") || name.equals("sara"))
For future reference the difference between the two is "||" short circuits. In this situtation, if barry is the name then the second statement for checking against sara will never be executed.
basically, you need an "Or" gate, this would work:
if(name.equals("name1")||name.equals("name2")||name.equals("name3"))
etc...

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