Studio won't print array elements when I test. (Java) - eclipse

I'm working with eclipse and when I want the program to print either all the array elements or just a single array element via indexing. It doesn't return an error or even an address when I run the program.
import java.util.Scanner;
public class FavoriteListMaker {
public static void main(String[] args)
{
Scanner inputDevice = new Scanner(System.in);
System.out.println("This program is to help you order a favorites list. Please enter the amount of items on the list.");
int ListSize = inputDevice.nextInt();
String [] TopXA = new String [ListSize + 1];
int [] TopXB = new int[ListSize + 1];
for (int x = 0; x < TopXA.length; ++ x)
{
System.out.println("Please enter an item to be organized on the list");
String item = inputDevice.nextLine();
TopXA[x] = item;
System.out.println("You have " + (ListSize - x) + " items left to fill on the list.");
}
System.out.println("Now we will compare each item on the list with every item on the list one at a time.");
System.out.println("We will ask you a series a question on whether you like item A better then item B and tally the score.");
System.out.println("At the end the item with the most points wins.");
for (int y = 0; y < TopXA.length; ++ y)
for (int z = 0; z < TopXA.length; ++ z)
{
String compareA = TopXA[y];
String compareB = TopXA[z];
System.out.println("Do you prefer " + compareA + " or " + compareB + " .");
System.out.println("If you prefer " + compareA + "Please press 1. If you prefer " + compareB + " please press 2.");
int choice = inputDevice.nextInt();
switch(choice)
{
case 1:
TopXB[y] =+ 1;
break;
case 2:
TopXB[z] =+ 2;
break;
default:
System.out.print("I'm sorry but that is not a valid input.");
}
}
When I run the code it will print out. "Do you prefer or ." instead of the array element.

Disclaimer - I don't have eclipse, I dont program in Java
Please check two things
1) The for loop for y doesn't have curly brackets
2) Please check array 'TopXA' to see if 'item' is being populated in array once you input it.
3) Are CompareA and CompareB being assigned values?
EDIT - found problem
Add scanner.nextLine(); after the nextINt line.

Your problem is that the nextInt() method is not consuming the newline character (see other question). This leads to the fact that your first element in the list is empty. In the first iteration (y=0, z=0) of the nested for-loops this empty element gets printed two times.
Try adding inputDevice.nextLine() after each nextInt() call and you will see that it is working ;)
And PLEASE: Don't name variables uppercase!
import java.util.Scanner;
public class FavoriteListMaker {
public static void main(String[] args)
{
Scanner inputDevice = new Scanner(System.in);
System.out.println("This program is to help you order a favorites list. Please enter the amount of items on the list.");
int listSize = inputDevice.nextInt();
inputDevice.nextLine();
String [] topXA = new String [listSize];
int [] topXB = new int[listSize];
for (int x = 0; x < topXA.length; ++x)
{
System.out.println("Please enter an item to be organized on the list");
String item = inputDevice.nextLine();
topXA[x] = item;
System.out.println("You have " + (listSize - x) + " items left to fill on the list.");
}
System.out.println("Now we will compare each item on the list with every item on the list one at a time.");
System.out.println("We will ask you a series a question on whether you like item A better then item B and tally the score.");
System.out.println("At the end the item with the most points wins.");
for (int y = 0; y < topXA.length; ++y)
{
for (int z = 0; z < topXA.length; ++z)
{
String compareA = topXA[y];
String compareB = topXA[z];
System.out.println("Do you prefer " + compareA + " or " + compareB + " .");
System.out.println("If you prefer " + compareA + "Please press 1. If you prefer " + compareB + " please press 2.");
int choice = inputDevice.nextInt();
inputDevice.nextLine();
switch(choice)
{
case 1:
topXB[y] =+ 1;
break;
case 2:
topXB[z] =+ 2;
break;
default:
System.out.print("I'm sorry but that is not a valid input.");
}
}
}
}
}

Related

Flutter - How to use data from equal built classes?

