Making an object named differently each time in a for loop - object

Alright, I am having a problem creating a new name for a new object after it is looped several times, code below:
Whatever A1 = new Whatever();
Whatever A2 = new Whatever();
Whatever A3 = new Whatever();
Whatever A4 = new Whatever();
Whatever A5 = new Whatever();
Scanner input = new Scanner(System.in);
int in;
while (true) {
try {
in = Integer.parseInt(input.nextLine());
switch (in) {
case 1:
Whatever A6 = new Whatever();
/*
* Name A6 for the first time, then A7 for the second time the
* loop repeats and so on, until I decide to quite the loop
*/
break;
}
} catch (Exception e) {
System.out.println("Invalid #");
}
}

If the size of the Whatever datatype is static, rather than creating new variables for each loop, you could create an Array of Whatever's and just increment the index after each loop.

Declaring all your Whatever objects individually like that makes it hard to perform an action on all of them at once - you want to bundle them together, probably in an array. I'd recommend first creating an array and then use a for loop to fill it with new Whatevers.

Related

How to read specific column one by one till the defined column number?

I have existing codes that work to get a particular cell from an excel sheet.
I have input data in excel sheet from cell C2 till cell T2.
Current codes allowed me to read cell C2 once.
I wanted to make it automatically read C2, D2, E2, ..... till T2
Codes:
public String ReadCellData(int vRow, int vColumn)
{
String value=null; //variable for storing the cell value
Workbook wb=null; //initialize Workbook null
try
{
//reading data from a file in the form of bytes
FileInputStream fis=new FileInputStream(RunConfiguration.getProjectDir() + "/Data Files/testmatrix.xlsx");
//constructs an XSSFWorkbook object, by buffering the whole stream into the memory
wb=new XSSFWorkbook(fis);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e1)
{
e1.printStackTrace();
}
Sheet sheet=wb.getSheetAt(0); //getting the XSSFSheet object at given index
Row row=sheet.getRow(vRow); //returns the logical row
Cell cell=row.getCell(vColumn); //getting the cell representing the given column
//value=cell.getStringCellValue(); //getting cell value
//return value; //returns the cell value
}
}
codes to get and print data
//read excel cell C2, ignore first row column A1. (int vRow, int vColumn)
def exceldata = CustomKeywords.'test.readexcel.ReadCellData'(2, 2)
String jsondata = JsonOutput.prettyPrint(exceldata.toString())
println(jsondata)
WebUI.delay(1)
//call the object and post the above data as API HTTP request body
def post = ((findTestObject('Object Repository/Web Service Request/test-service/Post')) as RequestObject)
post.setBodyContent(new HttpTextBodyContent(jsondata))
WebUI.delay(2)
//POST and verification
def response = WS.sendRequestAndVerify(post)
println(response.statusCode)
assert response.getStatusCode() == 201
Use the For loop and iterate the loop and get the value
Example
def exceldata="";
for(int row =1;row<=2;row++)
{
for(int col=1;col<=5;col++)
{
exceldata = CustomKeywords.'test.readexcel.ReadCellData'(row,col)
}
}

A loop within a loop in JavaScript

The solution to this may be simple but I cannot seem to think of an easier solution at present. I am using Excel.js and want to add values from an array to a specific set of cells. In this example E6:E25
The problem I face is that I cannot seem to select specific cells, only all of them in a column.
var array = ["4","3","3","3","3","8","2","4","5","2","2","6","4","3","8","5","4","3","2","2"]
workbook.xlsx.readFile('myFile.xlsx')
.then(function() {
var worksheet = workbook.getWorksheet(1);
var column = worksheet.getColumn(5) // Selecting specific column
column.eachCell(function(cell, rownumber){
// eachCell count is 122, ideally not wanting to iterate 122 times
// when only needing 20
switch (cell['_address']) {
case 'E6':
worksheet.getCell(cell['_address']).value = array[0];
break;
case 'E7':
worksheet.getCell(cell['_address']).value = array[1];
break;
case 'E8':
worksheet.getCell(cell['_address']).value = array[2];
break;
// and so on 20 times
default:
}
});
return workbook.xlsx.writeFile('newFile.xlsx');
})
This is awful I know; I am looking to refactor this and make it a lot cleaner and efficient.
Doesn't a simple for loop like this do the same?
var array = ["4","3","3","3","3","8","2","4","5","2","2","6","4","3","8","5","4","3","2","2"];
for (i=0; i<array.length; i++) {
col = i+6;
worksheet.getCell('E'+col).value = array[i];
}

