I hope the evening finds you well. My problem tonight is that I'm trying to create a char array, but I can't use any of the good ways to do it. I can only use String.length and String.charAt() my code is a miserable sad mess. This kind of combines all the things I've ever been terrible at so far.
Ultimately what I'll be trying to do is find a way to insert, delete, and replace things given certain indexes of a user-input string, but one step at a time, right?
This is what I have right now for my insert method, it's not even close to done obviously. All I'm really trying to figure out here, is how to print out my array, because when I try to print it out right now its just printing blanks. I apologize for my ineptitude.
public String insert_text(String fromtest){
System.out.println(fromtest.length());
System.out.println(fromtest);
for(int i=0;i<fromtest.length();i++){
text=new char[fromtest.charAt(i)];
System.out.println(text[i]);
}
System.out.println("* Enter the starting position:");
int startpos=k.nextInt();
System.out.println("* Enter the text you want to insert:");
String instring=k.next();
return fromtest;
}
I'm not sure why, but the prompt just say that the only things we can use are Sting.Length and String.charAt and store them to an array which I forgot to mentioned should be private char [] text.
String.toCharArray() is the function that you are looking for. It converts the String into equivalent Char array.
Convert an input String to char[] as the following sample code:
public static void main(String args[])
{
String str = "Sameer";
char[] cArray = str.toCharArray();
//Now perform functions with your charArray
}
Hope this helps.
Why can't you use
char [] input = fromtest.toCharArray(); // get's the character array as called...
if you can't use toCharArray you could try
char [] array = new char[fromtest.length()];
for (int i = 0; i < fromtest.length(); i++) {
array[i] = fromtest.charAt(i);
}
You can print each char by :
System.out.println(fromtest.charAt(i));
public String insert_text(String fromtest){
Char[] charArray = fromtest.toCharArray();
// do whateveryou want;
return fromtest;
}
So far i understand your problem is you need to make dynamic array of what String is passed in this function,
use char[] charArray = string.toCharArray();
but what you are doing i prefer you stack and queues
Related
I want to reverse a string. I know there are some other methods to do it but I wanted to do in a different way. There is no error but no output when I run my code. I dont understand why "String.valueOf(word.charAt(i)" doesnt return a value? Am I missing something?
String word = "myword";
for (int i = word.length(); i <= 0; i--) {
System.out.print(String.valueOf(word.charAt(i)));
}
The first value of i is out of index. And I also fixed your code. Check below:
String word = "myword";
for(int i=word.length()-1;i>=0;i--){
System.out.print(String.valueOf(word.charAt(i)));}
Just for providing another slightly different solution:
You can use a StringBuilder to reverse a String using its method reverse().
If you have a String, you can use it to initialize the StringBuilder with it and directly reverse it.
This example additionally uses an enhanced for-loop, which always goes through all of the elements. Using that, you can get rid of checking the length of a String and you won't have to use an int i for iterating.
For your requirements, this is a suitable option because you want to reverse the whole String.
String word = "myword";
for (char c : new StringBuilder(word).reverse().toString().toCharArray()) {
System.out.println(c);
}
Note that you can use the reverse() method for printing the reversed word in one line just doing
System.out.println(new StringBuilder(word).reverse().toString());
Your code has 2 issues.
i should be initialized with word.length()-1. Other wise you will get StringIndexOutOfBoundsException
for loop condition should be >= 0.
Below is the corrected code.
String word = "myword";
for(int i=word.length()-1;i>=0;i--) {
System.out.print(word.charAt(i));
}
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)
I have to take a string and convert the string to piglatin. There are three rules to piglatin, one of them being:
if the english word starts with a vowel return the english word + "yay" for the piglatin version.
So i tried doing this honestly expecting to get an error because the startsWith() method takes a string for parameters and not an array.
public String pigLatinize(String p){
if(pigLatRules(p) == 0){
return p + "yay";
}
}
public int pigLatRules(String r){
String vowel[] = {"a","e","i","o","u","A","E","I","O","U"};
if(r.startsWith(vowel)){
return 0;
}
}
but if i can't use an array i'd have to do something like this
if(r.startsWith("a")||r.startsWith("A")....);
return 0;
and test for every single vowel not including y which would take up a very large amount of space, and just personally I would think it would look rather messy.
As i write this i'm thinking of somehow testing it through iteration.
String vowel[] = new String[10];
for(i = 0; i<vowel[]; i++){
if(r.startsWith(vowel[i]){
return 0;
}
I don't know if that attempt at iteration even makes sense though.
Your code:
String vowel[] = new String[10];
for(i = 0; i<vowel[]; i++){
if(r.startsWith(vowel[i]){
return 0;
}
}
Is actually really close to a solution that should work (assuming you actually put some values in the array).
What values do you need to put in it, well as you mentioned you can populate the array with all the possible values for vowels. Those of course being
String[] vowel={"a","A","e","E","i","I","o","O","u","U"};
now you have this you would want to loop (as you worked out) over the array and do your check:
public int pigLatRules(String r){
final String[] vowels={"a","A","e","E","i","I","o","O","u","U"};
for(int i = 0; i< vowels.length; i++){
if(r.startsWith(vowels[i])){
return 0;
}
}
return 1;
}
There are some improvements you can make to this though. Some are best practice some are just choice, some are performance.
As for a best practice, You are currently returning an int from this function. You would be best to change the result of this function to be a boolean value (I recommend looking them up if you have not encountered them).
As for a choice you say you do not like having to have an array with the upercase and lowercase vowels in. Well here is a little bit of information. Strings have lots of methods on them http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html one of them is toLowerCase() which as you can guess lowercases a whole string. if you do this to the work you pass in to your function, you cut the amount of checks you need to do in half.
There is lots more you cam get into but this is just a little bit.
Put all those characters in a HashSet and then just perform a lookup to see if the character is valid or not and return 0 accordingly.
Please go through some example on HashSet insert/lookup. It should be straightforward.
Hope this helps.
Put all the vowels in a string, grab the first char in the word you are testing and just see if your char is in the string of all vowels.
Newbie question comming up. Trying to get my head around JAVA.
How do I print out the content of the reference and not just their postition ? My program is ment to get some text in from the user, and print it out in a reverse order.
Here is my program (so far):
package myProgram;
import javax.swing.JOptionPane;
public class someRandomClass {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Write som text here");
StringBuilder outPut = new StringBuilder();
for (int i = word.length()-1; i>=0; i--){
outPut.append(i);
}
System.out.println(outPut.toString());
}
}
I am greatfull for any help and tips! :)
In the line
outPut.append(i);
you are appending the value of your loop counter. You surely mean
outPut.append(word.charAt(i));
You seem to appending the integers instead of the appropriate characters. Try this instead:
outPut.append(word.substring(i, i + 1))
This way, the individual characters of word are appended to your StringBuilder. Note that the append method could also take a char as an argument, so you are also able to use word.charAt(i).
So, you want to emit the character at the position? Try using String.charAt.
outPut.append(word.charAt(i));
I'd probably avoid that and just index the char[] from String.toCharArray, though.
To be honest, I'd avoid doing the reversal loop manually to begin with... try something as follows:
final String word = JOptionPane.showInputDialog("Enter text below");
System.out.println(new StringBuilder(word).reverse());
StringBuilder.reverse should do the work for you (likely in a more efficient way, too). You also don't need to call toString manually, as println will do that for you.
I have to do this for an assignment in my java class. I have been searching for a while now, but only find solutions with regex etc.
For my assignment however I may only use charAt(), length() and/or toCharArray(). I need to get from a string like gu578si300 for example just the numbers so it will become: 578300.
i know numbers are 48 - 57 in ASCII but i can't figure out how to do this in java. You guys any ideas?
i was thinking about a for loop that checks whether the (int) char is between 48-57 en if so puts the value into a seperate array. Howeevr i dont know how to programm that last thing.
I now have this;
public static String filterGetallenreeks(String reeks){
String temp = "";
for (char c : reeks.toCharArray()) {
if ((int) c > 47 && (int) c < 58)
temp += c;
}
return temp;
however it is not working, it just outputs the same as goes in.
is it something in my mainm which looks like this. If i'm right the return temp; will return the temp string into the reeks string in the main right? why is my input still the same a sthe output?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Voer een zin, woord of cijferreeks in:");
String reeks = sc.nextLine();
if (isGetallenreeks(reeks)){
System.out.println("is getallenreeks");
filterGetallenreeks(reeks);
System.out.println(reeks);
}
Since this is homework I will not be providing the complete solution, however, this is how you should go about it:
Do a for loop that iterates for the total amount of characters within the string (.length). Check if the character is a digit using the charAt and isDigit methods.
You could do a loop that checks a character in the string, and if it's a number, append it to another string:
//I haven't tested this, so you know.
String test = "gu578si300 ";
String numbers = "";
for(int i=0; i<test.length(); i++){
if("0123456789".indexOf(test.charAt(i)) // if the character at position i is a number,
numbers = numbers + test.charAt(i); // Add it to the end of "numbers".
}
int final = Integer.parseInt(numbers); // If you need to do something with those numbers,
// Parse it.
Let me know if that works for you.
It seems like a reasonable approach, but I'd make a couple of changes from what you suggested:
If you need to result as a string then use a StringBuilder instead of an array.
Use character literals like '0' and '9' instead of ASCII codes to make your code more readable.
Update
The specific problem with your code is this line:
temp = temp + (int)c;
This converts the character to its ASCII value and then converts that to a decimal string containing the ASCII value. That's not what you want. Use this instead:
temp += c;