I want to build an app for my pupil which generates tasks out of sentence blocks.
For example I created two classes, apple and pear, with nearly the same structure. They return a question built out of the sentence blocks which are defined in the classes. In both classes is a GenerateQuestion()-function for that.
Now I want to build some kind of overclass, which picks a random class of i.e. apple or pear and then returns the strings from the functions. The functions names are the same, but I can't figure out how to get data from a random choosen class. Hoping for help. Thanks in advance.
Update: Here is the code I wrote so far (I tried to translate it properly):
import 'dart:math';
int randomminmax1 = 0;
int randomminmax2 = 0;
int randomminmax3 = 0;
List classes = [apple, pear];
class overClass {
static pickClass(){
int randomClassItem = Random().nextInt(classes.length);
print(classes[randomClassItem]);
return classes[randomClassItem];
}
}
class apple {
static String giveQuestion() {
randomminmax1 = 2 + Random().nextInt(15 - 2);
randomminmax2 = randomminmax1 * (2+Random().nextInt(12 - 2));
randomminmax3 = 2 + Random().nextInt(30 - 2);
List value_1 = [" boxes", " bags", " bucket"];
List verbs = ["cost","have a price of", "are offered for"];
List value_2 = ["Euro"];
List questionWords = [""];
int randomIndexValue1 = Random().nextInt(value_1.length);
int randomIndexVerbs = Random().nextInt(verbs.length);
int randomIndexValue2 = Random().nextInt(value_2.length);
String value = randomminmax1.toString() + value_1[randomIndexValue1].toString() + " apples" + verbs[randomIndexVerbs].toString() + " " + randomminmax2.toString() + " " + value_2[randomIndexValue2].toString() + ".\n";
String question = "How much are " + randomminmax3.toString() + value_1[randomIndexValue1].toString() + "?\n";
return value + question;
}
static String giveAnswer(){
double result = (randomminmax2/randomminmax1)*randomminmax3;
return result.toStringAsFixed(2) + " Euro.";
}
}
class pear {
static String giveQuestion() {
randomminmax1 = 2 + Random().nextInt(15 - 2);
randomminmax2 = randomminmax1 * (2+Random().nextInt(12 - 2));
randomminmax3 = 2 + Random().nextInt(30 - 2);
List value_1 = [" boxes", " bags", " bucket"];
List verbs = ["cost","have a price of", "are offered for"];
List value_2 = ["Euro"];
List questionWords = [""];
int randomIndexValue1 = Random().nextInt(value_1.length);
int randomIndexVerbs = Random().nextInt(verbs.length);
int randomIndexValue2 = Random().nextInt(value_2.length);
String value = randomminmax1.toString() + value_1[randomIndexValue1].toString() + " pears" + verbs[randomIndexVerbs].toString() + " " + randomminmax2.toString() + " " + value_2[randomIndexValue2].toString() + ".\n";
String question = "How much are " + randomminmax3.toString() + value_1[randomIndexValue1].toString() + "?\n";
return value + question;
}
static String giveAnswer(){
double result = (randomminmax2/randomminmax1)*randomminmax3;
return result.toStringAsFixed(2) + " Euro.";
}
}
static String giveAnswer(){
double result = (randomminmax2/randomminmax1)*randomminmax3;
return result.toStringAsFixed(2) + " Euro.";
}
}
Can you try to create a superclass that all question classes will inherit and then get the subclasses and programmatically call functions. Try to see here
At least I managed to give my values directly from the classes into the list. But then I got problems with the int-variables, which were built wrong.
My "solution": I converted my classes into isolated flutter widgets, which works fine, except the problem that I'm not able to put the widgets into a list, from where they are picked randomly...but therefore I'll write a new post.
Thank you Moustapha for your help (the superclass idea sounds good, but way too hard to code for me) ;)!

Google/OR-Tools Get Duration And Distance

