using charAt in a program - java

What I am trying to do is very elementary. The user should enter a name and the program prints only the initials of the name except for the last word.
Eg:
input - "Mansha Mannan UL Haque"
output - "M.M.U.Haque"
The program is as follows but it does not compile.
class joke
{
public static void main(String str)
{
String alter=" "+str;
int n=alter.length();
for(int i=0;i<=n;i++)
{
char f=alter.charAt(i);
if (f.compareTo(" ")>0)
{
System.out.println(alter.charAt(i+1));
}
}
}
}
The error showed is char cannot be dereferenced.

Split your input string into string array then access each word and print its first char, for last word print it whole.
class joke
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String alter=sc.nextLine(); //take input from user
String arr[] = alter.split(" ");
int n=arr.length(); //total words in user string
for(int i=0;i<n;i++)
{
if(i==n-1){ //if last word
System.out.print(arr[i]);
}
else{
System.out.print(arr[i].charAt(0)+". ");
}
}
}
}

This should do the trick
in this case namewould be your input
String name = "Mansha Mannan UL Haque";
String[] nameArray = name.split(" ");
String newName = "";
for(int i = 0; i < nameArray.length; i++)
{
if(i != nameArray.length -1)
{
newName += nameArray[i].substring(0, 1) + ".";
}
else
{
newName += nameArray[i];
}
}
and you should also make your class joke public and change String str to String[] args

Related

How can I replace the letters in a String?

I am supposed to write code that replaces a letter in an input. For example, if the word is "hello" and the letter to replace is "l" and put "y" it would make "heyyo". I just don't know what to do after the user inputs.
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static int replaceLetter(String word, String letterToReplace, String replacement)
{
int count = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
count++;
}
}
return count;
}
}
Try doing the next, replacing the char at the position if it is the same as the letter to replace.
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == letterToReplace)
{
word = word.substring(0, i)
+ replacement
+ word.substring(i + 1);
count++;
}
}
Or you could just do the next:
word = word.replace(letterToReplace, replacement);
YCF_L is correct, the best way would be with replace. If you need to do things programatically for some reason, this will work:
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
System.out.println(replaceLetter(word, letter, replace));
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static String replaceLetter(String word, String letterToReplace, String replacement)
{
//Short way:
String wayOne = word.replace(letterToReplace, replacement);
//Long way:
String wayTwo = "";
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == letterToReplace.charAt(0)){
wayTwo += replacement;
} else {
wayTwo += Character.toString(word.charAt(i));
}
}
return wayOne + " VS " + wayTwo;
}

It only gives one string as the output

