I'm trying to find two specific numbers (25,55) in a input list by converting them to tokens. e.g. below - string list = (52 98 55 86 42 25 87 566 56 843).
Just for context, the numbers are prices for books bought in a week for a library.
If they are both in a line only then I want to know (print "both"). If only one of them is in the line or something like 5562 or 3259 (part of another number), i want a return of "no". I guess that's why I'm converting them to tokens.
This code below is not working unless i remove the else statement and even when i do remove it, it prints out "both" no matter what I numbers i put in, even if there's no 25 or 55. Sorry if this seems like a dumb question, pretty new to coding.
package part;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
public class Part {
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
StringTokenizer tokenizer = new StringTokenizer(list);
String rp = tokenizer.nextToken();
if (rp.equals("25") && rp.equals ("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer works like ResultSet when fetching queries in DB side. Considering it, you should do something like this:
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
List<String> tokenList = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(list);
while(tokenizer.hasMoreTokens()){
tokenList.add(tokenizer.nextToken());
}
if(tokenList.contains("25") && tokenList.contains("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).
Try using below code if you want to check that the contains both of them.
String list = "52 98 55 86 42 25 87 566 56 843";
String[] strarr = list.split("\\s+");
boolean first;
boolean second;
for(String str:strarr){
if(str.equals("25")) first=true;
if(str.equals("55")) second=true;
if(first && second) break;
}
if(first && second) System.out.println("both");
else System.out.println("no");
Related
A lot of this code is already written but the code that I have added was to include ^ and %. It is the code to evaluate an expression in the right order using stacks. What I'm having trouble with this is the main method and adding a way to take user input and print out the result of the problem. I'm just including that part of the code
16 import java.util.Stack;
17 import java.util.Scanner;
18
19 public class EvaluateExpression {
20 public static void main(String[] args) {
21
22 Scanner input = new Scanner(System.in);
23 System.out.println("Enter the expression to be evaluated: ");
24 String expression = input.nextLine();
25
26 //Check number of arguments passed
27 if (args.length != 1) {
28 System.out.println("Usage: java EvaluateExpression \"expression\"");
29 System.exit(1);
30 }
31 try {
32 System.out.println(expression + " = " +
33 evaluateExpression(expression));
34 }
35 catch (Exception ex) {
36 ex.printStackTrace();
37 System.out.println("Wrong expression: " + expression);
38 }
39
40 }
Expected results: it is printing the expression to be evaluated along with the results.
But here is what I am getting with this when I try to enter a random expression:
Enter the expression to be evaluated:
6+9*8-7
Usage: java EvaluateExpression "expression"
It simply means that args.length is different than 1.
Your program is reading from standard input. Don't need to check args count. Args is program arguments that direct input of your program. Like
ls *.txt
or
java -cp . EvaluateExpression <myvalue>
Hope this helps.
I am still in the process of developing this code and I am looking ideas to do this in a efficient and compact ways as I intend to embed this in a separate java code. I am open to ideas for other methods too although I wold prefer HashMap or ArrayList methods
I have a file that I am working with that looks like this:
053 100% BRAN A0 B1 C01 E0
054 100% NATURAL A0 B1 C01 E0 F0 G0
the end product of this code has to look like
053 016% BRAN A0
053 100% BRAN B1
053 100% BRAN C01
053 100% BRAN E0
054 100% NATURAL A0
054 100% NATURAL B1
054 100% NATURAL C01
054 100% NATURAL E0
054 100% NATURAL F0
054 100% NATURAL G0
Please note that the file is very large. All columns are tab separated and the last column as space separated elements.
EDIT: I am sorry I should have framed my question better.I was thinking of collections because after doing this I need to be able to access all the lines with different keys (the repeating values of the first column).
If the pattern is fixed, then this can be done using RegEx. The get(); will take each line as input and returns the list of all combinations for that input string
public static void main(String[] args) {
String input="053 100% BRAN A0 B1 C01 E0";
System.out.println(get(input));
}
public static List<String> get(String input){
List<String> list = new ArrayList<String>();
String regEx="((?:\\d*)\\s(?:\\d*)%\\s(?:[A-Z]*))([\\s]*)([\\sA-Z0-9]*)";
Matcher matcher = Pattern.compile(regEx).matcher(input);
String firstHalf="";
String codes="";
if(matcher.matches()) {
firstHalf=matcher.group(1)+matcher.group(2);
codes=matcher.group(3);
}
for (String code : codes.split("\\s")) {
list.add(firstHalf+code);
}
return list;
}
It's unclear why you need a collection at all. Just manipulate the strings:
for (String line : input) {
String prefix = line.substring(0, 20); // Or however you decide on the line prefix.
String suffix = line.substring(20);
for (String part : suffix.split(" ")) {
System.out.printf("%s%s%n", prefix, part);
}
}
You can do it more efficiently than this, by using a PrintWriter to avoid explicitly constructing the substrings/split array.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Test {
public static void main (String[] args){
List<String[]> myList = new ArrayList<>();
//read each line of your file and split it by \s+
try (Stream<String> stream = Files.lines(Paths.get("C:\\temp\\xyz.txt"))) {
stream.forEach( line->{
String[] splited = line.split("\\s+");
//iterate from 4th element of your splited array to last
//and add the first three elements and the ith element to your list
for(int i = 3; i<splited.length; i++){
myList.add(new String [] {splited[0] ,splited[1], splited[2], splited[i]});
}
});
} catch (IOException ex) {
ex.printStackTrace();
}
//print or do other stuff with your list
myList.forEach(e->{System.out.println(Arrays.toString(e));});
}
}
I have been running through this array of objects trying to figure out what I am doing wrong and I can't see the error. This program runs through the first iteration bringing in Austria and all its subsequent information but will not move onto the second part of the array. I thought it might be that it's somehow taking each variable from the countries class and making it its own spot in the array but that can't be it because I have increased the array size to 64 and it still stops at the end of Austria. I have been able to get it to go a bit further by placing print statements after each item is added and it seems to be adding an unaccounted for blank line in it for some reason and I'm not sure why. any help that could be given would be greatly appreciated.
This is my test code with the data list:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "CountriesInfo2.txt";
FileReader inputDataFile = new FileReader (INPUT_FILE);
Scanner read = new Scanner (inputDataFile);
Countries[] c = new Countries[8];
for (int i = 0; i < c.length; i++) {
c[i] = new Countries();
c[i].countryName = read.nextLine();
c[i].latitude = read.nextLine();
c[i].longitude = read.nextLine();
c[i].countryArea = read.nextInt();
c[i].countryPopulation = read.nextInt();
c[i].countryGDP = read.nextDouble();
c[i].countryYear = read.nextInt();
sop ("" + c[i].countryName + "\n" + c[i].latitude+"\n"+c[i].longitude+"\n"+c[i].countryArea+"\n"+
c[i].countryPopulation+"\n"+c[i].countryGDP+"\n"+c[i].countryYear);
}// end for
} // End Main
public static void sop (String s) {
System.out.println(s);
} // End sop
} // end class
Austria
47 20 N
13 20 E
83871 8754513 417.2 2016
Belgium
50 50 N
04 00 E
30528 11491346 509.5 2016
Czech Republic
49 45 N
15 30 E
7886
10674723
350.7
2016
France
46 00 N
02 00 E
643801
67106161
2734.0
2016
This list is supposed to be one line for each bit of information with lat-long having 2 sets of double digits and a letter each.
nextLine() automatically moves the scanner down after returning the current line. Rather I would advise you do as following
read each line using String data = scanner.nextLine();
split the data using space separator String[] pieces =
data.split("\\s+");
set the pieces to Country attributes by converting them in to
their appropriate type.
eg. c[i].countryName = pieces[0];
`c[i].latitude = piece[1];`
I'm programming an app and trying to figure out how to format data from an EditText field
The data will look something like this
somename 123 445.46
somename2 56 234
somename3 34 42.65
What I want to do is move the first set of numbers to the left side
123 somename 445.46
56 somename2 234
34 somename3 42.65
Something like this will work:
public static String formatData(String str){
String[] temp = str.split(" ");
if(temp.length > 2){
return temp[1]+" "+temp[0]+" "+temp[2];
}else{
// can't perform.
return str;
}
}
let me start off by saying that I am a fairly new Java programmer, and what I am trying to attempt is a bit over my head. Thus, I came here to try to learn it.
Okay, so here's the issue: I am trying to build a program that makes a 2d array from values in a text document. The text document has three columns and many rows (100+)...basically a [3][i] array.
Here's what I can do: I understand how to read the text file using bufferedReader. Here is a sample program I have that prints the text exactly how it looks in the text file (I apologize ahead for bad formatting; it's my first time on these forums):
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("RA.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String[] nums = line.split(",");
for (String str : nums) {
System.out.println(str);
}
}
br.close();
}
}
This is what is printed:
00 03 57.504
02 04 03.796
00 06 03.386
03 17 43.059
00 52 49.199
05 52 49.555
etc, etc.
Please help me in making an array with values. Thank you!
define a list outside your while loop like
List list = new LinkedList();
Inside your while loop, add the splitted array to the list, like
list.add(line.split(","));
After the while loop convert your list to an array, resulting in a 2D array:
Foo[] array = list.toArray(new Foo[list.size()]);