I am trying to understand how this convertingStringToInt method works. I am reading a file, storing the values in an array and am to pass those values to the method to be converted. In the parameters of convertingStringToInt, I have (String number) I don't get where the String "number" is getting its values. So I am passing in a string called numbers, but how is that newly created String associated with any of the values in my file...?!?
I am trying to understand the cause all the return numbers are the error code -460 except the last digit in the file. So the String numbers is associated with the file somehow I just don't get how...
public static void read_file()
{
try {
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared?
{
String numbers = scan.nextInt();
try {
return Integer.parseInt(numbers);
} catch (NumberFormatException n) {
return -460;
}
}
I have global_numbers declared as a global variable.
so the first thing u need understand is what u have in your txt file
if in this file you have only number is ok use stringToInt
but if you have words this never work properly
Related
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
This is the public class
public class Process {
private String keywordAsString = "";
private String keyword = "";
// ArrayList to hold the letters of the keyword with duplicates removed.
private ArrayList<Integer> keywordAsIntsNoDup = new ArrayList<Integer>(0);
// Map for removing all duplicate letters in the keyword.
private Map<Integer, Integer> keywordLetters = new LinkedHashMap<Integer, Integer>(0);
// ArrayList to hold all 256 ASCII characters (as integers).
private ArrayList<Integer> asciiArray = new ArrayList<Integer>(0);
// ArrayList for storing the message from the file.
ArrayList<Integer> fileMessageAsInteger = new ArrayList<Integer>(0);
// Constructor
public void process() {
}
public void processKeyword(String keyword) {
// Copy incoming keyword String
this.keywordAsString = keyword;
// Pass incoming keyword String to the removeDuplicate method.
// removeDuplicate will first convert the letters to Integers,
// then remove any duplicate letters.
// Store the result in the keywordAsIntsNoDup ArrayList
this.keywordAsIntsNoDup = removeDuplicates(this.keywordAsString);
// Create ArrayList and fill it with all 256 ASCII characters (as integers).
createAsciiArr();
// Remove the keyword letters from the asciiArray.
for (int i=0; i<this.keywordAsIntsNoDup.size(); i++) {
Integer letterToSearchFor = this.keywordAsIntsNoDup.get(i);
if (this.asciiArray.contains(letterToSearchFor))
{
this.asciiArray.remove(letterToSearchFor);
}
}
}// END processKeyword()
public ArrayList<Integer> removeDuplicates(String keyword) {
// Copy incoming keyword String
this.keyword = keyword;
I really would appreciate if someone would help me Java is really no piece of cake.
// Loop through the keywordAsIntArray ArrayList, putting each 'letter' of the keyword into the map.
// Duplicate letters will be overridden, so the map will contain the keyword without any duplicates.
for (int i=0; i
// Put the maps' key set (which holds the 'letters') into an ArrayList.
// This will make it easier to put the 'letters' into the Table later.
ArrayList<Integer> keyslist = new ArrayList<Integer>(this.keywordLetters.keySet());
System.out.println("\n" + "map.keySet() from keyslist ArrayList = " + keyslist.toString());
return keyslist;
}
public void createAsciiArr() {
// Use an enhanced for loop to fill the asciiArray ArrayList
// with all 256 ASCII characters as integers.
for (int i=0; i<256; i++) {
this.asciiArray.add(i);
}
}// END createAsciiArr()
}// END class
Please I want to input String as keyword, then get back hex values as the encrypted code and not integers. Also Please I have more of the codes I dont really understand,am really new to Java. Please can anyone help me.
I have textfiles, which have attributes saved in Strings. Those Strings have a pattern like this:
[attributeName]:[value]
I can't generalize the [value], because it could be of any primitive datatype.
Saving the effectively values is not my concern, because it's depending on the user which attribute has to be loaded. The same file won't be loaded very often.
Now I have 2 problems:
1) For some reason the program which creates those files sometimes adds spaces around the : at some attributes and [value] could also contain spaces, so I have to get rid of those
2) Making the reading of those attributes more performant:
I've come up with this method:
public String getAttribute(File file, String attribute)
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(file), 1024);
String line;
Pattern p = Pattern.compile(Pattern.quote(attribute), Pattern.CASE_INSENSITIVE);
while ((line = reader.readLine()) != null)
{
int i = line.indexOf(":");
if(line.charAt(i-1) == ' ')
line = line.substring(0,i-2) + line.substring(i);
if(line.charAt(i+1) == ' ')
line = line.substring(0,i) + line.substring(i+2);
if (p.matcher(line).find())
{
return line.replace(attribute, "").trim();
}
}
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
However, this method will probably be one of the most called by my application, so I can't leave it so unperformant as it is right now,
Thanks for any help!
I modified code to find appropriate line. Check example code below.
If you have a lot of files and attributes in these files you could think about saving somewhere pair attribute=value in code. In example code I provided very primitive cache by using Table interface from guava library.
Example code:
# guava library
import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;
# apache commons lang
import static org.apache.commons.lang.StringUtils.startsWithIgnoreCase;
# apache commons io
import static org.apache.commons.io.IOUtils.closeQuietly;
[...]
# very primitive cache implementation. To find a value in table you have to
# pass row and column keys. In this implementation row is equal to file
# absolute path (because you can have 2 files with the same name) and column
# is equal to attribute name.
# If you have a lot of files and attributes probably you will have to clear
# from time to time the cache otherwise you will get out of memory
private static final Table<String, String, String> CACHE = HashBasedTable.create();
[...]
public String getAttribute(File file, String attribute) {
# get value for the given attribute from the given file
String value = CACHE.get(file.getAbsolutePath(), attribute);
# if cache does not contain value, method will read value from file
if (null == value) {
BufferedReader reader = null;
String value = null;
try {
reader = new BufferedReader(new FileReader(file), 1024);
String line;
while ((line = reader.readLine()) != null) {
# From your description I understood that each line in file
# starts with attribute name
if (startsWithIgnoreCase(line, attribute) {
# if we found correct line we simple split it by ':'
String[] array = line.split(":");
# this is to ensure that line contains attribute name
# and value
if (array.length >= 2) {
# we found value for attribute and we remove spaces
value = array[1].trim();
# we put value to the cache to speed up finding
# value for the same attribute in the future
CACHE.put(file.getAbsolutePath(), attribute, value);
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
# you should always close
closeQuietly(reader);
}
}
return value;
}
I want to get the highest available string value in java how can i achieve this.
Example: hello jameswangfron
I want to get the highest string "jameswangfron"
String Text = request.getParameter("hello jameswangfron");
Please code example.
public class HelloWorld{
public static void main(String []args){
String text = "hello jameswangfron";
String[] textArray = text.split(" ");
String biggestString = "";
for(int i=0; i<textArray.length; i++){
if(i==0) {
textArray[i].length();
biggestString = textArray[i];
} else {
if(textArray[i].length()>textArray[i-1].length()){
biggestString = textArray[i];
}
}
}
System.out.println("Biggest String : "+biggestString);
}
}
And it shows the output as
Biggest String : jameswangfron
Maybe this will be easyer to understand
public class HelloWorld {
public static void main(String[] args) {
System.out.println(StringManipulator.getMaxLengthString("hello jameswangfron", " "));
}
}
class StringManipulator{
public static String getMaxLengthString(String data, String separator){
String[] stringArray = data.split(separator);
String toReturn = "";
int maxLengthSoFar = 0;
for (String string : stringArray) {
if(string.length()>maxLengthSoFar){
maxLengthSoFar = string.length();
toReturn = string;
}
}
return toReturn;
}
}
But there is a catch. If you pay attention to split method from class String, you will find out that the spliter is actually a regex. For your code, i see that you want to separate the words (which means blank space). if you want an entire text to search, you have to pass a regex.
Here's a tip. If you want your words to be separated by " ", ".", "," (you get the ideea) then you should replace the " " from getMaxLengthString method with the following
"[^a-zA-Z0-9]"
If you want digits to split up words, simply put
"[^a-zA-Z]"
This tells us that we use the separators as anything that is NOT a lower case letter or upper case letter. (the ^ character means you don't want the characters you listed in your brackets [])
Here is another way of doing this
"[^\\w]"
\w it actually means word characters. so if you negate this (with ^) you should be fine
i want to find value in List<> but i am not getting the integer value. Here is my code from that i want to find the value in the List
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
try
{
//decimal find = decimal.Parse(txtnapsaserach.Text);
if (decimal.Parse(txtnapsaserach.Text) > 0)
{
List<NapsaTable> _napsatabs = this.napsaTableBindingSource.List as List<NapsaTable>;
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate.Equals(txtnapsaserach.Text)).ToList();
}
}
catch (Exception Ex)
{
}
}
any solution for me . Because this works for me when i try to find string value.
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
float value;
if (!float.TryParse(txtnapsaserach.Text, out value))
return; // return if text cannot be parsed as float number
if (value > 0)
{
var napsatabs = napsaTableBindingSource.List as List<NapsaTable>;
napsaTableBindingSource.DataSource =
napsatabs.Where(p =>p.NapsaRate == value).ToList();
}
}
try this
i want to find value in List<> but i am not getting the integer value.
Your p.NapsaRate is either integer type or floating point number, (probably decimal) Convert your txtnapsaserach.Text to decimal value and then compare it in where clause.
decimal rate = 0;
if(!decimal.TryParse(txtnapsaserach.Text), out rate)
{
//Invalid number in textbox
}
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate == rate)).ToList();
if p.NapsaRate is of type double or float you can parse them accordingly using Double.TryParse or Double.Parse etc
The reason you are not getting any error is that you are using object.Equals method for comparing decimal value with string. You should always use == for equality comparison of value types.
I have a text file, for example : file.txt, I want to read a line, for example line 7, have any way to read directly line 7 without reading other lines? I want to save memory from this work.
Because of the way JME been cut down you cannot do this. You would have to read whole file. Only other way, but may not be well suitable is to read the file , store it in RecordStore new entry per line, but is it really worth...
I think it is possible however you need to use a hashtable which might result to more heap usage.
Anyway, first, the contents of the text file should be stored in a char array. Then, second, the contents of the char array must be moved to the hashtable.
Each line in the text file is separated by a new line. In the char array, the new line (maybe) is translated to '\n'. Concatenate the characters in the array until the new line character is reached. The concatenated characters (minus '\n') will form the string in the first line. There should also be a counter here which should have been initialized to 0 (or 1, whatever you prefer). Save the text to the hashtable; The value will be the string that has been created and the key will be the counter. Increment the counter afterwards. Repeat this process for the remainder of the array until the end of file is reached.
With the hashtable, you can now get the string at line 7 without going through the other lines. Well, basically, each line has been read once. But, at least, you don't have to traverse each line once they have been stored in the hashtable.
Like what I have said earlier, doing this might increase heap usage especially if the text file is very large.
[And, by the way, sorry for the very late response. This is my first time here (I mean I just registered and answered this question) :D ]
Common Code
private String readLine(InputStream _inStream, int lineNum)
throws IOException {
if (null == _inStream) {
throw new IOException("Inputstream null.");
}
if (lineNum < 0) {
return ("Cannot read line a number " + lineNum);
}
final StringBuffer buf = new StringBuffer();
byte c;
int curLine = 1;
while (((c = (byte) _inStream.read()) != -1)) {
//System.out.println((char)c);
if (c == '\n') {
++curLine;
if (curLine > lineNum) {
break;
} else if (curLine < lineNum) {
continue;
}
} else if (curLine != lineNum) {
continue;
}
buf.append((char) c);
}
if (0 == buf.length()) {
return null;
} else {
return buf.toString().trim();
}
}
.
private String readLineWithSkip(InputStream _inStream, long skipCharacters)
throws IOException {
if (null == _inStream) {
throw new IOException("Inputstream null.");
}
if (skipCharacters < 1) {
return ("Cannot skip stream of " + skipCharacters + " characters");
}
final StringBuffer buf = new StringBuffer();
byte c;
_inStream.skip(skipCharacters);
while ((c = (byte) _inStream.read()) != '\n') {
//System.out.println((char)c);
buf.append((char) c);
}
if (0 == buf.length()) {
return null;
} else {
return buf.toString().trim();
}
}
.
InputStream inStream = null;
int fileLength = 39;
int skipCharacters = 10;
int lineNumber = 3;
String myLine = "No line read.";
try {
inStream = Class.class.getResourceAsStream("/test.txt");
if (null != inStream) {
inStream.mark(fileLength);
//For Approach II
myLine = readLine(inStream, lineNumber);
inStream.reset();
//For Approach I
myLine = readLineWithSkip(inStream, skipCharacters);
}
} catch (SecurityException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
inStream = null;
System.out.println(myLine);
}
.
Approach I: Map the line number with no of cumulative characters
Run the file through a code that maps the line number with the last of charater in that line from the 0th position of the file (to be used as skip() value) all +2 ('\r\n\') for each line. You can store this Mapping table either at the start or at the end of the same file.
The run the above common code with method readLineWithSkip(inStream,
skipCharacters); ONLY and judiciously commenting other method calls.
Points to Consider:
Skips to the desired position in the inputstream
Has an overhead of parsing the file and storing the mapping table.
.
Approach II: Read each line till the Nth line is read
The run the above common code with method readLine(inStream,
lineNumber); ONLY and judiciously commenting other method calls.
Points to Consider:
Slow since it has to read each character till it reaches the desired line
No overhead of parsing the file and no storing of the mapping table.
I would like to further simplify the problem of reading the chars without requiring any mapping of characters with line numbers.
...
Form form=new Form("filename");
InputStream fin=fconn.openDataInputStream();
StringBuffer buf =new StringBuffer();
int c;
int counter=-1;
while((c=fin.read())!=-1)
{
counter++;
if(counter==23)
{
form.append(buf.toString());
buf=null;counter=0;
continue;
}
buf.append((char)c);
}
if(counter<23 && counter>=0) // write the skipped chars between the last number read and the end of file
{
form.append(buf.toString());
buf=null;counter=0;
}
fin.close();
...
Hope this would help others.