Comparing List<String> to String [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been having a bit of an issue with my assignment. After reading from an input.txt file, I've created an array in which all of the information has been stored in, but for some reason I seem to be unable to compare them individually. I've tried equals() and contains() I can't think of anything else that would work. what I'm trying to achieve.
public static void readFromFile(String filePath) throws IOException{
BufferedReader inputFile = new BufferedReader(new FileReader(filePath));
String inputText = null;
List<String> list = new ArrayList<String>();
String[] splited = null;
//splitting the text file
while((inputText = inputFile.readLine())!= null) {
splited = inputText.split("[;^:]");
for (String part : splited) {
list.add(part);
}
}
String [] stockArr = list.toArray(new String[list.size()]);
// verify contents of array
for(int index = 0; index < stockArr.length;index++) {
System.out.println(stockArr[i]);
}
for (int i = 0; i > stockArr.length; i++) {
if(stockArr[i].equals("BusinessContact")) {
System.out.println("test");
}
}
}
Now if I were to print this, it does not print "test" but rather only
BusinessContact
firstName=Victor
middleName=Garces
lastName=Guana
Address
addressType=WORK
streetName=Athabasca Hall
streetNumber=2-32
apartmentNumber=4-52
city=Edmonton
postalCode=T6G 2E8
country=Canada

Check your run-condition for the second for-loop:
for (int i = 0; i > stockArr.length; i++){
if(stockArr[i].equals("BusinessContact")){
System.out.println("test");
}
}
I think you rather meant
for (int i = 0; i < stockArr.length; i++){
if(stockArr[i].equals("BusinessContact")){
System.out.println("test");
}
}

The last for loop should have a < in its condition:
for (int i = 0; i < stockArr.length; i++){

Related

Replace non-digit characters from an array of String and return a String Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
I need to replace non-digit characters from an array of String and return a String with digits separated by coma, actually, I made it but don't like it.
The first thing I made, was added values from the String array to the String.
Then I replaced non-digit characters from a String.
After that, I added digit values to an int array and sorted it.
Then I added all this stuff to an array of strings and separated values with commas, after that I returned it.
I would be glad for advice, thanks for attention.
import java.util.Arrays;
class Test {
private static String sortedStringOfNumber(String[] string) {
StringBuilder temp = new StringBuilder();
for (String s: string) {
temp.append(s);
}
String numberOnly = temp.toString().replaceAll("[^0-9]", "");
int[] numbers = new int[numberOnly.length()];
for (int i = 0; i < numberOnly.length(); i++) {
numbers[i] = numberOnly.charAt(i) - '0';
}
Arrays.sort(numbers);
String[] result = new String[numbers.length];
for (int i = 0; i < numbers.length; i++) {
result[i] = String.valueOf(numbers[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
sb.append(result[i].toString());
if (i != result.length - 1)
sb.append(", ");
}
return sb.toString();
}
public static void main(String[] args) {
String[] arrayStringData = new String[] { "1", "ab3c", "level", null, "java2s.com", "asdf 456", "Br0C0de" };
//Should be "0, 0, 1, 2, 3, 4, 5, 6"
System.out.println("Sorted string of numbers ->\t" + sortedStringOfNumber(arrayStringData));
}
}
Your solution would run in O(n*log n) mainly due to Arrays.sort.
Use a simple counting sort. This would give you a runtime of O(n).
Look at the string and ignore all other non-digits.
You might also try it this way:
String sortedIntsCsv = Arrays.stream(string).map(s -> s.replaceAll("\\D", "")).mapToInt(Integer::valueOf).sorted().mapToObj(String::valueOf).collect(Collectors.joining(","));

Blank Screen after launching/debugging ArrayList exercise in Eclipse [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm learning ArrayList in Java. I'm trying to add and print elements in an Array with various methods. Trying to run or compile the above code results in 2 "placeholder" print and the console hanging when trying to set String = Scanner value. What's wrong? Here's the code:
public class Arraylist {
private ArrayList<String> list = new ArrayList<>();
public void addIt(String str) {
list.add(str);
}
public String toStrings() {
int i = list.size();
String prova = new String();
while ((i < list.size()) && (i >= 0)) {
prova = list.get(i);
i--;
}
return prova;
}
public static void main(String args[]) {
Arraylist ciccio = new Arraylist();
Scanner in = new Scanner(System.in);
System.out.println("Placeholder");
String str;
System.out.println("Placeholder");
str = in.next();
System.out.println("Placeholder");
while (!str.equals("bye")) {
System.out.println("Add new values");
ciccio.addIt(in.next());
}
System.out.println("Printing");
String str2;
str2 = ciccio.toStrings();
in.close();
}
}
It will never enter the while. i should start on list.size() - 1 not list.size(). Also, you might want to append to that string, not replace it.
public String toStrings() {
int i = list.size() - 1;
String prova = new String();
while ((i < list.size()) && (i >= 0)) {
prova += list.get(i);
i--;
}
return prova;
}
Also, it will never exit this loop since str is only assigned once.
while (!str.equals("bye")) {
System.out.println("Add new values");
ciccio.addIt(in.next());
}
Fix:
boolean control = true;
while (control) {
System.out.println("Add new values");
String temp = in.next();
if (temp.equals("bye"))
control = false;
else
ciccio.addIt(temp);
}

Split Strings, Search and Translate Substrings JAVA [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm pretty new to Java, and I need to solve this problem for an assignment. Can anyone help me please?
The problem is we need to enter a String like "AUGUUUUCU" and then split it into three letter strings like "AUG", "UUU", "UCU".
After that I would have to iterate over these and translate them to "AUG = METIONINA", "UUU = FENILANINA", "UCU = SERINA". Can anyone help me with this?
I already found a way to split them:
public class Main {
public static void main(String[] args) {
String str = "AUG-UUU-UCU";
String delimiter = "-";
String[] temp;
temp = str.split(delimiter);
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
}
}
If you're supposed to take user input, then you'll need to use a Scanner:
Scanner sc = new Scanner(System.in);
String input = sc.next();
To split it into three-letter Strings, use an array and store the substrings in the array using a for loop:
String[] subs = new String[input.length()/3];
int index;
for (int i=0; i<input.length(); i++) {
index = i*3;
subs[i] = input.substring(index, index+3);
}
You could then iterate over the array with another for loop and use a switch statement to determine the correct output:
for (int i=0; i<subs.length; i++) {
switch(subs[i]) {
case "AUG":
System.out.println("METIONINA");
break;
case "UUU":
System.out.println("FENILANINA");
break;
case "UCU":
System.out.println("SERINA");
break;
default:
break;
}
}
Note the break statements within the switch block. These are important to include; without break statements, it will simply execute all code after the matching case.
You could create an array that holds the values that are to be translated.
translateArray = new String[3];
Then you could set the values of the parallel array based on the input you receive. Then you could post those values.
for (int i=0; i<temp.length ; i++) {
if (temp[i] == "AUG" ) {
translateArray[i] = "METIONINA";
}
if (temp[i] == "UUU") {
translateArray[i] = "FENILANINA";
}
if (temp[i] == "UCU") {
translateArray[i] = "SERINA";
}
System.out.println(temp[i] + " = " + translateArray[i]);
}
Maybe that will work better for you.
To split a string into strings 3 chars long is 1 line:
String[] words = str.split("(?<=\\G...)");

Converting an String array into char array to compare it with another text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Given two files
random_letters.txt
AABBBBB
FLOWERS
BACKGFD
TOBEACH
dictionary.txt
flowers
to
beach
back
I need to check each combination of the random_letters with dictionary to see if there is anything common. it can be a word with at least 6 characters or two words that equal at least 6 characters. Which would make it FLOWERS or TOBEACH.
I am having a tough time figuring out what I need to do. I can get it to work for words with 7 characters because I used strings. I understand I need to use char in order for it to work.
what I have so far:
public static void compare() {
private static String stringToWrite2 = "";
private static String[] allWords = new String[2187];
private static String[] diction = new String[79765];
private static char[][] test = new char[2187][7];
private static char[][] test2 = new char[79765][7];
public static void main(String args[])
try {
Scanner file1 = new Scanner(new File("random_letters.txt"));
Scanner file2 = new Scanner(new File("dictionary.txt"));
for(int i = 0; i < 2187; i++) {
allWords[i] = file1.next();
test[i] = allWords[i].toCharArray();
}
for(int i = 0; i < 79765; i++) {
diction[i] = file2.next();
diction[i] = diction[i].toUpperCase();
test2[i] = diction[i].toCharArray();
}
for(int i = 0; i < 2187; i++) {
for (int j = 0; j < 79765; j++) {
if(allWords[i].equals(diction[j])) {
stringToWrite2 += diction[j];
}
}
}
} catch (IOException e) {
System.out.println("could not find file");
}
System.out.println("-------------------");
System.out.println(stringToWrite2);
for(int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++)
System.out.println(test2[i][j]);
}
}}
You have two somewhat distinct tasks here: determining if there are any words in dictionary that are also in random_letters (of length >= 6), and determining if there are any sets of two words in dictionary such that their union is a word in random_letters.
Instead of using an array, let's use HashSets for storage, because the single most used operation here will probably be .contains(...). It also gives us access to .retainAll(...), which is very useful for finding intersections.
For the second half of the task, my initial thought was to create a data structure with all of the pairwise permutations of words in diction, and intersect that with allWords. I quickly realized how big that would (likely) become. Instead I used an uglier but more space efficient solution.
private static HashSet<String> allWords = new HashSet<String>();
private static HashSet<String> diction = new HashSet<String>();
public static void compare() {
try {
Scanner file1 = new Scanner(new File("random_letters.txt"));
Scanner file2 = new Scanner(new File("dictionary.txt"));
for(int i = 0; i < 2187; i++) {
allWords.add(file1.next());
}
for(int i = 0; i < 79765; i++) {
diction.add(file2.next().toUpperCase());
}
//Compile set of words that are in both
HashSet<String> intersect = new HashSet<String>();
intersect.addAll(allWords);
intersect.retainAll(diction);
for (String s : intersect){
System.out.println(s);
}
//For every word in random_letters, see if there is a word in diction that is the start of it
HashSet<String> couplesIntersect = new HashSet<String>();
for(String s : allWords){
for(String d : diction){
if(s.startsWith(d)){
//If so, check every word in diction again to see if there is a word that is the remainder
String remainder = s.subString(d.length());
for(String d2 : diction){
if(d2.equals(remainder))
//If so, store this word
couplesIntersect.add(s);
}
}
}
}
//Print those results
for (String s : couplesIntersect){
System.out.println(s);
}
} catch (IOException e) {
System.out.println("could not find file");
}
}
}

How can i read 1,A,5,B with scanner and put it while reading in a string and an int vector in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So, i have this input at once:
1,A,5,B,10,A,8,A,17,B,17
I have these 2 lists:
String[] bidderName = new String[100];
int[] bidValue = new int[100];
I want, as i read this at once, to be able to store the numbers(1,5,10 etc.) in the bidValue list, and the names(A,B, etc.) in the biddername list.
How can i do this using java.util.Scanner, or anything else?
Than you in advance. Respects!
I assume that the letters are the bidder names,
and that your input starts with a bidder name.
public class Test055 {
public static void main(String[] args) {
String input = "A,5,B,10,A,8,A,17,B,17,B,1";
String[] bidderName = new String[100];
int[] bidValue = new int[100];
String[] data = input.trim().split(",");
int k = 0;
for (int i = 0; i < data.length; i += 2) {
bidderName[i/2] = data[i];
bidValue[i/2] = Integer.parseInt(data[i + 1]);
k++;
}
for (int i = 0; i < k; i++) {
System.out.println(bidderName[i] + " // " + bidValue[i]);
}
}
}
You could use a Scanner, but I wouldn't. The input is short enough (unless you have thousands of these) to read it in once and use Java regular expressions:
String s = "1,A,5,B,10,A,8,A,17,B,17";
String[] split = s.split(",");
for (String current : split) {
if (current.matches("^\\d+$")) {
System.out.println("handle number " + current);
} else
System.out.println("handle letter " + current);
}
Consider using an ArrayList rather than an array so you don't have to know the number of elements in each "array" up front.
First try to do it by yourself
Split the string using ',' use split(",") then you will get string array which contains both letters and numbers
if you are sure that sequence follows same pattern add every odd index tokens to int array using Integer.parseInt()
put even indexes directly to your array
You don't specify where the input is coming from, but for example, if it's coming from System.in, you could do something like this:
String[] bidderName = new String[100];
int[] bidValue = new int[100];
int bvIndex = 0;
int bnIndex = 0;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
bidderValue[bvIndex++] = scanner.nextInt();
else {
bidderName[bnIndex++] = scanner.next();
}
}
You would want some sort of terminal condition in addition to scanner.hasNext(), but that's up to you to determine.

Categories