I made a scanner program where it reads a fake language and returns a string of numbers to represent keywords, letters/letters with numbers, numbers, and symbols to a text file to be read by a parser.
The issue I'm having is that when on the text file being initially read has a number that has more than one digit it returns like so:
1 = letter
12 = equal
2 = number
777 is the number in the first text.
Ex. In the initial text : b = 777
the final text: 1 12 2 7 2 7 2 7
When I really want 1 12 2 777
I know I should make the character 777 into a string but my confusion comes from how do I get that to go first when I have in the loop I've posted
I also have another loop for words and again it's the same issue.
Thank you
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
while(text.charAt(i)>='0'&&text.charAt(i)<='9')
{
log(Integer.toString(CONST));
System.out.println(CONST);
char num =text.charAt(i);
System.out.println(num);
log(Character.toString(num));
i++;
}
The first thing you should do when your code doesn't work is to shape it into something that's testable, and write a test that fails.
I adapted your code by:
removing the parts you didn't explain, or that looked irrelevant (CONST, and log())
making write to an arbitrary Writer, rather than hard-code System.out.
So:
private void consumeDigits(Writer writer, String text) throws IOException {
int i=0;
while (text.charAt(i) >= '0' && text.charAt(i) <= '9') {
char num = text.charAt(i);
writer.append(num);
i++;
}
}
Now I can write a test.
#Test
public void printStackTrace() throws IOException {
String text = "777abcdef";
StringWriter writer = new StringWriter();
consumeDigits(writer, text);
assertEquals(writer.toString(), "777");
}
The test passes -- so either your code works, or I've misunderstood your requirements. But if you follow this method of working and write a failing test, it's something answerers on SO can help with more easily.
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.
Hello I have a bit of a problem with calculating numbers from a file.
My input is the following rawData.txt:
19.95
5
The output however is this:
49.0 57
My code looks like this:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class ReadAndWrite
{
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = null;
diskScanner = new Scanner(new FileReader("rawData.txt"));
PrintStream diskWriter = new PrintStream("cookedData.txt");
double total;
double unitPrice = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(unitPrice);
int quantity = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(quantity);
total = unitPrice * quantity;
diskWriter.println(total);
diskScanner.close();
}
}
Eventually the cookedData.txt file contains the number 2793.0
Please help
You are fetching only the first character of each line - because of the charAt(0), then cast it to a double (casting char to double!!)
I can't understand what you are trying to do, but converting char to double using casting is almost always NOT what you should do.
Try using Double.parseDouble instead. see it here: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
diskScanner.findWithinHorizon(".",0).charAt(0);
means that you are getting any character, because the first parameter of findWithinHorizon is a regular expression, and "." means one character. From that string you take the first char, i.e. 1. The ascii value of 1 is... 49.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im creating a program called "Book" for school and im having alot of trouble. IM suppost to find out how many times the character "a" comes up in a txt file. The txt file reads the following "go to the bathroom
he said
and he was right
I needed to go to the bathroom" . Here is my code but it doesnt seem to work at all and i am stuck.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Book
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner text = new Scanner (new File("data.txt"));
String word = null;
int count = 0;
while(text.hasNextLine())
{
word = text.nextLine();
for (int i = 0; i < word.length(); i++)
{
if (word.substring(i) == "a")
{
count++;
}
}
}
System.out.print(count);
}
}
The substring with one parameter returns a substring that starts at the given index. Also, you do not generally compare strings in Java using ==.
You need single quotes around a to make it a character constant, and charAt to get the specific character of the string, like this:
if (word.charAt(i) == 'a')
I think you are looking the charAt() function. substring() returns a String, but you really want a Character. Note: Characters are denoted with single quotes '
if (word.charAt(i) == 'a')
word.substring(i) returns a String, when used in an equality check with ==, the String objects in the operand are compared based on their location in memory, rather than their values.
Additionally, word.substring(i) will return the entire string beginning at i, not the character at i. To return just the character, you'll need to also specify the end index. (see the docs)
This will probably work if you replace
if (word.substring(i) == "a")
with
if (word.substring(i, i+1).equals("a"))
You are reading your text file line by line but
You can use FileInputStream to read char from file.
Here is an example given.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File file = new File("data.txt");
if (!file.exists()) {
System.out.println(args[0] + " does not exist.");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
char current;
int count = 0;
while (fis.available() > 0) {
current = (char) fis.read();
if (current == 'a') {
count++;
}
}
System.out.println(count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here you can iterate each char of file instead of line.
Hope this will help you.
Refer to Converting Letters to Numbers
In the file test.in.rtf, I have 'abcd' typed. However, when I run the program, I get ??? ??????????? ???????? plus maybe a few more in test.out.rtf. Why is this? Am I missing something?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("test.in.rtf"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.rtf")));
StringTokenizer st = new StringTokenizer(f.readLine());
StringBuilder sb = new StringBuilder();
for (char c : st.nextToken().toCharArray()) {
sb.append((char)(c - 'a' + 1));
}
out.println(sb); // output result
out.close(); // close the output file
System.exit(0);
}
}
I'm pretty sure you want
sb.append(Integer.toString(c - 'a' + 1));
or simply
sb.append( c - 'a' + 1 );
which implicitly does the same thing, since the expression c - 'a' + 1 is implicitly cast to an int since Java does all non-long integer math (anything involving chars, bytes, shorts, and/or ints) by converting everything to ints first.
What you had cast the integer result to a char, which would be represented by the character whose ASCII value is that number (something b/w 1 and 26), which isn't something readable.
You are trying to write the char values 1,2,3 and 4 ('a'-'a' + 1 = 1 and so on), which are all "unwriteable" hence the "?"s. Why you get 7 and not 4? I don't know - maybe a locale issue or 3 of them are just written as two "?".
what is wrong in this code?
import java.io.IOException;
import java.util.*;
public class char_digit {
public static void main(String[] args) throws IOException {
int count=0;
while (true){
char t=(char) System.in.read();
if (t=='0'){
break;
}
count++;
}
System.out.println(count);
}
}
run:
a
b
c
d
e
f
0
12
You're counting the newlines as well as the other characters. Try something like if (t == '\n') continue; before the current if.
nothing is wrong. The carriage return also counts as a char (or 2 depending on your OS)
The problem is that you're counting whitespace characters as well, which are inserted when you hit the Enter button into the console. One quick fix is to use Character.isWhitespace check as follows:
if (t=='0'){
break;
} else if (!Character.isWhitespace(t)) {
count++;
}
Depending on what you want to do, though, a java.util.Scanner may serve your purpose better. Using System.in.read directly is highly atypical, and especially if you're reading char, where a Reader is more suitable.
Related questions
Java I/O streams; what are the differences?
What is the difference between a stream and a reader in Java?