Java:Why is this not possible? - java

String myName[] = {"Mouse","Laptop","Facebook","Logitech"};
// print the first character
System.out.println(myName.charAt(0));
// print the second character
System.out.println(myName.charAt(1));
// print the last character
int lastPos = myName.length() - 1;
System.out.println(myName.charAt( lastPos ));
/*any one can explain to this noob? It's telling me to change to length, but that's not what I want. Basically what I want is to go through each character of string. */

You are using String methods on an array. To access the characters in the strings, you need to first get one of the String objects sitting in that array. Doing myName[0].charAt(0) for example will give you the first character of the first String in the array. If your intention is to do something with each character in each string in the array, you should use a loop like so:
for (int i=0; i<myName.length; i++){
for (int j=0; j< myName[i].length(); j++){
myName[i].charAt(j); // Do something with ths value, I am just getting it here.
}
}

You have created an Array of Strings where each element in that array is a "String". So, you can't use charAt to the array.
charAt(index) by it's name - you can think (give me the character at position index).
So, first you need to go to the particular "String" and then say "give me the character at position 'x' ".
So, if you want to go to "Facebook", then say hey "give me the element of the array at position 3 which is index 2" using:
myName[2];
store it in say variable str which needs to be a "String" :
String str = myName[2];
Then, you can use charAt(x) on str using :
for(int i =0 ; i<str.length() ; i++){
System.out.println(str.charAt(i));
}

You have initialized an array of string.Later if u want to access them you cannot directly use myName simply. Because its a container which has many memory locations in which data is stored. So by just using myName is not possible instead it should be followed by its index (ie, myName[i] pass 0,1,2.. in place of i). See the modification of ur program below. May be u can understand it.
public class ArrayDemo {
public static void main(String[] args) {
String myName[] = {"Mouse","Laptop","Facebook","Logitech"};
for(int i=0;i<=myName.length()-1;i++){
// print the first character
System.out.println(myName[i].charAt(0));
// print the second character
System.out.println(myName[i].charAt(1));
// print the last character
int lastPos = myName[0].length() - 1;
System.out.println(myName[i].charAt(lastPos));
}
}
}

Related

Remove element from arraylist which contains all the characters of same type

