This question already has answers here:
Why does String.replace not work? [duplicate]
(3 answers)
Closed 4 years ago.
Whenever I run the java code below it compiles but the line that include the replace method seems to be skipped, such so that the inputted string and the output (newMessage) are the same. Why? variable C and variable D are chars...
import java.util.Scanner;
public class javaencrypt
{
public static void main(String[] args)
{
// define and instantiate Scanner object
Scanner input = new Scanner(System.in);
//prompt user to enter a string
System.out.println("Please enter a string: ");
String message = input.nextLine();
String newMessage = message;
char c=' '; // the character at even locations
char d=' '; // new character
// go throughout the entire string, and replace characters at even positions by the character shifted by 5.
// access the even characters with a for loop starting at 0, step 2, and ending at length()-1
// for( initial value; maximum value; step)
for(int k=0; k<message.length(); k=k+2)
{
c=message.charAt(k);
d=(char)(c+5);
/*
there will always be characters available, because keyboard is mapped on ASCII which is in the beginning of UNICODE
*/
newMessage.replace(c,d);
}
System.out.println("Message replacement is: " + newMessage);
}
}
In Java, Strings are immutable.
An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified.
When you call newMessage.replace(c, d); this does not update newMessage, but rather creates a new String with all chars c replaced with d instead. If you want newMessage to change to include the replacing of c to d, then you need to reassign the variable. This would look like newMessage = newMessage.replace(c, d);
Related
I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.
First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t
I have a script that is supposed to take a String of both numbers and letters and break them down into their ASCII/Hex values under the appropriate column. It works flawlessly until I put a space anywhere in the String. It will print everything normally up to the space and then break with no errors.
Ex. (works):
kdillon76
Ex. (does NOT work):
kdillon 76
In my For Loop I have an If Statement stating that if the character is a digit then "do this" followed by an Else Statement to cover anything "else". Shouldn't the Else Statement be able to translate the space to the "32" ASCII number?
Any and all help is greatly appreciated!
import java.util.*; // Load all Utility Classes
public class DKUnit3Ch12 { // Begin Class DKUnit3Ch12
public static void main(String[] args) { // Begin Main
Scanner myScan = new Scanner(System.in); // Initialize the Scanner
String myInput; // Define a new Variable
System.out.print("Please enter a string of any length: "); //Print the text
myInput = myScan.next(); // Define a new Variable with the next user input
System.out.printf("%n%-8s%-16s%-16s%s%n", "Initial", "ASCII(char)", "ASCII(int)", "Hex"); // Print the labels with proper tablature
for(int x = 0; x < myInput.length(); x++) { // Begin For Loop
char myChar = myInput.charAt(x); // Define a new Variable based on position in index
if(Character.isDigit(myChar)) { // Begin If Statement (if the character is a digit)
System.out.printf("%-24s%-16d%02X%n", myChar, (int)myChar, (int)myChar); // Print the items with proper tablature including capitalized Hex
} // End If Statement
else { // Begin Else Statement (if the character is NOT a digit)
System.out.printf("%-8s%-32d%02X%n", myChar, (int)myChar, (int)myChar); // Print the items with proper tablature including capitalized Hex
} // End Else Statement
} // End For Loop
System.out.print("\nThank you for playing!"); // Print the text
myScan.close(); // Close the Scanner
} // End Main
} // End Class DKUnit3Ch12
From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Replace myScan.next() with myScan.nextLine()
I'm trying to take user input and put it into a character array and then print it out.... It's part of a bigger program and since i'm a new coder, I was hoping if you could keep the program simple without....
I get the error "Array index out of bounds". I tried changing the length of the array but that still didn't work.
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] ToEdit = new char [];
Scanner sc = new Scanner(System.in);
for (int i=0; i<5; i++)
{
System.out.println(i + ":");
ToEdit[i] = sc.next().charAt(i);
}
System.out.println(ToEdit);
}
Thank you
The problem lies here: char[] ToEdit = new char [];.
On that line, you are creating an empty array without a size. You would need to change it to : char[] ToEdit = new char [5];.
Further more, you will need to change this: ToEdit[i] = sc.next().charAt(i); to this: ToEdit[i] = sc.next().charAt(0);. The problem with your current line is that even if you enter 1 character, your code will look for more.
As a side note, it would be recommended that you extract the number 5 as a variable. This will allow you to increase or decrease the amount of characters your program can process by changing just one location.
As a further excercise, you can take a look at lists and see how you can make your program more flexible, without having to define a size for the array.
This wont compile as you need to add char array length first:
char[] ToEdit = new char[5];
Then this code ToEdit[i] = sc.next().charAt(i); produces String array out of bound exception. Because charAt(i) each time find char at 0,1,2,3,4 and so on position in string as shown below (the output of your program). So you need to change this to ToEdit[i] = sc.next().charAt(0);
0:
abcde
1:
acx
2:
acv
3:
acvff
4:
acdcdvc
acvfd
The way the program is supposed to work initially is to ask the user to input a string, followed by a character and then tests whether the string starts with that character. The case of the character should be irrelevant. I have had a good go myself it runs but doesn't meet specifications. For example when I run it and type "HELLO" as the first input and the second input is the character "h" lowercase it does not say true. Even though "h" is lowercase I still want my program to take it in to account. I am new to using objects of string with methods. I want the program to ignore the case.
import java.util.*;
public class Page189Question2aAnd2b
{
public static void main(String[] args)
{
String a = new String();
String b = new String();
System.out.println("Input a string:");
a = EasyScanner.nextString();
a.equalsIgnoreCase(a);
System.out.println("Enter a single character ");
b = EasyScanner.nextString();
b.equalsIgnoreCase(b);
if(a.startsWith(b))
{
System.out.println(a.startsWith(b));
//System.out.println(a.equalsIgnoreCase(b));
}
}
}
equalsIgnoreCase just returns a boolean, which indicates, whether two strings are equal if the case of the strings is not considered.
What you need is
String aLower = a.toLowerCase();
String bLower = b.toLowerCase();
if(aLower.startsWith(bLower))
{
// do something
}
That way you just convert both strings to lower case to compare them afterwards.
Try this :
System.out.println((a.toLowerCase()).startsWith(b.toLowerCase()));
So I want to know what indexOf() does. As I want to use it in my program it find out how many vowels are in a word that the user inputs.
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1;
}
But that doesnt seem to work at all hahah. as I have no idea what indexOf() actually does. anyway here is my program so far(sorry if its bad I'm really new). I left 5 questions too that would help me a lot! please and thank you for your help :D
import java.util.Scanner;
public class vowelCounter {
private static String input = methodInput(); //1. is there any other way to make a global Scanner?
public static void main(String[] args){
System.out.println("Enter word");
System.out.println(input);
System.out.println("This word has" + methodCheck('a')); //2. what should i put in my parameters?
}
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1; //3. what does this line do?
}
public static String methodInput(){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
return input;
//4. the output is 'hastrue' why is that?
//5. how can i make this program better?
}
}
If you don't know what a method does, then the solution is to go look at what it does. For example, the java documentation will tell you that
public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character
In either case, if no such character occurs in this string, then -1 is returned.
How you're using it is not necessarily wrong, considering how the method returns -1 if the character wasn't found. But if you want to check how many vowels there are in a word that the user enters, it wouldn't be right to check whether the word they entered is in the string of vowels.
All the standard Java libraries, classes and methods have Javadoc that describes what they do.
All you need to do is look up the Javadoc and they describe it.
In this case the Javadoc is at: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
Your first step with any question like this should always be the documentation, then if that doesn't work try doing a web search looking for examples. For example 5 seconds on google putting in "java indexOf example" found me:
http://www.tutorialspoint.com/java/java_string_indexof.htm
Then if that doesn't work you can try asking the question here.
When you have the word boolean before the name of a method, that means that the method will return either the value true or the value false. And it's this true or false value that your program is printing out, on the same line as "This word has".
This particular method will return true if the character you pass to it is a vowel, or false otherwise. The method indexOf tells you which character of a String is the first one that is equal to the value that you pass in to the method. It returns 0 for the first character, 1 for the second character and so on. It returns -1 if none of the characters match. In this case, you're just checking whether the value returned by indexOf is or isn't -1 - in other words, whether the character is or isn't in the String "AEIOUaeiou".
indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. If no such value of str exists, then -1 is returned.
For examples :
int num1 = "AEIOUaeiou".indexOf("a"); // it gives 5
int num2 = "AEIOUaeiou".indexOf("A"); // It gives 0
int num3 = "AEIOUaeiou".indexOf("z"); // It gives -1
1 Don't do that! Create a scanner in main, read input with it and then call your method(s).
2 How about countVowels(input)? You'd need to write an static int countVowels(String input) method.
3 Returns true since you pass in 'a'.
4 See number 3.
5 See number 2, and add a static boolean isVowel(char a).
Here is what the indexOf method does
string.indexOf(searchvalue,start)
Parameters
searchvalue : Required. The string to search for
start : Optional. Default 0. At which position to start the search
Return Value
Number : The position where the specified searchvalue occurs for the first time, or -1 if it never occurs
In simple terms, the index of method checks the first occurence of the value passed to it from the start position(if specified) and returns the position at which the value was first encountered in the string.
eg.
String s = "AEIOUaeiou";
s.indexOf("a"); //This would get a value of 5.
s.indexOf("v"); //This would get a value of -1, since it doesn't have the character v
To answer your questions,
You can directly declare the scanner as private and use it in the
entire program
`private static Scanner input = new Scanner(System.in);`
you can write a method that receives the String input by the user
and then checks if the String contains any of the vowels. You can
use indexOf or contains methods to check for the each vowel using
the indexOf method.
Already described above.
A better way to do it would be as follows.
public class vowelCounter{
public static void main (String[] args) {
Scanner keyboard = new Scanner (System.in); // No need to declare it as global. You use it only once.
System.out.println ("Enter word : "); //Prompt the user to enter a word
String input = keyboard.nextLine (); //Fetch the word that the user enters into a String
System.out.println ("This word has" + countVowel (input)); // Pass the string to the method to check if it has vowels.
}
private static int countVowel (String a) {
int count = 0;
String s = a.toLowerCase (); // convert the string to lower case so that you only have to check for the lower case characters
// Here you would need to check the number of times each vowel exists in the String and incremenet the count everytime.
return count;
}
}