After setting a format and writing some values for a given range, that same format is partially and automatically applied to other ranges

I'm not sure if this is an issue or if it is expected behavior from Excel. If it is indeed expected behavior, I would appreciate an explanation about what is happening, since I cannot see a pattern.
If you set a format and some values to a range and then assign only values to another range located below the first one, the format of the first range is applied partially (randomly?) to the new range.
My test function:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function loadSampleData(applyFormat) {
var columnCount = 30;
if (applyFormat) {
columnCount = 5;
}
var data = [];
for (var rows = 0; rows < 4; rows++) {
var row = [];
for (var columns = 0; columns < columnCount; columns++) {
var value = columns;
if (getRandomInt(1, 3) == 2) {
value = "text";
}
row.push(value);
}
data.push(row);
}
return Excel.run(function (ctx) {
var selectedRange = ctx.workbook.getSelectedRange().load(['rowCount', 'columnCount']);
var extendedRange;
return ctx.sync().then(function () {
var totalRows = data.length;
var totalColumns = data[0].length;
var deltaRows = totalRows - selectedRange.rowCount;
var deltaColumns = totalColumns - selectedRange.columnCount;
extendedRange = selectedRange.getResizedRange(deltaRows, deltaColumns);
if (applyFormat) {
extendedRange.format.fill.color = "orange";
extendedRange.format.font.color = "white";
}
else {
extendedRange.clear();
}
extendedRange.values = data;
}).then(ctx.sync)
}).catch(errorHandler);
}
Steps:
Create one button (Button A) in the task pane. This button must call loadSampleData and pass true, to write some data and format (fill and font color) to a range. (Range A)
Create another button (Button B) in the task pane. This button must call loadSampleData and pass false, to write only data (no format) to a bigger range (Range B).
Click the A1 cell, then click Button A. Notice the range and format that appears.
Click A6, then click Button B. Notice that a bigger range is written and that some of its cells have the same format as the range in step 3, even though no explicit format was set to the range.
With A6 still selected, click Button B multiple times. Notice that as the values of the range change, the formatted cells change as well.
Notes:
This doesn't happen if Range B is written above Range A.
This doesn't happen if Range B is written 4 (or more) rows below Range A.
Thanks!
Fascinatingly, I can reproduce the issue even in the UI, without programmability. Excel is doing some sort of pattern-matching, though I'll admit I have a hard time deciphering what the pattern is...
I will discuss with our team -- but in terms of concrete guidance, I think your safest bet is to set the values, and then clear the formatting. If you want to be super-careful, you can even take it one step further:
Set number formatting (to ensure that strings vs numbers vs date strings get interpreted as you want them to be)
Set the values
range.clear(Excel.ClearApplyTo.formats);
Re-set the number formatting
I will admit that this seems like a workflow worth improving. Let me see if we can either fix "values", or provide a method that lets you set values and number formats in one go, and in a stricter fashion than what is happening today.

AS3 "Advanced" string manipulation

