Right now, I have a program that contains this piece of code:
if(Highest6.y == 0){
if(G.y == Collections.min(YUpper) && !notdone){ Highest6 = G; YUpper.remove(Integer.valueOf(G.y)); notdone = true;}
}
When I run it, I get this error:
The most interesting thing that I have identical snippets, which appear in different HighestX.y statements(I have six of them). And this error occurs only in the last one. Anybody knows why this keeps happening? Thanks in advance.
Here's code for my list:
List<Integer> YPoint = new java.util.ArrayList(Arrays.asList(A.y, B.y, C.y, D.y, E.y, F.y, G.y, K.y, Q.y, L.y, M.y, N.y));
List<Integer> YUpper = new java.util.ArrayList(Arrays.asList());
int Classified = 0;
int Highest = 0;
while(Classified != 6){
Highest = Collections.min(YPoint);
YPoint.remove(Integer.valueOf(Highest));
YUpper.add(Integer.valueOf(Highest));
Classified++;
}
I think the problem is that your collection is empty. From the documentation of Collections min returns:
NoSuchElementException - if the collection is empty
That is: your yUpper Arraylist is empty:
Collections.min(YUpper)
And it's empty because you never enter that while loop:
while(Classified != 6){
As classified is 0
Style note: use camelCase for variables & methods. That's the way Java code is meant to be written. Not MyVar but myVar. It's easier to read to Java people.
Related
So, I never ever programmed JavaScript and never did anything with Google Script before either. I have a fairly good understanding of Visual Basic and macros in Excel and Word. Trying to make a fairly basic program: Plow through a list of variables in a spreadsheet, make a new sheet for each value, insert a formula in this new sheet, cell (1,1).
Debug accepts my program, no issues - however, nothing at all is happening when I run the program:
function kraft() {
var rightHere =
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1:A131");
var loopy;
var goshDarn = "";
for (loopy = 1; loopy < 132; loopy++) {
celly = rightHere.getCell(loopy,1);
vaerdi = celly.getValue();
fed = celly.getTextStyle();
console.log(vaerdi & " - " & fed);
if (vaerdi != "" && fed.isBold == false) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet(vaerdi);
var thisOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(vaerdi);
thisOne.deleteRows(500,500);
thisOne.deleteColumns(5, 23);
thisOne.getRange(1,1).setFormula("=ArrayFormula(FILTER('Individuelle varer'!A16:D30015,'Individuelle varer'!A16:A30015=" & Char(34) & vaerdi & Char(34) & ")))");
}
}
}
activeSheet could be called by name, so could activeSpreadsheet, I guess. But range A1:A131 has a ton of variables - some times there are empty lines and new headers (new headers are bold). But basically I want around 120 new sheets to appear in my spreadsheet, named like the lines here. But nothing happens. I tried to throw in a log thingy, but I cannot read those values anywhere.
I must be missing the most total basic thing of how to get script connected to a spreadsheet, I assume...
EDIT: I have tried to update code according to tips from here and other places, and it still does a wonderful nothing, but now looks like this:
function kraft() {
var rightHere = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1:A131");
var loopy;
var goshDarn = "";
for (loopy = 1; loopy < 132; loopy++) {
celly = rightHere.getCell(loopy,1);
vaerdi = celly.getValue();
fed = celly.getFontWeight();
console.log(vaerdi & " - " & fed);
if (vaerdi != "" && fed.isBold == false) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet(vaerdi);
var thisOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(vaerdi);
thisOne.deleteRows(500,500);
thisOne.deleteColumns(5, 23);
thisOne.getRange(1,1).setFormula("=ArrayFormula(FILTER('Individuelle varer'!A16:D30015,'Individuelle varer'!A16:A30015=" + "\"" + vaerdi + "\"" + ")))");
}
}
}
EDIT2: Thanks to exactly the advice I needed, the problem is now solved, with this code:
function kraft() {
var rightHere = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1:A131");
var loopy;
for (loopy = 1; loopy < 132; loopy++) {
celly = rightHere.getCell(loopy,1);
vaerdi = celly.getValue();
fed = celly.getFontWeight()
console.log(vaerdi & " - " & fed);
if (vaerdi != "" && fed != "bold") {
SpreadsheetApp.getActiveSpreadsheet().insertSheet(vaerdi);
var thisOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(vaerdi);
thisOne.deleteRows(500,499);
thisOne.deleteColumns(5, 20);
thisOne.getRange(1,1).setFormula("=ArrayFormula(FILTER('Individuelle varer'!A16:D30015;'Individuelle varer'!A16:A30015=" + "\"" + vaerdi + "\"" + "))");
}
}
}
There are multiple issues with your script, but the main one is that you never actually call the isBold() function in your 'if' statement.
if (value && format.isBold() == false) {
//do something
}
Because you omitted the parentheses in 'fed.isBold', the expression never evaluates to 'true'. 'isBold' (without the parentheses) is of type Object as it's a function.
There are other issues that prevent the script from running properly:
Not using the 'var' keyword to declare variables and polluting the global scope. As a result, all variables you declare within your 'for' loop are not private to your function. Instead, they are attached to the global object and are accessible outside the function. https://prntscr.com/kjd8s5
Not using the built-in debugger. Running the function is not debugging. You should set the breakpoints and click the debug button to execute your function step-by-step and examine all values as it's being executed.
Deleting the non-existent columns. When you create the new sheet, you call the deleteColums(). There are 26 columns in total. The 1st parameter is the starting column while the 2nd one specifies how many columns must be deleted. Starting from column 5 and telling the script to remove 23 columns will throw an exception. Always refer to the documentation to avoid such errors.
console.log doesn't exist within the context of the Script Editor. You are NOT executing the scripts inside your browser, so Browser object model is not available. Use Logger.log(). Again, this is detailed in the documentation.
Your formula is not formatted properly.
JS is a dynamically typed language that's not easy to get used to. If you don't do at least some research prior to writing code, you'll be in for a lot of pain.
Before reading below, do note that I have only recently started learning Javascript.
I am interested in making a text-based survival game. When trying to subtract a random number of survivors from the whole, I attempted to write what I think is, "A raid happens if the number is 0.50 - 1.00, and if the raid is successful, the group loses a random number of survivors between 1, and however many survivors there are." However, when I write this, I get an ESLint error, stating: ERROR: Parsing error: Unexpected Token if I don't know how I would rewrite it, or how to reformat it to work, if it is at all possible. The issue is in the code below, on lines 10, 11, & 12.
//constants
var EVENT_CHANCE = 0.15;
var EVENT_TYPE = 0.50;
var FOOD_CONSUMPTION = FOOD_CONSUMPTION;
var MATERIALS_CONSUMPTION = 1;
var ENEMY_STRENGTH = 10;
var SURVIVOR_STRENGTH = 1;
//equations
this.FOOD_CONSUMPTION = (this.food - this.surviors);
this.raid = if ( EVENT_TYPE > 0.50);{
this.survivors - Math.floor((Math.random() * this.surviors) + 1);
};
Let me know if I left anything important out
Note: I copied this post from the game development stack exchange, because they had advised me it is more of a stack overflow question, as it relates more to JS as a whole, than game development.
You have a semicolon after the condition
To conditionally assign a variable you need to use the ternary operator, for example:
const thing = condition ? ifTrue : ifFalse;
Or for your code:
this.raid = EVENT_TYPE > 0.50 ?
this.survivors - Math.floor((Math.random() * this.surviors) + 1) :
null;
//replace the null with what you want the variable to be if the condition is false
You can't use a statement as the right-hand side of an assignment, which is what you're trying to do here:
this.raid = if ( EVENT_TYPE > 0.50);{
this.survivors - Math.floor((Math.random() * this.surviors) + 1);
};
If you want to set this.raid to the result of EVENT_TYPE > 0.50, you just do that directly:
this.raid = EVENT_TYPE > 0.50;
If you then want to use that in a branch, you can follow it with the if testing this.raid:
this.raid = EVENT_TYPE > 0.50;
if (this.raid) {
this.survivors - Math.floor((Math.random() * this.survivors) + 1);
}
(I also fixed a typo in that, the second survivors was missing a v. But there's still a problem I didn't know how to fix: It calculates a value without storing it anywhere. It's not an error in JavaScript, but it probably isn't what you wanted. You may have meant -= instead of -.)
Note that neither of the ; that were originally in that if belonged there. You don't put ; after the () in an if, and you don't put a ; after the block attached to a flow-control statement (if, while, etc.).
I'm attempting to write some code that puts a single string of emails into an array of emails. Splitting the string wherever there's a comma(,). The initial problem i'm having is the string that is being passed as a variable is not being recognized. I'm getting the error message "Cannot read property 'length' of undefined" of the conditional part of the for loop. Odd, as I'm definitely passing a string or trying to ?
When I pass in a string directly to the function parameter(to avoid the above problem for testing the rest of the function) only the first 2 email addresses appear the final email address is lost ?
I'm learning programming and this is an exercise as such I'm trying to avoid using the split() method or regEx. Daft i know.
Any help in overcoming these 2 issues greatly appreciated.
function separateCommaValues(text)
{
var input = [];
var val = '';
for(var i = 0; i < text.length; i++) {
if(text[i] == ',') {
if(val.length == 0){
continue;
}
input.push(val);
val = '';
} else {
val += text[i];
}
}
document.write( input );
}
separateCommaValues(str);
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
separateCommaValues(str);
This is the correct order. Your variable can be declared before it is used via hoisting, but you can't define it before it is used (undefined error).
And the last email address isn't pushed into the array because it doesn't have a comma after it. So after the loop, before document.write( input );, add something like this:
if(val.length > 0){
input.push(val);
val = '';
}
I'm writing a script that's going to take some information about the website that you visit. I have copied this small portion of my code that I'm struggling with. This part of the code is supposed check if the visited website is using the www prefix and remove that prefix, then there is another part of the code that I haven't pasted stores the domain name in the variable website.
var website = location.hostname;
document.getElementById("displayBefore").innerHTML = website; //test to see the variable
if (website[0] == 'w' && website[1] == 'w' && website[2] == 'w' && website[3] == '.') {
document.getElementById("displayTrue1").innerHTML = "true"; //test to see if the conditional was met
for (i = 4; i < website.length; i++) {
website[i - 4] = website[i]; //this is not rewriting anything
document.getElementById("displayPos0").innerHTML = website[i]; //test to see if the for loop has run
}
document.getElementById("displayDuring").innerHTML = website; //test to see the variable
website.splice(0, 4); //this is breaking everything after it
document.getElementById("displayAfter").innerHTML = website; //test to see the variable
}
Here is what's actually being displayed when in those tests when I pull it up in a browser:
WebsiteBeforeFix: www.example.com
True1: true
website[i]: m
WebsiteDuringFix: www.example.com
WebsiteAfterFix:
The two parts of the code that aren't working are the following:
website[i - 4] = website[i];
This is supposed to pretty much shift the letters over 4 spaces to the left(eliminating "www.").
website.splice(0,4);
This is actually causing nothing after it to display at all in any of the code that does work. Can anyone tell me what I may be doing wrong?
splice is an array method, not for strings (they're immutable). Make the variable an array to manipulate it using the split method, and join it back together using the join method:
var websiteStr = location.hostname;
var website = websiteStr.split('');
console.log("displayBefore: " + website.join(''));
if (websiteStr.indexOf("www.") === 0) {
console.log("true");
/*for (var i = 4; i < website.length; i++) {
website[i - 4] = website[i];
console.log("displayPos0: " + website[i]);
}*/
console.log("displayDuring: " + website.join(''));
website.splice(0, 4);
console.log("displayAfter: " + website.join(''));
}
Instead of manipulating HTML, you can use console.log to do basic logging at particular points, which will show up in your browser's console. Anyway, it seems that your for loop doesn't do what you want it to -- splice already removes the "www." prefix.
You can also change this:
if (website[0] == 'w' && website[1] == 'w' && website[2] == 'w' && website[3] == '.') {
to this:
if (websiteStr.indexOf("www.") === 0) {
which performs the same thing much more concisely.
With the fixed code, it now displays:
displayBefore: www.google.com
true
displayDuring: www.google.com
displayAfter: google.com
For this question, it might be a little vague, because i just dont understand it at all, its probably the wording.. from what i learn in class it seems a lot harder. So im lost as to where to begin.. if someone can help walk me through it easier i would appreciate it!
Question: Design a Program that will read the same parts inventory file described in the problem 6. the parts are: (Record code, part number, part description, and inventory balance) validate the record code and part number on each record, and print the details of all valid records whose part numbers fall within the value AA3000 and AA3999 inclusive. Also print a count of these selected records at the end of the parts listing.
Now, i hope you can understand what its asking because i sure dont. Any help or a small walk through would be awesome. This is the code i am supposed to start out from that was given to me.
var Rec_Code = new Array(11,11,11,12,11,12,11,13,11,14);
var Numer = new Array(2000,3000,3003,3008,3999,2000,1090,3678,3777,3543);
var Alpha = new Array("AA","AA","AX","AA","AA","AA","AB","AA","AN","AA");
var Desc = new Array("X","L","S","F","R","U","T","N","Q","Y");
var Inv_Bal = new Array(12,13,14,23,34,56,32,45,67,77);
also, this was given to me, which is basically what i have to do, but dont know how to completely do it.
use the vars that I provided to create 5 parallel arrays, RecCode, AlphaPart of part number, Numeric part of the part number,Description and Inventory. You need to search the first 3 arrays for:
RecCode of 11
AlphaCode of 'AA':
Numeric Code betweewn 3000 - 3999 inclusive
when you find a match increment a count and display the Description and Inventory.
Assuming that all arrays are the same length and sorted appropriately, you can loop over one and display the information you need:
var count = 0;
for(var i = 0; i < Rec_Code.length; i++)
{
if(Rec_Code[i] == 11 && Alpha[i] == 'AA' && (Numer[i] >= 3000 && Numer[i] <= 3999))
{
console.log(Desc[i]);
console.log(Inv_Bal[i]);
count++;
}
}
var Rec_Code = new Array(11,11,11,12,11,12,11,13,11,14);
var Numer = new Array(2000,3000,3003,3008,3999,2000,1090,3678,3777,3543);
var Alpha = new Array("AA","AA","AX","AA","AA","AA","AB","AA","AN","AA");
var Desc = new Array("X","L","S","F","R","U","T","N","Q","Y");
var Inv_Bal = new Array(12,13,14,23,34,56,32,45,67,77);
var count = 0;
for(var i = 0; i < Rec_Code.length; i++)
{
if(Rec_Code[i] == 11 && Alpha[i] == 'AA' && (Numer[i] >= 3000 && Numer[i] <= 3999))
{
console.log(Desc[i]);
console.log(Inv_Bal[i]);
count++;
}
}