I'm trying to understand the solution call in the MVRP examples
I have two matrixes, duration and distance that have been returned via calls to google
My solution is based on distance but given that i have the data already returned i want to find the index associated with the duration.
unfortunately I'm not sure completely what is going on under the hood of the the Routing Calls so hoping for a simple fast answer for look up and what index to use
for simplicity sake I will show the google example rather than my code and highlight what im looking for:
public string PrintSolution()
{
// Inspect solution.
string ret = "";
long maxRouteDistance = 0;
for (int i = 0; i < _data.Drivers; ++i)
{
ret += $"Route for Vehicle {i}:";
ret += Environment.NewLine;
long routeDistance = 0;
var index = _routing.Start(i);
while (_routing.IsEnd(index) == false)
{
ret += $"{_manager.IndexToNode((int) index)} -> ";
var previousIndex = index;
index = _solution.Value(_routing.NextVar(index));
long legDistance = _routing.GetArcCostForVehicle(previousIndex, index, i);
//LOOKING FOR
//long legDuration = ??? what index am is using here to find in my duration matrix which is built the same as indexes as distance
ret += " leg distance: " + legDistance;
routeDistance += legDistance;
}
ret += $"{_manager.IndexToNode((int) index)}";
ret += Environment.NewLine;
ret += $"Distance of the route: {routeDistance}m";
ret += Environment.NewLine;
ret += Environment.NewLine;
maxRouteDistance = Math.Max(routeDistance, maxRouteDistance);
}
ret += $"Maximum distance of the routes: {maxRouteDistance}m";
ret += Environment.NewLine;
return ret;
}
#Mizux
disclaimer: This is a simplification but should help you to understand.
In OR-Tools Routing there is a primal "hidden" dimension without name but you can retrieve the cost using RoutingModel::GetArcCostForVehicle()
For any "regular" dimension you can get inspect the CumulVar at each node.
e.g. supposing you have created two dimensions using RoutingModel::AddDimension() whose name were "Distance" and "Duration".
note: CumulVar is an accumulator so if you want the "arc cost" you'll need something like this dim.CumulVar(next_index) - dim.CumulVar(index)
Then in you PrintFunction you can use:
public string PrintSolution()
{
...
RoutingDimension distanceDimension = routing.GetMutableDimension("Distance");
RoutingDimension durationDimension = routing.GetMutableDimension("Duration");
for (int i = 0; i < _manager.getNumberOfVehicles(); ++i)
{
while (_routing.IsEnd(index) == false)
{
...
IntVar distanceVar = distanceDimension.CumulVar(index);
IntVar durationVar = durationDimension.CumulVar(index);
long distance = _solution.Value(distanceVar);
long duration = _solution.Value(durationVar);
...
}
}
}

Flutter, Dart Split sentence every one character to 2 characters size, for flutter custom tts project

Example:
var sentence = (hello there, I am Bob.)
var result = [
'he',
'el',
'll',
'lo',
' ',
'th',
'he',
'er',
're',
',',
' ',
'I',
' ',
'am',
' ',
'bo',
'ob',
'.']
I've found here working example, though it is in Javascript and I don't really know how to adopt it for Dart, and not sure how will behave once white space and punctuation is added in. Punctation and white space I need always split on its own not in combination with letters, I need them as well, as I will use them to add pauses in between words and sentences.
Thank you
var a = 12345678;
a= a.toString();
var arr=[];
for (var i =0; i<a.length-1; i++) {
arr.push(Number(a[i]+''+a[i+1]));
}
console.log(arr);
You could use regular expressions to split the sentence. For example:
void main() {
var exp = RegExp('([A-Za-z]{1,2}|[,!.?\s ])');
var str = "hello there, I am Bob.";
var matches = exp.allMatches(str);
for (var m in matches) {
print(m.group(0));
}
}
This looks for letters (A-Z or a-z) in groups of either 1 or 2, or single punctuation characters (,!.?) \s represents a white space.
Running the above would produce:
he
ll
o
th
er
e
,
I
am
Bo
b
.
Another approach
void main() {
var a = "1234!5678";
a = a.toString();
var arr = [];
for (var i = 0; i < a.length - 1; i++) {
if (a[i + 1] == '!') {
continue;
}
if (a[i] == '!') {
arr.add(a[i]);
continue;
}
arr.add(a[i] + '' + a[i + 1]);
}
print(arr);
}
I don't know dart much but I wrote this simple algorithm on dartpad and it works
If someone is having same issue, this is how I solved it
void main(String string) {
var test = "I Hello there I am Bob 23!";
List<String> nameArray = test.split('');
for (int curIndex = 0; curIndex < nameArray.length; curIndex++) {
if (curIndex >= 1 && nameArray[curIndex].contains(new RegExp(r'[a-zA-Z]')) && nameArray[curIndex-1].contains(new RegExp(r'[a-zA-Z]'))) {
print(nameArray[curIndex-1] + nameArray[curIndex]); // checks if current curIndex and previous curIndex are letters, if so returns previous and curent letters joined
} else {
if (curIndex >= 1 && nameArray[curIndex].contains(new RegExp(r'[a-zA-Z]')) && nameArray[curIndex+1].contains(new RegExp(r'[a-zA-Z]'))) {
null; // checks if curIndex and next curIndex are letters, if so returns null
}else{
print(nameArray[curIndex]);
}
}
}
}
Which returns
I
He
el
ll
lo
th
he
er
re
I
am
Bo
ob
2
3
!

