So i am using string.split because i need to take certain parts of a string and then print the first part. The part size may vary so I can't use substring or a math formula. I am attempting to store everything I need in the string array to then selectively print what I need based on the position, this much I can control. However, I am not sure what to do because I know when I do a split, it takes the two parts and stores them in the array. However, there is one case where I need that value in the array untouched. I'm afraid if I do
format[0] = rename
That it will overwrite that value and mess up the entire array. My question is how do I assign a position to this value when I don't know what the position of the others will be? Do I need to preemptively assign it a value or give it the last possible value in the array? I have attached a segment of the code that deals with my question. The only thing I can add is that this is in a bigger loop and rename's value changes every iteration. Don't pay to much attention to the comments, those are more of reminders for me as to what to do rather than what the code is suppose to do. Any pointers, tips, help is greatly appreciated.
String format[];
rename = workbook.getSheet(sheet).getCell(column,row).getContents();
for(int i = 0; i < rename.length(); i++) {
//may need to add[i] so it has somewhere to go and store
if(rename.charAt(i) == '/') {
format = rename.split("/");
}
else if(rename.charAt(i) == '.') {
if(rename.charAt(0) == 0) {
//just put that value in the array
format = rename;
} else {
//round it to the tenths place and then put it into the array
format = rename.split("\\.");
}
} else if(rename.charAt(i) == '%') {
//space between number and percentage
format = rename.split(" ");
}
}
Whenever you assign a variable it gets overwritten
format[0] = rename
Will overwrite the first index of this array of Strings.
In your example, the 'format' array is being overwritten with each iteration of the for loop. After the loop has been completed 'format' will contain only the values for the most recent split.
I would suggest looking into using an ArrayList, they are much easier to manage than a traditional array and you can simply just iterate through the split values and append them at the end.
Related
I'm working on a program for a class and was wondering if someone could point me in the right direction. I've worked with Java before, but it's been a while and I'm really rusty. The purpose of this program is to prompt a user to enter a phone number represented by letters (for example CALL HOME would be 225-5466), the program is then to display the phone number based on the letters entered.
We are supposed to store the letters entered by the user into an array and then convert those letters into the actual phone number. Here's what I'm getting stuck on at the moment, I've only worked with arrays consisting of numbers so am not sure how to set this one up. I'm assuming that each index would be one letter, but how would I break the string entered by the user down into individual char characters?
I'm still in the process of thinking through how this program should work and putting it on paper so haven't actually started coding yet, so I apologize for not having any code to share. But this is what I'm thinking would need to happen once the letter representation of the phone numbers were placed in the array:
Declare variables for each letter, like
int a = 1
int b = 1
int c = 1
int d = 2
etc. Or is there a more efficient way to do that? Then use if statements for each index like,
if [0] == a || b || c
[0] = 1
if [0] == d || e || f
[0] = 2
and so on. Like I said, I'm really rusty and am just trying to think my way through this right now before just throwing code at the screen haha. Any pointers would be much appreciated.
Just use String#toCharArray:
char[] characters = string.toCharArray();
You can then get the individual characters from a string.
You could use a series of if statements to see what characters map to what number. But there are more-elegant approaches. I am not sure if you have used Map<K, V>, but you could set up a Map<String, Integer> that maps a letter to its integer representation. Then you'd simply have to iterate over the characters in the string and look up their value.
Since this is homework, this is about as much information that I think is appropriate. Using what I have given you, you should be able to come up with an algorithm. Just start writing the code even if you don't know what the end result will look like. This will give you the following advantages:
Give you a clearer idea of the problem.
Will familiarize you with the problem-space.
Will help you visualize and understand your problem and the algorithm.
What you can do is to create a 2 dimensional array and methods to check the input against it. For example you can do the following:
Create an array numbers of length 10. Each index corresponds to a number you have to call.
Now each entry of the numbers array is an array of chars. So in the end you have something like this :
numbers = [['w/e you want for 0'],['a','b','c'],['d','e','f'], ['g','h','i'], ... etc ]
When you parse the input string you compare each character with a method like this:
private int letterToNumber(char c){
for(i = 0; i < numbers.length; i++)
if(contains(numbers[i], c) return i;
}
and your contains() method should be something like that
private boolean contains(char[] chars, char c){
for(char x : chars)
return(x == c)? true; false;
}
Very new to Java: Trying to learn it.
I created an Array and would like to access individual components of the array.
The first issue I am having is how to I print the array as a batch or the whole array as indicated below? For example: on the last value MyValue4 I added a line break so that when the values are printed, the output will look like this: There has to be a better way to do this?
MyValue1
MyValue2
MyValue3
MyValue4
MyValue1
MyValue2
MyValue3
MyValue4
The next thing I need to do is, manipulate or replace a value with something else, example: MyValue with MyValx, when the repeat variable is at a certain number or value.
So when the repeat variable reaches 3 change my value to something else and then change back when it reaches 6.
I am familiar with the Replace method, I am just not sure how to put this all together.
I am having trouble with changing just parts of the array with the while and for loop in the mix.
My Code:
public static String[] MyArray() {
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
return MyValues;
}
public static void main(String[] args) {
int repeat = 0;
while (repeat < 7) {
for (String lines : MyArray()) {
System.out.println(lines);
}
repeat = repeat + 1;
if (repeat == 7) {
break;
}
}
}
Maybe to use for cycle to be shorter:
for (int i = 0; i < 7; i++) {
for (String lines : MyArray()) {
// Changes depended by values.
if (i > 3) {
lines = MyValx;
}
System.out.println(lines); // to have `\n` effect
}
System.out.println();
}
And BTW variables will start in lower case and not end withenter (\n). So use:
String myValues[] = {"MyValue1", "MyValue2", "MyValue3", "MyValue4"};
instead of:
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
and add System.out.println(); after eache inside cycle instead of this:
MyValues[n] = "value";
where n is the position in the array.
You may consider using System.out.println() without any argument for printing an empty line instead of inserting new-line characters in your data.
You already know the for-each loop, but consider a count-controlled loop, such as
for (int i = 0; i < lines.length; i++) {
...
}
There you can use i for accessing your array as well as for deciding for further actions.
Replacing array items based on a number in a string might be a bit trickier. A regular expression will definitely do the job, if you are familiar with that. If not, I can recommend learning this, because it will sure be useful in future situations.
A simpler approach might be using
int a = Integer.parseInt("123"); // returns 123 as integer
but that only works on strings, which contain pure numbers (positive and negative). It won't work with abc123. This will throw an exception.
These are some ideas, you might try out and experiment with. Also use the documentation excessively. ;-)
I wanted to optimize my code, so instead of copying my entire char array for each iteration in the alphabet, I opted to do the copying beforehand and then I'd just add chars into the copy.
E.g.:
copy "lord" (i=0)
modify the first letter (aord, bord, cord &c)
copy "lord" (i=1)
modify the second letter (lard, lbrd, lcrd &c)
&c
for (int i = 0; i < wordLength; i++) {
Word moddedWord = new Word(Arrays.copyOf(temp.word.content, wordLength));
for (int c = 0; c < alphabetLength; c++) {
if (alphabet[c] != temp.word.content[i]) {
// Word moddedWord = new Word(Arrays.copyOf(temp.word.content, wordLength));
moddedWord.content[i] = alphabet[c];
Word res = WordList.Contains(moddedWord);
if (res != null && WordList.MarkAsUsedIfUnused(res)) {
WordRec wr = new WordRec(res, temp);
q.Put(wr);
}
}
}
}
However, when I do this small change, my program doesn't work, when it used to when I instead used the commented line for copying. I've debugged this for hours on end now and I can find nothing that changes this, I've tried various forms of copying, I've tried storing the "original" word as a String and then converting it to a char array when I need to copy it, nothing seems to work. Oh by the way, "Word" is just a wrapper for char[] (Word.content is a char[] field).
You can't avoid copying if you want to store each modification of the word. Here:
new WordRec(res, temp);
you create a word record based on the mutable instance of the word and then you keep changing that one instance. You'd need to copy temp inside this constructor. So the best you achieve is copying a bit later, possibly a bit less due to the "ifology" within which it happens.
Now, if you really want to improve performance, then rework the WordList to be a WordSet and have O(1) lookup time with the Contains method.
A final note: please respect the Java naming conventions. Methods start with a lowercase letter.
I have a list of names in an array, and there is some redundancy in it. I was able to get only unique names to print, but I need a way to print the first line, skip the printing however many times there was a redundancy, then continue printing the next name (all redundant instances were always next to eachother). Here is what I have for that part so far:
int x = 1;
int skipCount = 0;
while (x<i){
if (titles[x].length() == titles[x-1].length()){
//do nothing
skipCount++;
}
else{
System.out.printf("%s\n", titles[x]);
}
x++;
}
So basically, how would I go about skipping the else statement 'skipCount' times, then have it start again? I haven't found much about this and am relatively new to java.
Why not just use a Set? ;-)
final Set<String> set = new HashSet<>(Arrays.asList(titles));
for (final String title : set) {
/* title is unique */
System.out.println(title);
}
Some of the changes include using println rather than printf("%s\n", ...), which is just clearer, and using an enhanced for loop, instead of manually tracking the position in the array in a loop.
To be honest, you might consider using a Set<String> in place of String[] for titles in the first place.
I'm used to python and django but I've recently started learning java. Since I don't have much time because of work I missed a lot of classes and I'm a bit confused now that I have to do a work.
EDIT
The program is suppose to attribute points according to the time each athlete made in bike and race. I have 4 extra tables for male and female with points and times.
I have to compare then and find the corresponding points for each time (linear interpolation).
So this was my idea to read the file, and use an arrayList
One of the things I'm having difficulties is creating a two dimensional array.
I have a file similar to this one:
12 M 23:56 62:50
36 F 59:30 20:60
Where the first number is an athlete, the second the gender and next time of different races (which needs to be converted into seconds).
Since I can't make an array mixed (int and char), I have to convert the gender to 0 and 1.
so where is what I've done so far:
public static void main(String[] args) throws FileNotFoundException {
Scanner fileTime = new Scanner (new FileReader ("time.txt"));
while (fileTime.hasNext()) {
String value = fileTime.next();
// Modify gender by o and 1, this way I'm able to convert string into integer
if (value.equals("F"))
value = "0";
else if (value.equals("M"))
value = "1";
// Verify which values has :
int index = valor.indexOf(":");
if (index != -1) {
String [] temp = value.split(":");
for (int i=0; i<temp.length; i++) {
// convert string to int
int num = Integer.parseInt(temp[i]);
// I wanted to multiply the first number by 60 to convert into seconds and add the second number to the first
num * 60; // but this way I multiplying everything
}
}
}
I'm aware that there's probably easier ways to do this but honestly I'm a bit confused, any lights are welcome.
Just because an array works well to store the data in one language does not mean it is the best way to store the data in another language.
Instead of trying to make a two dimensional array, you can make a single array (or collection) of a custom class.
public class Athlete {
private int _id;
private boolean _isMale;
private int[] _times;
//...
}
How you intend to use the data may change the way you structure the class. But this is a simple direct representation of the data line you described.
Python is a dynamically-typed language, which means you can think of each row as a tuple, or even as a list/array if you like. The Java idiom is to be stricter in typing. So, rather than having a list of list of elements, your Java program should define a class that represents a the information in each line, and then instantiate and populate objects of that class. In other words, if you want to program in idiomatic Java, this is not a two-dimensional array problem; it's a List<MyClass> problem.
Try reading the file line by line:
while (fileTime.hasNext())
Instead of hasNext use hasNextLine.
Read the next line instead of next token:
String value = fileTime.next();
// can be
String line = fileTime.nextLine();
Split the line into four parts with something as follows:
String[] parts = line.split("\\s+");
Access the parts using parts[0], parts[1], parts[2] and parts[3]. And you already know what's in what. Easily process them.