So my code so far reads in lines from a file, stores them in two separate ArrayLists. Now I'm going to have to make each node in a doubly Linked List contain the line's string and the corresponding integer, but since I cant put two ArrayLists in the declaration for a Linked List, I tried making a Tree map where the key is the string and the value is the corresponding integer. Here's the relevant code
public class FileReaderProgram
{
public static void main(String[] args) throws IOException
{
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
String stringComponent = " ";
int integerComponent = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the absolute path of the file");
String fileName = in.next(); //Gets the file from the user
File inFile = new File(fileName);
**Map<String,Integer> lineCombo = new TreeMap<String,Integer>();**
try
{
Scanner fileReader = new Scanner(inFile); //Constructs Scanner for reading the file
fileReader.useDelimiter("\\n");
while (fileReader.hasNextLine())
{
String line = fileReader.nextLine(); //Gets line from the file
Scanner lineScanner = new Scanner(line); //Constructs new scanner to analyize the line
lineScanner.useDelimiter(",");
stringComponent = lineScanner.next(); //Read first word
while (!lineScanner.hasNextInt())
{
stringComponent = stringComponent + " " + lineScanner.next(); //Checks if more than one word part of string
}
integerComponent = lineScanner.nextInt(); //Read in integer
words.add(stringComponent); //Array of Strings, element number corresponding to the line it came from
numbers.add(integerComponent); //Array of Ints, same thing as above
**lineCombo.put(stringComponent, integerComponent);**
}
}
So when I run the file:
example string,1
another example,42
data,200
final,150
it prints out {another example=42, data=200, example string=1, final=150}
Why is it putting the strings in the wrong order?
Related
Please bear with me as I'm rather new to this.
I'm trying to iterate through a recordset using DataReader object, and do something at each iteration, but it doesn't seem to be getting passed the first record. I essentially want to look at each record and then assign a specific image to a specified location based on the data in a column in the recordset.
I'm using Visual Studio 2019 and using OleDataReader to read Access table. I've got the command object working properly, just can't seem to get passed the first record.
this is the method definition in my class
//Giving string variable names to the virtual paths of the images
private string whitePallet = "~/images/White.jpg";
private string redPallet = "~/images/Red.jpg";
private string bluePallet = "~/images/Blue.jpg";
private string blackPallet = "~/images/Black.jpg";
private string greenPallet = "~/images/Green.jpg";
private string racetrack = "~/images/Racetrack.jpeg";
public string Racetrack { get => racetrack; set => racetrack = value; }
public string OpenConnection(string connectString, String selectString)
{
using (OleDbConnection cn = new OleDbConnection(connectString))
{
cn.Open(); //Open the connection.
OleDbCommand cmd = new OleDbCommand(selectString, cn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string pallet;
if (reader["Status"].ToString() == "Blocked Location")
{
pallet = blackPallet;
return pallet;
}
if (reader["Status"].ToString() == "AP Purge")
{
pallet = redPallet;
return pallet;
}
if (reader["Status"].ToString() == "Open")
{
pallet = whitePallet;
return pallet;
}
if (reader["Status"].ToString() == "Order Complete")
{
pallet = greenPallet;
return pallet;
}
if (reader["Status"].ToString() == "Pallet Full")
{
pallet = bluePallet;
return pallet;
}
}
//Close the reader and the related connection.
reader.Close();
return null;
}
}
this is the instantiation of the class/method
'''
Definitions defs = new Definitions();
Image imgRacetrack = Image.FromFile(Server.MapPath(defs.Racetrack));
//Creating image panel to draw upon using w/h of racetrack image
Image img = new Bitmap(imgRacetrack.Width, imgRacetrack.Height);
using (Graphics gr = Graphics.FromImage(img))
{
//Background image
gr.DrawImage(imgRacetrack, new Point(0, 0));
//Defining the points on the left side:
Point p1 = new Point(125, 50);
Image imgPallet = Image.FromFile(Server.MapPath(defs.OpenConnection(connectString,selectString)));
gr.DrawImage(imgPallet, p1);
Point p2 = new Point(125, 100);
Image imgPallet2 = enter code hereImage.FromFile(Server.MapPath(defs.OpenConnection(connectString, selectString)));
gr.DrawImage(imgPallet2, p2);
}
I'm expecting to iterate through each record and then place the image with the correct color into the correct position, but it's only giving the results to each point/location based on the very first record only. What's wrong with my logic??
You declare pallet string pallet; then have several if statements in which you return pallet;.
First, you want to return a string, but you're doing
pallet = blackPallet; // pallet will not be a string.
pallet = "blackPallet"; // pallet will be a string.
Second, when you say return..., you leave the method; you don't continue after that, you are saying you are done - return this value and stop.
So you need to read the value from each row and store them, then return the collection of values. Then you can loop through the collection and plug in each value as needed.
That's one way. I didn't study what you have in complete detail so there might be a better way. Hope that's enough for now.
As these questions point out, Guid.NewGuid will return the same value for all rows due to the enforced deterministic nature of U-SQL i.e if it's scaled out if an element (vertex) needs retrying then it should return the same value....
Guid.NewGuid() always return same Guid for all rows
auto_increment in U-SQL
However.... the code example in the officials documentation for a User Defined Extractor purposefully uses Guid.NewGuid().
I'm not querying the validity of the answers for the questions above, as they are from an authoritative source (the programme manager for u-sql, so very authoritative!). However, what I'm wondering if the action of using an Extractor means NewGuid can be used as normal? Is it simply within c# expressions in u-sql and User Defined Functions in which NewGuid is unsafe?
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class FullDescriptionExtractor : IExtractor
{
private Encoding _encoding;
private byte[] _row_delim;
private char _col_delim;
public FullDescriptionExtractor(Encoding encoding, string row_delim = "\r\n", char col_delim = '\t')
{
this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding);
this._row_delim = this._encoding.GetBytes(row_delim);
this._col_delim = col_delim;
}
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
string line;
//Read the input line by line
foreach (Stream current in input.Split(_encoding.GetBytes("\r\n")))
{
using (System.IO.StreamReader streamReader = new StreamReader(current, this._encoding))
{
line = streamReader.ReadToEnd().Trim();
//Split the input by the column delimiter
string[] parts = line.Split(this._col_delim);
int count = 0; // start with first column
foreach (string part in parts)
{
if (count == 0)
{ // for column “guid”, re-generated guid
Guid new_guid = Guid.NewGuid();
output.Set<Guid>(count, new_guid);
}
else if (count == 2)
{
// for column “user”, convert to UPPER case
output.Set<string>(count, part.ToUpper());
}
else
{
// keep the rest of the columns as-is
output.Set<string>(count, part);
}
count += 1;
}
}
yield return output.AsReadOnly();
}
yield break;
}
}
https://learn.microsoft.com/en-us/azure/data-lake-analytics/data-lake-analytics-u-sql-programmability-guide#use-user-defined-extractors
Right now I cant even compile this program. Im trying to write a program that takes a inputted string and then encrypts the letters by swapping them out with another letter predetermined in a array and then shows you again the original text. any help would be appreciated.
import java.util.Scanner;
public class Array {
private char [] alphabet = new char [25];
private char [] crypt = new char [25];
String oldMessage;
public Array()
{ char[] alphabet = "abcdefghijklmnoptqrstuvwxyz".toCharArray();
char[] crypt = "qwertyuiopasdfghjklzxcvbnm|".toCharArray();
}
public static void run(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a message that you would like to encrypt\n");
oldMessage = scan.nextLine();
String newMessage = "";
for (int i=0; i<oldMessage.length(); ++i) {
int index = alphabet.indexOf(old.charAt(i));
if (index == -1)
newMessage +="?";
else
newMessage += crypt.charAt(index);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {Array myApplication = new Array(); myApplication.run();}
First off, when encountering errors, it's always best to include the error in your question--often it will point you right to the source of the error. What does your compiler say when the build fails?
Next, I'm on my phone right now and can't verify that I've found all the problems, but remember that strings in Java are immutable, meaning that they can't be changed after creation. This means that you can't append to them in the way you're doing. Try using the StringBuilder class to accomplish what you're looking for here, or filling a new array as you go and converting to String at the end.
Also, it looks like you're missing two end braces (the for loop and the run method).
From static method run() you are referring to non-static variables like alphabet, crypt, oldMessage.
This is first that comes into mind
We have a word document with [Signature] Key as a paragraph, All we need to do is replace with signature with some Names, based on the names we need to repeat the [signature] key.
Ex: if names are containing 10 to 15 characters it should be repeat 2 times in a row like below
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
if names are containing 5 charecters should be repeat 3 times
XXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXX
based on the name node will repeat...?
please help how to solve this task ......
To find and replace text in a word document, Aspose.Words provides IReplacingCallback interface which can easily be used to achieve your goal. I used a static string to test the scenario as I don't have the details of your data source. You will require to add a check in your code based on the name length, you need to add the signature. Check the following sample:
//Open the file
Document doc = new Document("c:\\data\\Signature.docx");
//Specify the string / tag to be replace
doc.Range.Replace(new Regex(#"\[Signature\]", RegexOptions.IgnoreCase), new ReplaceEvaluatorSignature(), false);
//Save the updated document
doc.Save("c:\\data\\Output.docx");
/// <summary>
/// Class to change the signature
/// </summary>
public class ReplaceEvaluatorSignature : IReplacingCallback
{
/// <summary>
/// This method is called by the Aspose.Words find and replace engine for each match.
/// This method highlights the match string, even if it spans multiple runs.
/// </summary>
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
// This is a Run node that contains either the beginning or the complete match.
Node currentNode = e.MatchNode;
// The first (and may be the only) run can contain text before the match,
// in this case it is necessary to split the run.
if (e.MatchOffset > 0)
currentNode = SplitRun((Run)currentNode, e.MatchOffset);
// This array is used to store all nodes of the match for further removing.
ArrayList runs = new ArrayList();
// Find all runs that contain parts of the match string.
int remainingLength = e.Match.Value.Length;
while (
(remainingLength > 0) &&
(currentNode != null) &&
(currentNode.GetText().Length <= remainingLength))
{
runs.Add(currentNode);
remainingLength = remainingLength - currentNode.GetText().Length;
// Select the next Run node.
// Have to loop because there could be other nodes such as BookmarkStart etc.
do
{
currentNode = currentNode.NextSibling;
}
while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
}
// Split the last run that contains the match if there is any text left.
if ((currentNode != null) && (remainingLength > 0))
{
SplitRun((Run)currentNode, remainingLength);
runs.Add(currentNode);
}
//Name is defined for testing, replace it with your data source
// string TestName = "Nausherwan Aslam";
//Following is to test less or equal to 10 charators
string TestName = "Nausherwan";
// Create Document Buidler
DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document as Document);
builder.MoveTo((Run)runs[runs.Count - 1]);
if (TestName.Length > 10)
{
builder.Write(TestName+ " " + TestName);
}
else
{
builder.Write(TestName + " " + TestName + " " + TestName);
}
// Now remove all runs in the sequence.
foreach (Run run in runs)
run.Remove();
// Signal to the replace engine to do nothing because we have already done all what we wanted.
return ReplaceAction.Skip;
}
private static Run SplitRun(Run run, int position)
{
Run afterRun = (Run)run.Clone(true);
afterRun.Text = run.Text.Substring(position);
run.Text = run.Text.Substring(0, position);
run.ParentNode.InsertAfter(afterRun, run);
return afterRun;
}
}
I am beginner in JavaME. I'd like to make simple dicitionary. The source data is placed on "data.txt" file in "res" directory. The structure is like this:
#apple=kind of fruit;
#spinach=kind of vegetable;
The flow is so simple. User enters word that he want to search in a text field, e.g "apple", system take the user input, read the "data.txt", search the matched word in it, take corresponding word, and display it to another textfield/textbox.
I've managed to read whole "data.txt" using this code..
private String readDataText() {
InputStream is = getClass().getResourceAsStream("data.txt");
try {
StringBuffer sb = new StringBuffer();
int chr, i=0;
while ((chr = is.read()) != -1)
sb.append((char) chr);
return sb.toString();
}
catch (Exception e) {
}
return null;
}
but I still dont know how to split it, find the matched word with the user input and take corresponding word. Hope somebody willing to share his/her knowledge to help me..
Basically you want something like this:
private String readDataText() {
InputStream is = getClass().getResourceAsStream("data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
try {
while ((line = br.readLine()) != null)
{
String[] split = line.split("=");
if (split[0].equals("#someFruit"))
return split[1];
}
}
catch (Exception e) {}
return null;
}
Read the line using a BufferedReader, no need to handle single chars.
Split the line by the = token
Check if the key in the dictionary is the wanted key, if so, return the value.