How to use doOnNext, doOnSubscribe and doOnComplete?

New to RxJava2/RxAndroid and Android development, but am pretty familiar with Java.
However, I've ran into quite a roadblock when trying to "optimize" and be able to update the UI between a bunch of calls to the same resource.
My code is as follows:
private int batch = 0;
private int totalBatches = 0;
private List<ItemInfo> apiRetItems = new ArrayList<>();
private Observable<ItemInfo[]> apiGetItems(int[] ids) {
int batchSize = 100;
return Observable.create(emitter -> {
int[] idpart = new int[0];
for(int i = 0; i < ids.length; i += batchSize) {
batch++;
idpart = Arrays.copyOfRange(ids, i, Math.min(ids.length, i+batchSize));
ItemInfo[] items = client.items().get(idpart);
emitter.onNext(items);
}
emitter.onComplete();
}).doOnSubscribe( __ -> {
Log.d("GW2DB", "apiGetItems subscribed to with " + ids.length + " ids.");
totalBatches = (int)Math.ceil(ids.length / batchSize);
progressbarUpdate(0, totalBatches);
}).doOnNext(items -> {
Log.d("GW2DB", batch + " batches of " + totalBatches + " batches completed.");
progressbarUpdate(batch, totalBatches);
}).doOnComplete( () -> {
Log.d("GW2DB", "Fetching items completed!");
progressbarReset();
});
}
If I remove the doOnSubscribe, doOnNext and doOnComplete I get no errors in Android Studio, but if I use any of them I get Incompatible types. Required: Observable<[...].ItemInfo[]>. Found: Observable<java.lang.Object>
I'm using RxAndroid 2.1.1 and RxJava 2.2.16.
Any ideas?
Since you are adding a chain of method calls, the compiler is just unable to correctly guess the type for the generic parameter in Observable.create. You can set it explicitly using Observable.<ItemInfo[]>create(...).

Google Apps Script: How to pull values from column A based on values in column E and send all values in one email?