If I enter 3 objects
aakash
12323
aakshit
24r352
rahul
12323
If i give this as a input and enter search string as 'aa' then it gives only first string that matches the search ouput will be
aakash
12323
why not aakshit also
import java.util.Scanner;
import java.io.*;
public class DA_2_searching {
String name,phone_number;
Scanner s = new Scanner(System.in);
DA_2_searching()
{
System.out.print("Enter the Details");
name=s.nextLine();
phone_number= s.nextLine();
}
void search()
{
String search;
search=s.nextLine();
if(name.startsWith(search))
{
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[])
{
int n;
Scanner s = new Scanner(System.in);
n= s.nextInt();
DA_2_searching obj[]= new DA_2_searching[n];
for(int i=0;i<n;i++)
{
obj[i]= new DA_2_searching();
}
for(int i=0;i<n;i++)
{
obj[i].search();
}
}
}
The reason for your problem is, that you only search for one object at a time. Your for loop that calls the search() function only compares one object to a search input at a time.
In the for loop, you are only calling the search function for one DA_2_searching object (the one with index i - obj[i]). But you want to search in every DA_2_searching object you created, that means you have to rework the search() function so that it gets all DA_2_searching objects and compares them to the search-String.
Here's my solution:
import java.util.Scanner;
public class DA_2_searching {
private String name, phone_number;
private static DA_2_searching[] allPersons;
private static Scanner s = new Scanner(System.in);
public DA_2_searching() {
System.out.println("Enter the Details: ");
System.out.print("Name: ");
this.name = s.next();
System.out.print("Phone-Number: ");
this.phone_number = s.next();
System.out.println("\nNext: ");
}
public static void search() {
System.out.println("Type a word to search for: ");
String toSearch = s.next();
for(DA_2_searching person : allPersons) {
if(person.name.contains(toSearch)) { //contains is better for searching.
System.out.println("Result: " + person.name + " | " + person.phone_number);
}
}
System.out.println("\n");
if(!toSearch.equals("exit")) {
search();
}
}
public static void main(String args[]) {
System.out.print("Amount of Entries: ");
int n = s.nextInt();
System.out.println("");
allPersons = new DA_2_searching[n];
//Creating Persons
for(int i = 0; i < n; i++) {
allPersons[i] = new DA_2_searching();
}
//initializing search
search();
}
}
In your current code you search for a String in every iteration. You read in a String and check if this String equals Array[0] then you print it. Then you read in a String again and check if it is equal to Array[1]... and so on. What you want is a search in the whole Array.
A simple solution would be to read in the String before the 2nd loop and pass the
string into search();
void search(String search) {
if (name.startsWith(search)) {
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[]) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
DA_2_searching obj[] = new DA_2_searching[n];
for (int i = 0; i < n; i++) {
obj[i] = new DA_2_searching();
}
String search = new String();
search = s.nextLine();
for (int i = 0; i < n; i++) {
obj[i].search(search);
}
}

Removing a user defined element from a user defined string array [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have an assignment due in about 6 hours and I really need help. I stayed up all night working on this but I can't seem to figure it out.
Basically what I need to do is, I have a user defined array. I'm supposed to take that array and manipulate that string into a variety of things. I've gotten most of it but I can't seem to remove a user defined element in the user defined string. I've tried using a for loop to try and find the specific character that the user wants to remove but I can't seem to get it to compile or write properly. This is my code so far:
import java.util.Scanner;
import java.util.Arrays;
public class StringManipulator {
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equals("Print Reverse") || choice.equals("print reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equals("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equals("Replace Single") || choice.equals("replace single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
else if (choice.equals("Remove") || choice.equals("remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
char charRemove = ridOf2.charAt(0);
for (int i = 0; i < array.length; i++) {
if(userStr.charAt(i) != ridOf2) {
userStr += userStr.charAt(i);
}
}
}
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
The only section that i'm actually worried about at this moment is the
else if(choice.equals("Remove")
section of the code.
Give this a shot explanation further down
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equalsIgnoreCase("Print Reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equalsIgnoreCase("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equalsIgnoreCase("Replace Single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
This is the section I changed .equalsIgnoreCase compares them ignoring case as expected. Then I made sure the user only entered one char and if more ignore them. Then changed the char remove to be a string of only the first char(because you cannot replace with a char it needs to be a string) then I replaced the char to be removed in the string with nothing essentially removing it and set the user string to the new user string
else if (choice.equalsIgnoreCase("Remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
String charRemove = String.valueOf(ridOf2.charAt(0));
userStr = userStr.replaceAll(charRemove, "");//This will replace the first char the enter with nothing
}
End of section
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
String's replace should do it -
public class Test
{
public static void main(String [] args) {
String s = "Hello World";
s = s.replace(" ", "");
System.out.println(s);
}
}

Java palindrome until EOF

I have a program that is supposed to ask the user for a number and it will determine whether it is a palindrome or not. It's supposed to keep asking for numbers until EOF is input - So far it asks for the number twice and doesn't seem to be doing the while loop correctly.
Any insight is appreciated
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
String num = scanner.nextLine();
String reverse = "";
while (scanner.hasNextLine())
{
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
num = scanner.nextLine();
reverse = "";
}
System.out.println("\nProgram ended on request");
}
}
This worked for me; unless you need num or reverse outside the while loop it should work.
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
while (scanner.hasNextLine())
{
String num = scanner.nextLine();
String reverse = "";
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
}
System.out.println("\nProgram ended on request");
}
}
I would separate the palindrome test into its' own method. You could do that in a one line method like
public static boolean isPalindrome(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
but I would prefer to iterate the first half of the characters and compare them to the second half in reverse like
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i * 2 <= chars.length; i++) {
if (chars[i] != chars[chars.length - i - 1]) {
return false;
}
}
return true;
}
Then your main can invoke that in an infinite loop (terminating on the lack of input) like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number to check if it is a palindrome:");
if (!scanner.hasNextLine()) {
break;
}
String num = scanner.nextLine();
if (isPalindrome(num)) {
System.out.printf("%s is a palindrome%n", num);
} else {
System.out.printf("%s is NOT a palindrome%n", num);
}
}
System.out.println("Program ended on request");
}

Diamond Shape Based on Characters of String

I need to write a program that reads a string and then outputs a diamond shape based on the characters within the string (from user input). For example, if the user enters sample it should print the following in a diamond:
S
SAS
SAMAS
SAMPMAS
SAMPLPMAS
SAMPLELPMAS
SAMPLPMAS
SAMPMAS
SAMAS
SAS
S
I have figured out how to print the first letter of whatever the input is, do not know how to go about with the other letters. (This is for the normal triangle, I'm assuming the inverted one will be very similar.)
import java.util.Scanner;
public class PrintDiamond {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string");
String str = input.nextLine();
int l=str.length()*2-1;
int m=str.length();
for (int i=0; i<=m; i++) {
for (int j=0; j<=l; j++) {
if (j<=m-i) {
System.out.print(" ");
} else if (j==m) {
System.out.print(str.charAt(m-j));
} else if (j>=m+i) {
System.out.print(" ");
}
}
System.out.print("\n");
}
}
}
I would suggest using a Stringbuilder and a helper method to add the spaces necessary to keep a diamond shape.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string");
String str = input.nextLine();
StringBuilder sb;
int i;
for(i=1; i<=str.length(); i++){
System.out.print(addSpace(str.length()-i) + str.substring(0,i));
if(i>1){
sb = new StringBuilder(str.substring(0,i-1));
sb = sb.reverse();
System.out.print(sb.toString())
}
System.out.println();
}
for(i=str.length()-1; i>0; i--){
System.out.print(addSpace(str.length()-i) + str.substring(0,i));
if(i>1){
sb = new StringBuilder(str.substring(0,i-1));
sb = sb.reverse();
System.out.print(sb.toString())
}
System.out.println();
}
}
public static String addSpace(int x){
String s = "";
for(int i=0; i<x; i++){
s += " ";
}
return s;
}
Also something to consider: by simply reading the next line to use, you allow spaces. While this won't cause errors per say, it will contradict the idea of making a diamond shape.

Categories

Resources