What will be the best way to remove any item from the arraylist, which contains all the characters of the same type?
Please refer the example string array list data below:
Element 1: FFFFFFFF
Element 2: 123
Element 3: ABCD1234
Element 4: FFFFFFFFFFFFFFFFF
Element 5: ABCDEF
From the above data, I want to remove 1st and 4th records because they contain all the characters as "F".
What I have tried so far is explained in pseudo-code below:
1. Iterated the list till the end in a loop
2. Get the data of current element
3. Check if the element string contains all "F" characters and nothing else.
4. If yes, note the index position of current element else move to next element
5. Use second loop to remove the elements from the stored index position
6. Here I got stuck because removing an element from arraylist changes its size and index position of remaining elements
Note# It will be more helpful if the method is dynamic to supply any character(like if the element contains all "A").
You can call List.removeIf() with a regex to test for repeating characters:
listOfData.removeIf(s -> s.matches("(.)\\1*"));
To break down the regex:
. matches any character
(.) captures that first character
\1 backreferences that capture
* finds 0 or more of the same
In other words, if the string consists of only a character followed by itself n times, remove it.
If you want to test for a specific repeating character, say c, it's even easier:
listOfData.removeIf(s -> s.matches(c + "+"));
This means "match one or more instances of c". Note that this doesn't handle special characters like '('.
String s=//populate data of string here
int distinct = 1 ;
for (int j = 0; j < s.length(); j++) {
if(s.charAt(0)==s.charAt(j))
{
distinct++;
}
}
if(s.length==distinct){
//all characters are same and remove
}
If you are using Java 8, you can use List.removeIf() as #shmosel suggested. But if you want to compile your code under older java versions, try something like below.
public static void removeCharacterSetElementFromList(char character, ArrayList<String> list){
ArrayList<String> listCopy = (ArrayList<String>)list.clone();
for (String listItem : listCopy){
boolean removable = listItem.length()>0 && character==listItem.charAt(0);
for (int i = 0; i < listItem.length(); i++){
char current = listItem.charAt(i);
if (character!=current) {
removable=false;
break;
}
}
if(removable) list.remove(listItem);
}
}
Then you can simply call removeCharacterSetElementFromList('F',listOfData); to remove recodes.

Why isn't this code reversing user inputted text?

System.out.println("type something to get it back reversed...");
Scanner sc1 = new Scanner(System.in);
String x = sc1.nextLine();//user input
for(int i = x.length(); i > 0; i--)
{
System.out.print(x.substring(i));
}
In this code, I want to take user-inputted text and output it in reverse order (i.e. dog = god) with a for-loop and the substring method. The above code is non-functional.
For example...
-when I input "dog", I get "gog".
-when I input "computer", I get "rerteruterputermputeromputer"
It never outputs the first letter of the text. I'd be very grateful if somebody could help me out and explain this to me :)
See the API for the String class. The String.substring(int index) method creates a substring from the parameter index to the end of the String (so if x is dog, the x.substring(0) results in 'dog'. Perhaps you wish to use the two parameter substring method. Also note the indexes of the loop, starting at length - 1 and ending at 0
for ( int i = x.length()-1; i >= 0; i-- ){
System.out.print(x.substring(i, i+1));
}
substring(i) returns everything in your string from i to the end. To get the character at position i in a string, use charAt(i).
Also, the last index of the string is x.length()-1. The first is zero. So your loop should be something like:
for (int i = x.length()-1; i>=0; --i) {
System.out.print(x.charAt(i));
}
As copeg explained, substring() returns all characters after the character i. An easier solution would be to use charAt():
for(int i = x.length()-1; i >= 0; i--) {
System.out.print(x.charAt(i));
}

I want to print my name's letters one by one

I want to print my name's letters one by one like so:
Result:
A
Af
Afs
afsh
afsha
afshan
.....
I've tried this coding but its a simple loop and it showing my complete name.
char[]aar={'a','f','s','h','a','n'};
for(int b=0; b<1;b++){
String str=new String(aar);
System.out.println(""+str);
}
It's simple. You can use the substring method of String class.
String name="yourname";
for(int i=0;i<name.length();i++)
{
System.out.println(name.substring(0,i+1));
}
It sounds like you want to print a substring of your name on each step. So start with the complete name:
String name = "Afshan";
and then loop for as many letters as there are (using String.length() to check) and then print the substring from the start to that iteration number - use name.substring(0, i + 1) to get the relevant substring where i is the variable in the loop. Read the documentation for substring carefully to see what each of the parameters means (and why you want i + 1 rather than i).
It's important to use i in the body of the loop, otherwise you will be printing the same thing on each iteration.
I won't provide the full code here, as you're trying to learn (yay) but as an aside, try to avoid using "" + ... - in your existing code, you don't need it anyway, as str is already a string, but if you do need to convert a different type into a string, use String.valueOf(x) instead. That says exactly what you want to do, whereas concatenation with an empty string doesn't.
Here's another way using nested for-loops
char[]aar={'a','f','s','h','a','n'};
//count just from 1 to the length of array
for(int a = 1; a<aar.length; a++)
{
//print elements from 0-1, 0-2 ,0-3, and so on.
for(int b=0; b<a;b++)
{
System.out.print(aar[b]);
}
System.out.println();
}
Here is an another version.
Please use meaningful names and correct indentation.
Note that the outer for loop needs the equals. Otherwise it doesn't work.
char[] chars = {'a', 'f', 's', 'h', 'a', 'n'};
for (int length = 1; length <= chars.length; length++) {
for(int i = 0; i < length; i++) {
System.out.print(chars[i]);
}
System.out.println();
}

How to place spaces in between input textfield

I am trying to place spaces in between a number that has been entered in a textfield. I am using the following code:
for(int i = 0; i <= 2; i++)
{
char cijfer = tf1.getText().charAt(i);
char getal1 = tf1.getText().charAt(0);
char getal2 = tf1.getText().charAt(1);
char getal3 = tf1.getText().charAt(2);
}
String uitvoerGetal = getal1 + " " + getal2 + " " + getal3;
I suppose I don't understand the charAt() function yet, does anyone have a link explaining it in a way so I might be able to make this work too? Thanks in advance!
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces the following result:
a
In more Detail From java docs
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
In straight words You can't. You can't add space in int datatype because int is meant to store the integer value only. Change int to String to store the space in between.
Okay, let's see what's wrong with your code...
Your for-loop is 1-based instead of the standard 0-based. That's not good at all.
You're attempting to assign a char to a String (3 times), the first call to charAt is correct, but for some reason you then switch to using a String?
Finally you're attempting to assign a String to an int, which is just completely nonsensical.
You have a number of problems, but well done on an honest attempt.
First up, the indexes in a string are zero-based, so charAt(0) gives you the first character, charAt(1) gives you the second character, and so on.
Secondly, repeating all your calls to charAt three times is probably unnecessary.
Thirdly, you must be careful with your types. The return value from charAt is a char, not a String, so you can't assign it to a String variable. Likewise, on the last line, don't assign a String to an int variable.
Lastly, I don't think you've thought about what happens if the text field doesn't contain enough characters.
Bearing these points in mind, please try again, and ask for further help if you need it.
Try following code
String text = tf1.getText(); // get string from jtextfield
StringBuilder finalString = new StringBuilder();
for(int index = 0; index <text.length(); index++){
finalString.append(text.charAt(index) + " "); // add spaces
}
tf1.setText(finalString.toString().trim()) // set string to jtextfield

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

Categories