Uppercase a string input from scanner in java - java

I am supposed to use the Scanner in Java to receive a 14 char input and have all the letter char output in uppercase format. I've tried entering some of the code I found through Google such as " str.toUpperCase(Locale.ENGLISH); " but it tells me str cannot be resolved and that the locale can't be resolved. When I did a search on here I got results for uppercasing specific char or counting char. I just need the specific line of input to be uppercased.
The following is what I have at the moment. I am using eclipse java neon
import java.util.Scanner;
public class MemberIDLotz {
// Everette Lotz
public static void main(String[] args) {
Scanner string = new Scanner(System.in);
// We're going to get a 14 char string from a user.
System.out.println("Please enter in a 14 character long ID");
String name = string.next();
str.toUpperCase(Locale.ENGLISH);
string.close();
}
}
Thank you for your help in advance.
*Edit: Ok so it is no longer giving me an error message, and yes I had simply copy and pasted the code. However when it prints out its not in upper case format. I put the following right after "String name =...." and deleted the str.toUppercase() line:
System.out.println(name);
name = name.toUpperCase();`

Is there a reason you don't uppercase immediately?
String name = string.next().toUpperCase()

Change to
name = name.toUpperCase(Locale.ENGLISH);
or more simply
name = name.toUpperCase();

You can also add trim to it if you'd like, it is a working example:
String choice;
Scanner s = new Scanner(System.in);
choice = s.nextLine().trim().toUpperCase();

Related

I need some guidance on the substring function in JAVA

I'm not sure where I am going wrong with this particular code. Could someone please lend me some guidance to this?
Here is my question as well as what I have attempted to have as an outcome.
Modify songVerse to play "The Name Game" (OxfordDictionaries.com), by replacing "(Name)" with userName but without the first letter.
Ex: If userName = "Katie" and songVerse = "Banana-fana fo-f(Name)!", the program prints:
Banana-fana fo-fatie!
Ex: If userName = "Katie" and songVerse = "Fee fi mo-m(Name)", the program prints:
Fee fi mo-matie
Note: You may assume songVerse will always contain the substring "(Name)".
Code that I tried this last time...and no matter what I put in I keep getting the same results. I've tried different scenarios of the "userName.substring()" and still have the same outcome.
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse + userName.substring(1 , userName.length()); // this is where my problem is.
System.out.println(songVerse);
}
}
1 test passed
All tests passed
Run
Testing Katie and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!tie
Expected output
Banana-fana fo-fatie!
Testing Walter and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!lter
Expected output
Banana-fana fo-falter!
Testing Katie and Fee fi mo-m(Name)
Output differs. See highlights below.
Your output
Fee fi mo-m(Name)tie
Expected output
Fee fi mo-matie
Here you go.
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName.substring(0));
System.out.println(songVerse);
}
}
here you removed first character already from userName, so at the second last line you again don't need to remove it.
and for the song Verse, you need to remove "(NAME)" from it, so here you can use
songVerse = songVerse.replace("(NAME)","");
songVerse = songVerse+userName;
The method substring(int begin, int end) let hoose/create a substring from the initial String indicating the numbers of chars from which the substring should begin and end or begin only. There are no other variants to edit a substring, while it will not become a part of a freshly made string (“String songVerse” in your case). The object.replace() method should change the indicated “Text” (in your case it’s a “(Name)”) onto anything that you’d like to be inserted instead of it independently on the quantity or type of the chars before or after the “Text”. The variant proposed by Nicholas K is correct and should work or you can try its shorter version, however the result will be the same:
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
songVerse = scnr.nextLine();
songVerse = songVerse.replace("(Name)", userName.substring(1));
System.out.println(songVerse);
}
}
The problem with your code is that you are not attempting to solve the problem that you described in your question.
Try following these steps:
Devise a list of steps written in English to solve the problem; pay attention to details.
Run the list of steps in step 1 by hand.
Convert the steps in step 1 to code.
Here are some hints:
You will be reading the lyrics one line at a time.
Some lines have a replacement and others do not.
You will receive the Name as input one time; generate the name replacement value one time and use it each time you perform a replacement.
Your code is terrible.
Here is some more about "Pay attention to details"
You do not have a loop in your code;
this will read one line of lyrics and perform one substitution.
Count the number of lines in the lyrics.
If the number of lines is greater than one,
then your technique is guaranteed to fail.
If you have a loop in your code but decided not to include it in your code,
stop lying in your questions.
We can not help you fix code that you pretend does not exist.
In a sane world,
the name to use for the substitutions will appear exactly one time.
Read it one time.
In order to replace (Name) in a string, you must first find (Name) in a string.
This is pretty easy
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName);
/* Your solution goes here */
System.out.println(songVerse);
}
}

Java input/output confusion

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.

Converting Strings to Uppercase with charAt

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

Why is this code keep being "terminated"?

I have this code in Eclipse:
package test;
import java.util.Scanner;
class test{
public static void main(String args[]){
Scanner Input = new Scanner(System.in);
if (Input.equals("payday2")){
System.out.println(Input);
}
}
}
Now when I try to start the code/aplication, it terminates itself.
Any ideas why that happens?
You instantiate the Scanner as a variable named Input but never try to read.
Your condition
if (Input.equals("payday2")){
will only check if the Scanner object is equals to the string "payday2" which will always be false, hence the program terminate.
If you want to read, you need to do Input.nextLine().
I dont know about eclipse, but Netbeans would give a warning "equals on incompatible type" with this line.
Also, you should not name your variable with a capital letter as by convention, only class name should start with a capital.
So your fixed program would be
Scanner input = new Scanner(System.in);
String value = input.nextLine();
if ("payday2".equals(value)) {
System.out.println(value);
}
Notice that I kept the string in a variable to display it as displaying input would call toString of the Scanner object which is probably not what you expected.
Notice that I also compared the string in reverse order which is a good practice to avoid NPE even if not really needed here.
You never read input from the Scanner instance so the application doesnt block
String text = input.nextLine();
if ("payday2".equals(text)) {
...
I think you mean to do:
String in = Input.nextLine();
if(in.equals("payday2"))
{
System.out.println(in);
}
Note: in Java 7 you can do the following:
String in = Input.nextLine();
switch(in)
{
case "payday2":
System.out.println(in)
break;
case "payday the heist":
//...
break;
}
Which makes it much easier to manage different input cases.

How to take a scanner object and make it a String

I need help doing the following:
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
The below code is what I have so far but it is only returning user input and not removing numbers:
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1.replaceAll("[^0-9]","");
System.out.println(firstname1);
Updated Code. Thank you Hovercraft. I am now investigating how to retrieve all alpha characters as with the code below, I am only getting back the letters prior to the numeric values entered by the user:
import java.util.Scanner;
public class Assignment2_A {
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1 = firstname1.replaceAll("[^A-Z]","");
System.out.println(firstname1);
String input = yourScannerObject.nextLine ();
where "yourScannerObject" is the name you give your scanner.
What method did you use to scan? is it {scanner object name}.next() ?
if so you have got a string and all that you have to do is create some string, and save the input to it, e.g.:
String str="";
str = {scanner object name}.next();
before using anything in java, I would advise you to read the API :
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next()
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
Here's an example:
String in;
Scanner scan = new Scanner("4r1e235153a6d 6321414t435hi4s 4524str43i5n5g");
System.out.println(in = (scan.nextLine().replaceAll("[0-9]", ""))); // use .next() for space or tab
Output:
read this string
The problem in your code is the regex "[^A-Z]" is set to remove all non-alphabet capital characters. This means you remove all lower case as well. You could say "[^a-zA-Z]", but then you're also removing special characters.

Categories

Resources