Converting Letters to Numbers 2 - java

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 "?".

Related

Creating A String with Characters in a While Loop Java

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.

How to retrieve all hexadecimal values of a .txt in java

I have a file with many lines.
Ex :
toto = 0x0020 tata 0x2000 0x0003
tata = 0x0001
tututtt = 0x0021
=> 0x3200
I just want to have these hexadecimal values in a byte array.
I've tried to use a BufferReader and split lines with the " " but I need to find a way to keep exclusively hexadecimal values.
Thanks in advance for your help.
I'd go with java.util.Scanner which can read tokens and patterns, here is the code that can read the file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
public class ReadOnlyHex {
private static Pattern pattern = Pattern.compile("0x\\d{4}");
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("c:/temp/input.txt"));
while(in.hasNextLine()) {
String token = in.findInLine(pattern);
if (token == null) {
in.nextLine();
continue;
}
System.out.println(token.getBytes());
}
in.close();
}
}
I can only assume you are looking for the bytes array of the string, which can be achieved with String.getBytes()
Otherwise, the value represents an int that can be later changed to Integer.toBinaryString
You can use a regex pattern to filter. Loop over the line and use filter function in if you are using Java8.
So first define your pattern
final Pattern p= Pattern.compile("0x[0-9A-F]+$");
Then you can filter your each line array as
String[] splitLineArray=line.split(" ");
String[] hexNumbers=Arrays.stream(splitLineArray).filter((s)-> p.matcher(s).matches()).toArray();
This will return a new array with only hex numbers.

number converting to other number

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.

my BufferedReader character input loop program keeps running forever

I wrote a program which prints out the characters of the sentence (or word) wrote by the user to the console. I thought that the program will end after I gave the first input. But it didn't and kept taking inputs and printing it even after it printed the first sentence. Can you explain me why it happened so? I am new to this. Here is the program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
/*
* This program prints out the characters written in the console
* line by line.
*/
public class ReaderProgram {
public static void main(String args[]) throws IOException{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do{
//reads character and stores it in c
c = (char) br.read();
//prints out c
System.out.println(c);
}while(c != -1);
//'while' checks if c is -1 (-1 means end of the stream)
}
}
Output is shown here (Input to console is show like this):
Epic
E
p
i
c
Dream
D
r
e
a
m
You have cast the result of br.read() too early.
br.read() returns a int, which has a larger storage capacity than a char. char is neither signed nor large enough to store both -1 and the full UTF-16 range of values.
By casting the result to a char before comparing it to -1 you have effectively converted -1 to Character.MAX_VALUE. Which can never equal -1.
Consider the following code:
public static void main( String[] args ) {
char v = (char) -1;
System.out.println( "v = " + (int) v );
}
It will print 65535, and not -1.

String processing - improve efficiency

To print strings in which consecutive characters are different. For example, ABAA into ABA.To do this, it is allowed to delete the characters in the string. Task is to find the minimum number of required deletions. My code computes desired output for less value of T. But when T(=10) or string length become large it is Terminated due to timeout...can anyone give solution?
Input Format
The first line contains an integer T i.e. the number of test cases.
Next T lines contain a string each.
Output Format
Print minimum number of required steps for each test case.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.ArrayList;
public class AlternatingCharacters{
static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int no_of_testcase=s.nextInt();
String values="";
int removechars;
ArrayList<String> arrlist = new ArrayList<String>(no_of_testcase);
for(int i=0;i<no_of_testcase;i++)
{
values=s.next();
arrlist.add(values);
}
for(int i=0;i<arrlist.size();i++)
{
removechars=0;
for(int k=0;k<arrlist.get(i).length()-1;k++)
{
if(arrlist.get(i).charAt(k)==arrlist.get(i).charAt(k+1))
{
removeCharAt(arrlist.get(i),k+1);
removechars++;
}
}
System.out.println(removechars);
}
}
}
s.substring(0, pos) + s.substring(pos + 1);
There is your problem.
You should try using char arrays instead of Strings. String concatenation is extremely slow. Put everything in a char array than change your algorithm to use that.

Categories

Resources