How to count the key characters? - java

I have the following code:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("now input a letter to be replaced");
String letter = input.next();
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
}
}
the code needs to do three things take a string and a letter and :
replace the key letter in the string with "-"
remove the key letter of the string
count the amount of times the key letter appears.
At present I have two problems. I don't know how to count the amount of times the letter
appears because technically it is a string and not a char and i do not know how to count
strings. Second, I need to make it so that if the strings are not of the desired length it
simply asks again instead of exiting the program. I have tried to use the getString() method but for some reason it always says that the method is undefined.

For issue #1:
Near the top of the main method:
int count = 0;
After user3 is assigned:
count += (user3.length() - user.length());

With full credit to user1324109 for their solution to issue #1, here is how you can solve your issue #2:
import java.util.Scanner;
public class StringReader {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user1 = "", user2 = "", user3 = "";
int count = 0;
while(user1.equals("") || user1.length() < 7) {
System.out.println("Input a string");
user1 = input.nextLine();
}
if(!user1.equals("")) {
System.out.println("now input a letter to be replaced");
String letter = input.next();
user2 = user1.replace(letter, "-");
user3 = user1.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
count += (user1.length() - user3.length());
System.out.println("letter was found to be present "+count+" times");
}
}
}

To help with issue #3:
int count = 0;
for(char c : user.toCharArray() ){
if ( c == letter.charAt(0)) count++;
}
System.out.println("Number of occurences: "+count);

Related

If condition is met -> scan input into one variable. If not -> scan input into another variable

Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}

How do I print a letter based on the index of the string?

I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.

Java string to array and replace a certain word from user to uppercase

Here is the full Question:
...
My Code
import java.util.Scanner;
import java.lang.StringBuilder;
public class javaAPIString {
public static void main(String[]args)
{
String SentenceFromUser = "";
String IndiWordFromUser = "";
/// String upper = IndiWordFromUser.toUpperCase();
//String[] words = SentenceFromUser.split("\\s+");
char ans;
Scanner keyboard = new Scanner(System.in);
do
{
final StringBuilder result = new StringBuilder(SentenceFromUser.length());
String[] words = SentenceFromUser.split("\\s");
System.out.println("Enter a sentence :");
SentenceFromUser = keyboard.nextLine();
System.out.println("Enter a word : ");
IndiWordFromUser = keyboard.next();
/// IndiWordFromUser = upper;
for(int i =0; i > words.length; i++ )
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
// System.out.println("The Output is : " + SentenceFromUser);
System.out.println("Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.");
ans = keyboard.next().charAt(0);
}
while ((ans == 'Y') || (ans == 'Y'));
}
}
My Output/ problem of my code :
Enter a sentence :
i like cookies
Enter a word :
cookies
The Output is : i like cookies
Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.
it returns the same original sentence without changing to Uppercase of the second input to replace to all CAPS.
I hope my solution will help you out! :)
import java.util.Scanner;
public class Solution {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
getTextFromUser();
}
private static void getTextFromUser() {
print("Enter Sentence Here: ");
String text = in.nextLine();
print("\nDo you want to capitalize words in sentence? Y/N: ");
while (in.nextLine().equalsIgnoreCase("y")) {
print("Enter Word: ");
print("Modified Text: " + changeWord(text, in.nextLine()));
print("\n\nDo you want to capitalize words in sentence? Y/N");
}
}
private static String changeWord(String text, String word) {
return text.replaceAll("\\b" + word + "\\b" /* \\b Means word
boundary */, word.toUpperCase()); // No validations done.
}
private static void print(String message) {
System.out.print(message);
}
}
Just some things:
please use java naming conventions for variables name
when you execute your code this instruction will overwrite the user input with an empty string.
IndiWordFromUser = upper;
String[] words = SentenceFromUser.split("\\s");... you are splitting an empty string the first time and the old sentence the other runs
The variable IndiWordFromUser is never read

Java - make sure each letter does not contain a number

