I'm reading my game map
FileHandle file = Gdx.files.internal("data/" + level + ".txt");
StringTokenizer tokens = new StringTokenizer(file.readString());
while(tokens.hasMoreTokens()){
String type = tokens.nextToken();
if(type.equals("Car")){
carLiist.add(new Car(Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken()), Float.parseFloat(tokens.nextToken()), Float.parseFloat(tokens.nextToken())));
}
And here is my text file
Block 0 0
Block 64 0
Car 1 5 9 5
Car 1 5 2
Block 1
Car 7
Is it possible in java to count number in each line?
EDIT:
How I need to get whole line using stringtokenizer? Here what I'm trying to do, but I get only first word in each line
while(tokens.hasMoreTokens()){
String type = tokens.nextToken();
System.out.println(type);
if(type.equals("Block")){
//System.out.println(type);
list.add(new Brick(Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken())));
Yes there is. Java provides a method to check whether a character is digit or not. Check the character and and increase count if its digit like this:
int digitCount = 0;
if(isDigit(characterToCheck)) {
digitCount++;
}
Method: boolean isDigit(char ch). See here for example
Related
Question explaination: as some of the comments suggested, I will try my best to make this question clearer. The inputs are from a file and the code is just one example. Supposedly the code should work for any inputs in the format. I understand that I need to use Scanner to read the file. The question would be what code do I use to get to the output.
Input Specification:
The first line of input contains the number N, which is the number of lines that follow. The next
N lines will contain at least one and at most 80 characters, none of which are spaces.
Output Specification:
Output will be N lines. Line i of the output will be the encoding of the line i + 1 of the input.
The encoding of a line will be a sequence of pairs, separated by a space, where each pair is an
integer (representing the number of times the character appears consecutively) followed by a space,
followed by the character.
Sample Input
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output for Sample Input
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
I have only posted two questions so far, and I don't quite understand the standard of a "good" question and a "bad" question? Can someone explain why this is a bad question? Appreciate it!
Complete working code here try it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharTask {
public static void main(String[] args) {
List<String> lines = null;
try {
File file = new File("inp.txt");
FileInputStream ins =new FileInputStream(file);
Scanner scanner = new Scanner(ins);
lines = new ArrayList<String>();
while(scanner.hasNext()) {
lines.add(scanner.nextLine());
}
List<String> output = processInput(lines);
for (int i=1;i<output.size(); i++) {
System.out.println(output.get(i));
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static List<String> processInput(List<String> lines){
List<String> output = new ArrayList<String>();
for (String line: lines) {
output.add(getProcessLine(line));
}
return output;
}
private static String getProcessLine(String line) {
if(line.length() == 0) {
return null;
}
String output = "";
char prev = line.charAt(0);
int count = 1;
for(int i=1;i<line.length();i++) {
char c = line.charAt(i);
if (c == prev) {
count = count +1;
}
else {
output = output + " "+count + " "+prev;
prev = c;
count = 1;
}
}
output = output + " "+count+" "+prev;
return output;
}
}
Input
(inp.txt)
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
There are two different problems you need to address, and I think it is going to help you to address them separately. The first is to read in the input. It's not clear to me whether you are going to prompt for it and whether it is coming from the console or a file or what exactly. For that you will want to initialize a scanner, use nextInt to get the number of lines, call nextLine() to clear the rest of that line and then run a for loop from 0 up to the number of lines, reading the next line (using nextLine()) into a String variable. To make sure that is working well, I would suggest printing out the unaltered string and see if what is coming out is what is going in.
The other task is to convert a given input String into the desired output String. You can work on that independently, then pull things back together later. You will want a method that takes in a string and returns a string. You can test it by passing the sample Strings and seeing if it gives you back the desired output strings. Set the result="". Looping over the characters in the String using charAt, it will want variables for the currentCharacter and currentCount, and when the character changes or the end of the string is encountered, concatenate the number and character onto the string and reset the character count and current character as needed. Outside the loop, return the result.
Once the two tasks are solved, pull them together by printing out what the method returns for the input string as opposed to the input string itself.
I think that gives you direction on the method to use. It's not a full-blown solution, but that's not what you requested or needed.
Input:
1 10
How can I provide a space between two inputs so that compiler can take both the inputs differently.
I tried to use
st1=in.nextInt();
in.next();
st2=in.nextInt();
Simply remove the in.next(); call. nextInt() already "ignores" whitespaces. And there is no need to create an array by using split() and to convert the number "manually". Just let the Scanner handle this by using nextInt() like you do already:
Scanner s = new Scanner("1 10 9 5");
while(s.hasNextInt()) {
int number = s.nextInt();
System.out.println(number);
}
The good thing about that is, that you won't get a NumberFormatException like in the other answers if the user does not provide numbers (e.g. a b c).
The following line will give you a String array containing the two numbers as strings:
String[] numbersFromUser = in.nextLine().split(" ");
Assuming that the user properly formats the input.
This would of course also work for a number of arguments greater than 2.
You can then go on to convert numbersFromUser[0] and numbersFromUser[1] into the int values you need:
int st1 = Integer.valueOf(numbersFromUser[0]).intValue();
int st2 = Integer.valueOf(numbersFromUser[1]).intValue();
Use:
data = line.split("\s");
first = data[0];
second = data[1];
third = data[2];
System.out.println(first)
System.out.println(second);
System.out.println(third);
Input:
1 5 6
Output:
1
5
6
So I have a programming exercise that involves concordance. I am attempting to take a .txt file, use regex to parse it into strings containing all words, then create a Hashtable that has the key (the word) and the value (the number of times the word appears in the document). We are supposed to be able to account for both case sensitive and non-case sensitive scenarios by passing in a boolean.
Here is what I have:
public Concordance( String pathName, boolean is_case_sensitive ) {
Scanner file = new Scanner(pathName);
try {
file = new Scanner(new File(pathName));
} catch (FileNotFoundException e) {
System.out.println("No File Found");
}
String[] words;
Pattern pattern = Pattern.compile("\\W+");
words = pattern.split(file.nextLine());
String[] wordsCopy = new String[words.length];
for (int i = 0; i < words.length; i++){
wordsCopy[i] = new String(words[i]);
}
int counter = 0;
while (file.hasNext()){
for (String w : words){
counter = 0;
for (String w2 : wordsCopy){
if (is_case_sensitive == false){
if (w.equalsIgnoreCase(w2)){
counter++;
//w2 = null;
tableOfWords.put(w, counter);
file.next();
}
}
if (is_case_sensitive == true){
if (w.equals(w2)){
counter++;
//w2 = null;
tableOfWords.put(w, counter);
file.next();
}
}
}
}
}
}
To walk you through where I am and where my error I believe is....
I use the scanner to "take in" the file the use the regex \W+ to get all of words. I create a String array, I split the Pattern pattern into the String array. Then I create a deep copy of the array to use during comparison. (So I now have two String arrays - words and wordsCopy). I use an int counter variable to keep track of how many times it appears and address case sensitivity by using an if statement and the equals/equalsIgnoreCase methods. I have been going back and forth between assigning w2 to null (its currently commented out) as I intuitively feel like if it is not set to null, it will be counted twice, but I can't seem to think through it appropriately. I think I am counting items in duplicate, but can't seem to figure out a solution. Any insight? Thanks!
You dont need any extra String[] to check case sensitive
Pattern pattern = Pattern.compile("\\W+");
HashMap<String, AtomicInteger> tableOfWords = new HashMap<String, AtomicInteger>();
while (file.hasNextLine()){
words = pattern.split(file.nextLine());
for (String w : words){
String tmp = w;
if (!is_case_sensitive){
tmp = String.valueOf(w.toLowerCase());
}
AtomicInteger count = tableOfWords.get(tmp);
if (count == null){
count = new AtomicInteger(0);
}
count.incrementAndGet();
tableOfWords.put(tmp,count);
}
}
Convert the actual word into low / high case if case sensitive is not required. then everything work perfectly.
As far as I can see you are actually counting words multiple times (more than twice aswell)
I'll give you a simple foreach loop to explain what you're doing,
some of the syntax might be wrong as i'm not using an ide to write this code
int[5] ints = {1,2,3,4,5};
int[5] intcopy = ints;
for(int i:ints){
for(int j: intcopy){
system.out.println(j);
}
}
What you will end out printing is
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
So instead of counting 5 things you are counting 25 things, hope this helps
I have a program that will read a text file starting on line number 29. If the line contains the words "n.a" or "Total" the program will skip those lines.
The program will get the elements [2] and [6] from the array.
I need to get element [6] of the array and print it underneath its corresponding value.
Element[2] of the array is where all the analytes are and element[6] contains the amount of each analyte.
The files that the program will read look like this:
12 9-62-1
Sample Name: 9-62-1 Injection Volume: 25.0
Vial Number: 37 Channel: ECD_1
Sample Type: unknown Wavelength: n.a.
Control Program: Anions Run Bandwidth: n.a.
Quantif. Method: Anions Method Dilution Factor: 1.0000
Recording Time: 10/2/2013 19:55 Sample Weight: 1.0000
Run Time (min): 14.00 Sample Amount: 1.0000
No. Ret.Time Peak Name Height Area Rel.Area Amount Type
min µS µS*min % mG/L
1 2.99 Fluoride 7.341 1.989 0.87 10.458 BMB
2 3.88 Chloride 425.633 108.551 47.72 671.120 BMb
3 4.54 Nitrite 397.537 115.237 50.66 403.430 bMB
4 5.39 n.a. 0.470 0.140 0.06 n.a. BMB
5 11.22 Sulfate 4.232 1.564 0.69 13.064 BMB
Total: 835.213 227.482 100.00 1098.073
The program needs to read that type of files and stores the element[6] of the array under a heading in a separate file in a folder. That file will have a heading like this:
Fluoride,Chloride,Nitrite,Sulfate,
The amount of fluoride should go under fluoride, the amount of chloride should go under chloride and so on and if there isn`t Nitrite or any other analyte it should put a zero for each analyte.
I just need to know how to match that and then I know I have to make write to the file which I will do later, but for know I need help matching.
The final output should looe like this.
The first line will be written in the textfile and then the second line will be values that will be match under its corresponding analyte like this:
Sample#,Date,Time,Fluoride,Chloride,Nitrite,Sulfate,9-62-1,10/2/2013,19:55,10.458,671.120,403.430,13.064,
Also again if an analyte isnt present on the file or it is null it should put a 0.
Here is my code:
//Get the sample#, Date and time.
String line2;
while ((line2 = br2.readLine()) != null) {
if (--linesToSkip2 > 0) {
continue;
}
if (line2.isEmpty() || line2.trim().equals("") || line2.trim().equals("\n")) {
continue;
}
if (line2.contains("n.a.")) {
continue;
}
if (line2.contains("Total")) {
continue;
}
String[] values2 = line2.split("\t");
String v = values2[2];//Stored element 2 in a string.
String v2 = values2[6];//Stored element 6 in a string.
String analytes = "Fluoride,Chloride,Nitrite,Sulfate";//Stored the analytes into an array.
if (analytes.contains(v)) {
System.out.println(v2);
}
int index2 = 0;
for (String value2 : values2) {
/*System.out.println("values[" + index + "] = " + value);*/
index2++;
}
System.out.print(values2[6] + "\b,");
/*System.out.println(values[6]+"\b,");*/
br.close();
}
Thanks in advance!
So if i understand your task right and every element is in new line.
Where is a lot of ways how to solve this, but with your code simpliest way to solve it in my opinion would be with StringBuffer.
//In your code i saw you have to arrays one of them with element name
//other with element code or smth
StringBuffer firstLine = new StringBuffer();
StringBuffer secondLine = new StringBuffer();
public static void printResult(String[] Name, String[] Code){
//First we gona make first line
//Here we are adding data before Names
firstLine.append("Stuff before Names");
for(int i =0;i<name.length;i++){
//Here we gona add all names in the list which is good
//Dont forget spaces
firstLine.append(name[i]+ " ");
}
//And same goes for second line just change loop array and data added before loop.
//And in the end this should print out your result
System.out.println(firstLine+"\n" + secondLine);
}
Call this method after all file reading is done.
Hope it helps!
Instructions:
Write a program that will read a line of text that ends
with a period, which serves as a sentinel value. Display all the
letters that occur in the text, one per line and in alphabetical
order, along with the number of times each letter occurs in the text.
Use an array of base type int of length 26 so that the element at
index 0 contains the number of as. and index 1 contain number of bs etc.
package alphabetize;
import java.util.*;
public class Alphabetize
{
private static void number(String s)
{
int[] array = new int[26];
s = s.toUpperCase();
System.out.println(s);
for (int i = 0; i < s.length(); ++i)
{
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
{
++array[s.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println("|" + (char) ('A' + i) + "|" + array[i] + "|");
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String aString = ".";
while (true)
{
System.out.println("Please enter sentence with a period to end");
aString = keyboard.nextLine();
if (".".equals(aString))
{
System.exit(0);
}
number(aString);
}
}
}
Still having problem with the period thing.. it does not seem to work the way i did it.
Considering this is a homework and instructions are very specific, you should read the text character by character instead of using built-in functions
If your text file was something like
abcabca.
The output should be something a appears three times, b appears two times etc etc.
So your algo should be something like
Read next character
If char is period goto 5
If char is space goto 1.
If char is between a <-> z. update the counter in arr[0..25] and goto 1
output arr[0..25] one per line
Was it mandated that this assignment is done in Java? The whole idea of a "sentinal character" rather than just using a line terminator is pretty bizarre.
Anyway, you can achieve the behaviour you want by setting the delimiter of Scanner:
keyboard.useDelimiter("\\.");
As for the looping, a big hint is this:
int[] counts;
counts[chars[0] - 'a'] = counts[chars[0] - 'a'] + 1;
or simply
counts[chars[0] - 'a']++;
I'll leave it up to you to include that in a loop.
Edit
If you are looking for character-at-a-time input, I would suggest you use an InputStreamReader instead of Scanner for your input. Here's a basic skeleton of what that looks like:
Reader reader = new InputStreamReader(System.in);
while (true) {
int nextInput = reader.read();
if (nextInput == -1) {
System.out.println("End of input reached without sentinal character");
break;
}
char nextChar = (char) nextInput;
//deal with next character
}
Still, read() will typically block until either the end of input is reached (CTRL-D or CTRL-Z from most consoles) or a new line is sent. Thus the sentinal character is of limited use since you still have to do something after typing ".".
You have to check whether period is there at the end or not. So the last character should be '.'.
Then take the length of string before last '.'.
For the counting part create an array like u are doing :
int [] name = new int[26]
where each index starting from 0, 25 corresponds to 'a' till 'z'.
Now you put the string characters in a loop and have to check what that character is like :
if its a 'a' : increase the value at index 0 by 1.
if its a 'd' : increase the value at index 3 by 1.
like wise.
later you display the whole array with a, z along with indexes from 0 till 25.
Suggestion: If its not required to use an array, and you can use any other data-structure you can implement the same in a HashMap very easily. by keeping 'a', 'z' as the keys and count as the corresponding values. and then retrieving and showing the values will also be easier.
You need an int array (e.g., int[] counts = new int[26];) After you read the input line, examine it character by character in a loop. If the character is a not period, then increment the appropriate element of the counts array. (If the character is a, then increment counts[0]; if it is b, increment counts[1]; etc. Hint: you can subtract a from the character to get the appropriate index.) When you find a period, exit the loop and print the results (probably using a second loop).