I'm trying to create a script for a student attendance spreadsheet that will look in Column E for the string "X". For each instance of "X", the string from column A (the student name) will be added to the body of an email. I'm pretty new to JavaScript, although I have been studying the basics. I've done a lot of research and found some scripts I was able to modify to send an individual email for each instance of X in E. However, I have not been able to figure out how to combine that information into a single email.
Here's what I have so far:
function Email_ReminderNS() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("July_August"),
EMAIL_SENT = "EMAIL_SENT",
statusArray = sheet.getDataRange().getValues();
var class = statusArray[0][8],
status = "X",
email = "XXXX"
for (i=7;i < statusArray.length;i++){
var emailSent = statusArray[i][84];
if (status == statusArray[i][4] & emailSent != EMAIL_SENT) {
var student = statusArray[i][0];
var body = "This is a No-Show Report for " +student+ " from " + class;
var subject = "No-Show Report for " + student+ " from " + class;
MailApp.sendEmail(email,subject,body,{NoReply : true});
sheet.getRange(i+1, 85).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
I realize I'll probably need to move the sendEmail function to be outside the IF statement. I tried to create an array with the names and join those into a string and add it to the body of the email, but I've had no luck. It just ended up sending the last name instead of all of them.
If anyone has any suggestions for me I would be deeply grateful.
First set up variables to keep track of which student did not show up:
var students = [];
var student_rows = [];
Then, add student to these arrays when X is found:
if (status == statusArray[i][4] & emailSent != EMAIL_SENT) {
var student = statusArray[i][0];
students.push(student);
student_rows.push(i+1);
}
Then send the email with all student names combined (outside of the for loop like you said)
var body = "This is a No-Show Report for " + students.join(', ') + " from " + class;
var subject = "No-Show Report for " + students.join(', ') + " from " + class;
MailApp.sendEmail(email,subject,body,{NoReply : true});
Finally update the spreadsheet indicating which names were in that email:
for (var i=0; i<student_rows.length; i++) {
sheet.getRange(student_rows[i], 85).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
Here's the complete script:
function Email_ReminderNS() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("July_August"),
EMAIL_SENT = "EMAIL_SENT",
statusArray = sheet.getDataRange().getValues();
var class = statusArray[0][8],
status = "X",
email = "francis#bposolutions.com";
var students = [];
var student_rows = [];
for (i=7;i < statusArray.length;i++){
var emailSent = statusArray[i][84];
if (status == statusArray[i][4] & emailSent != EMAIL_SENT) {
var student = statusArray[i][0];
students.push(student);
student_rows.push(i+1);
}
}
var body = "This is a No-Show Report for " + students.join(', ') + " from " + class;
var subject = "No-Show Report for " + students.join(', ') + " from " + class;
MailApp.sendEmail(email,subject,body,{NoReply : true});
for (var i=0; i<student_rows.length; i++) {
sheet.getRange(student_rows[i], 85).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
There are probably many ways to implement a new version of your code, the other answer probably works but I think it can be improved (a bit).
First of all, you can get rid of the flush method that does nothing else than slowing down the function (it was originally used in the Google example to check the sent status row by row, it is useless when we send only one mail with all the data in it)
Secondly, it might be a good idea to use html format to get a better looking result.
And lastly, it is good practice to write back to the sheet using one setValues instead of multiple setValue() in a loop.
Here is a possible replacement code, you'll have to "tune" it to your needs to eventually improve the message format but the main structure is there and working.
function Email_ReminderNS() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("July_August"),
statusArray = sheet.getDataRange().getValues();
var email = Session.getActiveUser().getEmail(); //replace with the email you want, this value will send mails to you I used it for test.
var class = statusArray[0][8],
status = "X",
students = [];
for (var i=7;i < statusArray.length; i++){
var emailSent = statusArray[i][84];
if (status == statusArray[i][4] & emailSent != "EMAIL_SENT") {
students.push(statusArray[i][0]);
statusArray[i][84]="EMAIL_SENT";
}
}
var subject = "No-Show Report for " + students.length + " from " + class;
var textBody = "This is a No-Show Report for " +students.length+ " from " + class+"\n";
var HTMLBody = "<b>This is a No-Show Report for " +students.length+ " from " + class+"</b><br><br>"
+'<table style="background-color:lightblue;border-collapse:collapse;" border = 1 cellpadding = 5><th>Sent Mails</th><tr>';
for(var n in students){
HTMLBody += '<tr><td>'+n+'</td><td>'+statusArray[n][0]+'</td></tr>';
textBody += '\n'+n+' - '+statusArray[n][0];
}
HTMLBody+='</table><BR> kind regards.' ;
textBody+='\n\nKind regards';
Logger.log(HTMLBody);
Logger.log(textBody);
MailApp.sendEmail(email,subject,textBody,{'NoReply' : true, 'htmlBody' : HTMLBody});
sheet.getRange(1,1,statusArray.length,statusArray[0].length).setValues(statusArray);
}