I'm making an air dictionary and I have a(nother) problem. The main app is ready to go and works perfectly but when I tested it I noticed that it could be better. A bit of context: the language (ancient egyptian) I'm translating from does not use punctuation so a phrase canlooklikethis. Add to that the sheer complexity of the glyph system (6000+ glyphs).
Right know my app works like this :
user choose the glyphs composing his/r word.
app transforms those glyphs to alphanumerical values (A1 - D36 - X1A, etc).
the code compares the code (say : A5AD36) to a list of xml values.
if the word is found (A5AD36 = priestess of Bast), the user gets the translation. if not, s/he gets all the possible words corresponding to the two glyphs (A5A & D36).
If the user knows the string is a word, no problem. But if s/he enters a few words, s/he'll have a few more choices than hoped (exemple : query = A1A5AD36 gets A1 - A5A - D36 - A5AD36).
What I would like to do is this:
query = A1A5AD36 //word/phrase to be translated;
varArray = [A1, A5A, D36] //variables containing the value of the glyphs.
Corresponding possible words from the xml : A1, A5A, D36, A5AD36.
Possible phrases: A1 A5A D36 / A1 A5AD36 / A1A5A D36 / A1A5AD36.
Possible phrases with only legal words: A1 A5A D36 / A1 A5AD36.
I'm not I really clear but to things simple, I'd like to get all the possible phrases containing only legal words and filter out the other ones.
(example with english : TOBREAKFAST. Legal = to break fast / to breakfast. Illegal = tobreak fast.
I've managed to get all the possible words, but not the rest. Right now, when I run my app, I have an array containing A1 - A5A - D36 - A5AD36. But I'm stuck going forward.
Does anyone have an idea ? Thank you :)
function fnSearch(e: Event): void {
var val: int = sp.length; //sp is an array filled with variables containing the code for each used glyph.
for (var i: int = 0; i < val; i++) { //repeat for every glyph use.
var X: String = ""; //variable created to compare with xml dictionary
for (var i2: int = 0; i2 < val; i2++) { // if it's the first time, use the first glyph-code, else the one after last used.
if (X == "") {
X = sp[i];
} else {
X = X + sp[i2 + i];
}
xmlresult = myXML.mot.cd; //xmlresult = alphanumerical codes corresponding to words from XMLList already imported
trad = myXML.mot.td; //same with traductions.
for (var i3: int = 0; i3 < xmlresult.length(); i3++) { //check if element X is in dictionary
var codeElement: XML = xmlresult[i3]; //variable to compare with X
var tradElement: XML = trad[i3]; //variable corresponding to codeElement
if (X == codeElement.toString()) { //if codeElement[i3] is legal, add it to array of legal words.
checkArray.push(codeElement); //checkArray is an array filled with legal words.
}
}
}
}
var iT2: int = 500 //iT2 set to unreachable value for next lines.
for (var iT: int = 0; iT < checkArray.length; iT++) { //check if the word searched by user is in the results.
if (checkArray[iT] == query) {
iT2 = iT
}
}
if (iT2 != 500) { //if complete query is found, put it on top of the array so it appears on top of the results.
var oldFirst: String = checkArray[0];
checkArray[0] = checkArray[iT2];
checkArray[iT2] = oldFirst;
}
results.visible = true; //make result list visible
loadingResults.visible = false; //loading screen
fnPossibleResults(null); //update result list.
}
I end up with an array of variables containing the glyph-codes (sp) and another with all the possible legal words (checkArray). What I don't know how to do is mix those two to make legal phrases that way :
If there was only three glyphs, I could probably find a way, but user can enter 60 glyphs max.

Controling do while loop with string

Hi folks this is my question for example i have 3 articles and user can chose any one of them or all of them. In the beginning i ask a user, "do you want to choose some articles?" and if he types yes than we start a while or do while loop that adds prices of all chosen articles and adds them to the total value,
for example article one price is 20 and article 3 price is 40 it should write you have chosen articles one and article three and total price is 60. And when user ends with his choosing he types no and the loop ends.
The real question is my do while loop is always endless i don't know how to stop the loop with a String. This my 10th version of code, i tried everything but really can't solve this problem.
public static void main(String[] args) {
Scanner tastatura = new Scanner(System.in);
System.out.println("Artikal 1\nArtikal 2\nArtikal 3");
System.out.println("Do you want to chose a new article");
String choiseString = tastatura.nextLine();
do {
System.out.println("Chose article ");
int choise = tastatura.nextInt();
switch (choise) {
case 1:
System.out.println("Artikal 1 ");
int price = 10;
break;
case 2:
System.out.println("Artikal 2 ");
price= 20;
break;
case 3:
System.out.println("Artikal 3");
price = 30;
break;
}
} while (choiseString.equalsIgnoreCase("yes") );
}
I believe your issue is that you never give the opportunity for the user to change the value of choiseString.
You allow the user to set the value before the loop begins, but once inside the loop it doesn't change.
Your while loop could instead do something like:
do {
System.out.println("Do you wish to continue?");
choiseString = tastatura.nextLine();
System.out.println("Chose article ");
int choise = tastatura.nextInt();
//rest of your logic here
} while (choiseString.equalsIgnoreCase("yes") );
In this case it would then ask for 1 more choice and then exit the loop (although I haven't tested this code).
I recommend to use a boolean.
This way you will only need to check for true or false, or 1/0.
But the important part is to in some point inside the loop, set that variable to true or false, because if you don't do that, the loop will be an infinite loop.
Once you set the variable to false or true in some point inside the loop, everything will goes fine ;)
I hope this helps

Resources