Very new to programming, just starting a Java class.
Here is what the assignment says
1.) Input, via a question in the console, the report owner’s first name as a string and build the last name via input, one character at a time.
a. Check, conditionally, to make sure the first name and last name don’t contain any numeric characters, numbers between 0 – 9. If it does you must remove it. The names can not contain any white space either or special characters.
I already did the first part, and here is my code:
package inclassassignment;
import java.util.Scanner;
public class inclassassignment {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println ("Enter your first name");
String temp;
Scanner your_name = new Scanner (System.in);
temp = your_name.nextLine();
System.out.println(temp);
int n = 0;
System.out.println ("Enter your last name");
String temp1;
temp1 = "";
while (n < 6) {
System.out.println("Please print the next letter of your last name");
String nextletter1;
Scanner lastname = new Scanner (System.in);
nextletter1 = lastname.nextLine();
char nextletter = nextletter1.charAt(0);
temp1 = temp1 + nextletter;
n++;
}
System.out.println(temp1);
{
}
}
}
// I now need to do the part that says to check each ASCII value and make sure none of the letters contain a number. I'm pretty sure this requires an "if else" statement but I've never written one to success.
edit: I should point out I am not allowed to have any static variables or methods in any class except for the class with the main method.
According to your task, you can do it in this way:
int n = 0;
System.out.println("Enter your last name");
String lastName = "";
while (n < 6) {
System.out.print("Please print the next letter of your last name: ");
String tmp = your_name.nextLine();
char c = tmp.charAt(0);
if (Character.isAlphabetic(c)) {
lastName += c;
n++;
} else {
System.out.println("You can use only letters! Try again!");
}
}
System.out.println(lastName);
You can use regular expressions
Scanner sc=new Scanner(System.in);
String s= sc.nextLine(); //read the string
String regex1 = "\\d+" // the regular expression for numbers
if(s.matches(regex1)) // check if the string contains numbers
System.out.println("contains numbers");
I would start with a utility method to normalize names based on your required rules, Character.isUpperCase(char) or Character.isLowerCase(char) and a for-each loop over String.toCharArray() like,
static String normalizeName(String name) {
StringBuilder sb = new StringBuilder();
for (char ch : name.toCharArray()) {
if (Character.isUpperCase(ch) || Character.isLowerCase(ch)) {
sb.append(ch);
}
}
return sb.toString();
}
Then you can call it (and I would use it for both firstName and lastName, for consistency). Like,
public static void main(String[] args) {
System.out.println("Enter your first name");
Scanner scan = new Scanner(System.in);
String firstName = normalizeName(scan.nextLine());
System.out.println("Enter your last name");
String lastName = normalizeName(scan.nextLine());
System.out.printf("Hello %s %s%n", firstName, lastName);
}
Pretty sure this is posted elsewhere
str.matches(".*\\d+.*")// To check if string contains numbers
Try this function:
public String removeNum(String in){
String[] input= in.split("");
String num= "0123456789";
String[] numbers= num.split("");
List<String> numbersToDelete = Arrays.asList(numbers);
for(int i=0;i<input.length;i++){
if(numbersToDelete.contains(input[i])){
input[i]="";
}
}
//Converting from Array back to String
String out = "";
for(int j=0;j<input.length;j++){
out=out+input[j];
}
return out;
}

Why will this not only return the string if it is a palindrome?

Below is the code that I wrote in order to have a user input a few different strings, check if each is a palindrome, and only return the palindrome. Currently, all of the entered in strings will be returned. It seems that the IF statement if not working correctly. Any suggestions on how to have the correct strings returned?
import java.util.Scanner;
public class hh {
static void checkPalin () {
// creates a scanner
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
// asks the user for the number of strings
System.out.print("Enter the number of strings: ");
StringBuilder sentence = new StringBuilder(userInput);
StringBuilder palindrome = new StringBuilder();
// stores the number of strings user will enters
int stringNumber = input.nextInt();
// prompts the user to enter in their sentences
System.out.println("Enter the strings:");
// this loop will go until the number of strings entered are entered
while(i <= stringNumber){
userInput = input.nextLine();
if(sentence.reverse().equals(sentence)){
palindrome.insert(0, " " + userInput);
}
i ++;
}
// if( sentence == sentence.reverse()){
System.out.println("The palindromes are: " + palindrome);
}
public static void main(String[] args) {
checkPalin();
}
}
You need to create the String from the StringBuilder using the toString method before calling equals:
if(new StringBuilder(userInput).reverse().toString().equals(userInput)) { ... }
When you declare
StringBuilder sentence = new StringBuilder(userInput);
The "sentence" variable will not change if userInput changes. You need to recreate the StringBuilder each time you need it.
Here is the fixed code :
static void checkPalin() {
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
System.out.print("Enter the number of strings: ");
StringBuilder palindrome = new StringBuilder();
int stringNumber = input.nextInt();
System.out.println("Enter the strings:");
while (i <= stringNumber) {
userInput = input.nextLine();
String reversed = new StringBuilder(userInput).reverse().toString();
if (reversed.equals(userInput)) {
palindrome.insert(0, " " + userInput);
}
i++;
}
System.out.println("The palindromes are: " + palindrome);
}
You have to write something like
new StringBuilder(sentence.toString()).reverse().equals(sentence)
in your if

Categories