Loop assignment count entries - loops

I have an assignment where I am supposed to take grades entered and output the amount of each grade and the percentage of that grade. The loop should stop when a negative number is entered. I think I have it now but I can't get it to compile.
import java.util.Scanner;
public class Homework6_Project1
{
public static void main (String[] args)
{
Scanner Keyboard = new Scanner(System.in);
double count = Keyboard.nextDouble();
gradecounter:
do
{
for (int i = 0; i < count; i++)
{
System.out.println("Enter the grade:");
int Grade = Keyboard.nextInt();
}
if (Grade >=90)
{
int CountA = 0;
int A = Grade;
double AverageA = A/count;
++CountA;
}
if (Grade<89 && Grade>=80)
{
int CountB = 0;
int B = Grade;
double AverageB = B/count;
++CountB;
}
if (Grade < 80 && Grade >=70)
{
int CountC = 0;
int C = Grade;
double AverageC = C/count;
++CountC;
}
if (Grade < 70 && Grade >= 60)
{
int CountD = 0;
int D = Grade;
double AverageD = D/count;
++CountD;
}
if (Grade < 60 && Grade >= 0)
{
int CountF = 0;
int F = Grade;
double AverageF = F/count;
++CountF;
}
while (Grade < 0)
{
System.out.println("Count of A grade's:" + " " + CountA + " Percentage of A's:" + " " + AverageA);
System.out.println("Count of B grade's:" + " " + CountB + " Percentage of B's:" + " " + AverageB);
System.out.println("Count of C grade's:" + " " + CountC + " Percentage of C's:" + " " + AverageC);
System.out.println("Count of D grade's:" + " " + CountD + " Percentage of D's:" + " " + AverageD);
System.out.println("Count of F grade's:" + " " + CountF + " Percentage of F's:" + " " + AverageF);
break gradecounter;
}
}
}
}

Related

Convert arabic number (long long int) to words in C

I would like to convert a number, let's say, 1024 or 2345787654 into english words, such that for 1024 it should print one thousand twenty four etc.
However, my code gives me segmentation fault. I tried to run it with gdb but is suggests that the problem is inside my_strcat function. However, I do not see any problem with this function. Please, help.
#include <stdlib.h>
#include <string.h>
const char *digits[] = { NULL, "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine " };
const char *tens[] = { NULL, "ten ", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety " };
const char *teens[] = { "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " };
const char *scales[] = { "", "thousand ", "million ", "billion " };
char *my_strcat ( char **dest, const char * src)
{
char *tab = malloc ( sizeof ( char) * (strlen ( *dest) + strlen ( src) + 1));
if ( NULL == tab)
return NULL;
strcpy ( tab, *dest);
strcat ( tab, src);
free ( *dest);
*dest = malloc ( sizeof ( char) * ( strlen ( tab) + 1));
strcpy ( *dest, tab);
return tab;
}
char * LongToEnglish(unsigned long x)
{
switch(x)
{
case 0:
return "Zero";
case 1:
return "One";
case 2:
return "Two";
case 3:
return "Three";
case 4:
return "Four";
case 5:
return "Five";
case 6:
return "Six";
case 7:
return "Seven";
case 8:
return "Eight";
case 9:
return "Nine";
case 10:
return "Ten";
case 11:
return "Eleven";
case 12:
return "Twelve";
case 13:
return "Thirteen";
case 14:
return "Fourteen";
case 15:
return "Fifteen";
case 16:
return "Sixteen";
case 17:
return "Seventeen";
case 18:
return "Eighteen";
case 19:
return "Nineteen";
case 20:
return "Twenty";
case 30:
return "Thirty";
case 40:
return "Forty";
case 50:
return "Fifty";
case 60:
return "Sixty";
case 70:
return "Seventy";
case 80:
return "Eighty";
case 90:
return "Ninety";
case 100:
return "One Hundred";
case 1000:
return "One Thousand";
case 1000000:
return "One Million";
case 1000000000:
return "One Billion";
}
// less than 100
for (long i = 1; i <= 9; i ++)
{
long j = i * 10;
if ((x >= j) && (x < j + 10))
{
long r = x - j;
if(r > 0)
return my_strcat(my_strcat(*LongToEnglish(j), " "), LongToEnglish(r));
else
return my_strcat(*LongToEnglish(j), "");
}
}
// less than 1000
for (long i = 1; i <= 9; i ++)
{
long j = i * 100;
if ((x >= j) && (x < j + 100))
{
long r = x - j;
if(r > 0)
return my_strcat(my_strcat(LongToEnglish(i), " Hundred "), LongToEnglish(r));
else
return my_strcat(LongToEnglish(i), " Hundred");
}
}
// less than 10000
for (long i = 1; i <= 9; i ++)
{
long j = i * 1000;
if ((x >= j) && (x < j + 1000))
{
long r = x - j;
if(r > 0)
return my_strcat(my_strcat(LongToEnglish(i), " Thousand "), LongToEnglish(r));
else
return my_strcat(LongToEnglish(i), " Thousand");
}
}
// Million
for (long i = 1; i <= 9; i ++)
{
long j = i * 1000000;
if ((x >= j) && (x < j + 1000000))
{
long r = x - j;
if(r > 0)
return my_strcat(my_strcat(LongToEnglish(i), " Million "), LongToEnglish(r));
else
return my_strcat(LongToEnglish(i), " Million");
}
}
// Billion
for (long i = 1; i <= 4; i ++)
{
long j = i * 1000000000;
if ((x >= j) && (x < j + 1000000000))
{
long r = x - j;
if(r > 0)
return my_strcat(my_strcat(LongToEnglish(i), " Billion "), LongToEnglish(r));
else
return my_strcat(LongToEnglish(i), " Billion");
}
}
// Divide the number into 3-digit groups from left to right
char* output = "";
long cnt = 0;
while (x > 0)
{
long y = x % 1000;
x /= 1000;
if (y > 0) // skip middle-chunk zero
{
char * t = "";
if (cnt == 1) t = " Thousand ";
if (cnt == 2) t = " Million ";
if (cnt == 3) t = " Billion ";
output = my_strcat(my_strcat(LongToEnglish(y), t), output);
}
cnt ++;
}
return (output);
}
char* numberToWords(int num)
{
return LongToEnglish(num);
}
int main(int argc, char **argv)
{
char *dst = NULL;
dst = malloc ( sizeof ( char) * 10000000);
unsigned long long n = 122334;
dst = numberToWords(n);
printf("%s", dst);
free(dst);
return 0;
}
There are other problems in your code, I tell just one. When input is n=3 in main, numberToWords returns "Three" and you try to call free("Three"), etc.
You return a static string sometimes and try to free it for this particular case.
The task is for groups of thousands allways the same. So you can do it much less complicated.
The string handling might be optimized...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *digits[] = { NULL, "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " };
const char *tens[] = { NULL, "ten ", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety " };
const char *scales[] = { "", "thousand ", "million ", "billion " };
char *long2words(long x, int grp) {
char *buf = malloc(4096), *bp;
int e,t,h;
*buf='\0';
e = x%10;
t = (x/10)%10;
h = (x/100)%10;
x /=1000;
if(x!=0) {
strcat(buf, bp=long2words(x,grp+1));
free(bp);
}
if(h!=0) {
strcat(buf, digits[h]);
strcat(buf,"hundred ");
}
if(t<2) strcat(buf, digits[t*10+e]);
else {
strcat(buf, tens[t]);
strcat(buf, digits[e]);
}
strcat(buf, scales[grp]);
return buf;
}
int main()
{
printf(long2words(102410241024,0));
return 0;
}

How to put dynamic array in function C#?

This my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class RetardedStudent
{
public String Name = "1";
public int IQ;
public void PrintName()
{
Console.Write("Student Name ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(Name);
Console.ResetColor();
Console.Write(" Student Test Result: ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(IQ);
Console.ResetColor();
Console.WriteLine();
}
}
public class Program
{
public unsafe void SortRetardedStudents(RetardedStudent[] Retards)
{
int IQ;
string Name;
int RetardsNumber = Retards.Length;
for (int i = 0; i < RetardsNumber; i++)
{
for (int j = 0; j < RetardsNumber - i - 1; j++)
{
if (Retards[j].IQ > Retards[j + 1].IQ || (Retards[j].IQ == Retards[j + 1].IQ) && (String.Compare(Retards[j].Name, 0, Retards[j + 1].Name, 0, Math.Max(Retards[j].Name.Length, Retards[j + 1].Name.Length)) > 0))
{
IQ = Retards[j].IQ;
Name = Retards[j].Name;
Retards[j].IQ = Retards[j + 1].IQ;
Retards[j].Name = Retards[j + 1].Name;
Retards[j + 1].IQ = IQ;
Retards[j + 1].Name = Name;
}
}
}
}
static void Main(string[] args)
{
unsafe
{
Console.Write("Input number of students:");
Console.WriteLine();
int RetardsNumber;// = Convert.ToInt32(Console.ReadLine());//Convert не прокатывает если ввести не число
Int32.TryParse(Console.ReadLine(), out RetardsNumber);//на случай ввода не числа не будет вылета - будет словно ввели 0
if (RetardsNumber < 1)
{
Console.WriteLine("You entered zero/nonnumeric values as number of students. Programm execution is finished");
Console.ReadLine();
return;
}
RetardedStudent[] Retards = new RetardedStudent[RetardsNumber];
for (int i = 0; i < RetardsNumber; i++)//fill students and their scores
{
Retards[i] = new RetardedStudent();
Console.Write("Input Name and score for student # {0} ", i + 1);
String StudentNameAndScore = Console.ReadLine();
int SpaceIndex = StudentNameAndScore.LastIndexOf(" ");
if (SpaceIndex != -1)
{
Retards[i].Name = StudentNameAndScore.Remove(SpaceIndex, StudentNameAndScore.Length - SpaceIndex);
Int32.TryParse(StudentNameAndScore.Remove(0, SpaceIndex + 1), out Retards[i].IQ);
}
else
{
Retards[i].Name = StudentNameAndScore;
Retards[i].IQ = 0;
}
}
if (RetardsNumber == 1)
{
Console.WriteLine("You entered 1 student " + Retards[0].Name + " with iq score test result: " + Retards[0].IQ + " Programm execution is finished because no need in sorting");
Console.ReadLine();
return;
}
RetardedStudent tempRetard = new RetardedStudent();
SortRetardedStudents(&Retards);
for (int i = 0; i < RetardsNumber; i++)
{
for (int j = 0; j < RetardsNumber - i - 1; j++)
{
if (Retards[j].IQ > Retards[j + 1].IQ || (Retards[j].IQ == Retards[j + 1].IQ) && (String.Compare(Retards[j].Name, 0, Retards[j + 1].Name, 0, Math.Max(Retards[j].Name.Length, Retards[j + 1].Name.Length)) > 0))
{
tempRetard.IQ = Retards[j].IQ;
tempRetard.Name = Retards[j].Name;
Retards[j].IQ = Retards[j + 1].IQ;
Retards[j].Name = Retards[j + 1].Name;
Retards[j + 1].IQ = tempRetard.IQ;
Retards[j + 1].Name = tempRetard.Name;
}
}
}
Console.WriteLine();
Console.WriteLine("sorted by score then by Name");
Console.WriteLine();
for (int i = 0; i < RetardsNumber; i++)
{
Console.Write("# {0} ", i + 1);
Retards[i].PrintName();
}
// Console.WriteLine("X format: {0:X}",99999);
Console.ReadLine();
}
//
}
}
}
I try to call SortRetardedStudents but whatever i do i always encounter errors. I tried to use unsafe, i added property to project whicj allows me to run unsafe code.
Right now my error is CS0208
Please help to solve the problem. I'm very bad with understanding pointers and references evem after videos.
I'm sure there is no reason to use unsafe code here.
It's looks like you miss static in your origin code.
public static void SortRetardedStudents(RetardedStudent[] Retards)

Loop wont stop, even with limit set (count++)

I just cannot seem to get this to stop looping after the count (5) is reached. IT just keeps asking away. IS there something I'm not seeing?
Any help is greatly appreciated.
Scanner keyboard = new Scanner(System.in);
int count = 0;
double answer = 0;
int randomInt1;
int randomInt2;
randomInt1 = (int)(1 + Math.random() * 10 - 1 +1);
randomInt2 = (int)(1 + Math.random() * 10 - 1 +1);
//System.out.println("Please answer the following problem: ");
//System.out.println(randomInt1 + "+" + randomInt2 + "=");
//answer = keyboard.nextDouble();
count=1;
while(count < 5)
{
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if(answer != (randomInt1 + randomInt2))
{
System.out.println("Sorry, that is not correct.");
count++;
break;
}
if(answer == (randomInt1 + randomInt2))
{
System.out.println("Nice!");
count++;
break;
}
}
return answer;
}
}
****UPDATED
count=0;
while(count < 5)
{
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if(answer != (randomInt1 + randomInt2))
{
System.out.println("Sorry, that is not correct.");
}
else if(answer == (randomInt1 + randomInt2))
{
System.out.println("Nice!");
}
count++;
break;
}
return answer;
Avoid using break on your code. Use else instead of the second if statement. Also, you should better indent your code. It helps reading.
If you want to count 5 times, you should do:
count = 0;
while(count < 5) {
...(your code here)
}
Why don't you increase count outside the if condition.
count = 0;
while(count < 5) {
if(condition1){
// ...
}
else{
// ...
}
count++;
}
Update:
Below is the complete code, which may be like what you want.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
double answer = 0;
int randomInt1;
int randomInt2;
randomInt1 = (int) (1 + Math.random() * 10 - 1 + 1);
randomInt2 = (int) (1 + Math.random() * 10 - 1 + 1);
while (count < 5) {
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if (answer != (randomInt1 + randomInt2)) {
System.out.println("Sorry, that is not correct.");
} else if (answer == (randomInt1 + randomInt2)) {
System.out.println("Nice!");
break;
}
count++;
}
}
}

Compiler error while writing to a file

I'm getting the error:-
error: cannot find symbol
tofile.println("Dancing" + " " + danceminutes + " " + bpm);
^
symbol: variable tofile
location: class CreateFile
I'm not sure why.
// writing to a file
PrintWriter toFile = new PrintWriter(new FileWriter("exLog.txt"));
Random randy = new Random();
int count = randy.nextInt(12) + 19;
for (int i = count; i > 0; i--) {
int exercise = randy.nextInt(3);
if (exercise == 0) {
int minutesOne = randy.nextInt(47) + 14;
int minutesTwo = randy.nextInt(62) + 59;
int minutesThree = randy.nextInt(122) + 119;
int roulette = randy.nextInt(100);
if (roulette <= 74) {
int runoneminutes = minutesOne;
double speed = 4.9 + (16.1 - 4.9) * randy.nextDouble();
double distance = speed * runoneminutes/60;
tofile.println("Running" + " " + runoneminutes + " " + distance);
}
else if (roulette > 74 && roulette < 96) {
int runtwominutes = minutesTwo;
double twospeed = 4.9 + (16.1 - 4.9) * randy.nextDouble();
double twodistance = twospeed * runtwominutes/60;
tofile.println("Running" + " " + runtwominutes + " " + twodistance);
}
else if (roulette >= 96) {
int runthreeminutes = minutesThree;
double threespeed = 4.9 + (16.1 - 4.9) * randy.nextDouble();
double threedistance = threespeed * runthreeminutes/60;
tofile.println("Running" + " " + runthreeminutes + " " + threedistance);
}
}
if (exercise == 1) {
int bikeminutesOne = randy.nextInt(62) + 29;
int bikeminutesTwo = randy.nextInt(212) + 89;
int bikeroulette = randy.nextInt(100);
if (bikeroulette <= 49) {
int bikeoneminutes = bikeminutesOne;
double bikeonespeed = 7.9 + (25.1 - 7.9) * randy.nextDouble();
double bikeonedistance = bikeonespeed * bikeoneminutes/60;
tofile.println("Biking" + " " + bikeoneminutes + " " + bikeonedistance);
}
else if (bikeroulette > 49) {
int biketwominutes = bikeminutesTwo;
double biketwospeed = 7.9 + (25.1 - 7.9) * randy.nextDouble();
double biketwodistance = biketwospeed * biketwominutes/60;
tofile.println("Biking" + " " + biketwominutes + " " + biketwodistance);
}
}
if (exercise == 2) {
int exercises = randy.nextInt(15) + 1;
int reps = randy.nextInt(37) + 9;
double liftminutes;
int liftminutes = 5*reps*exercises/60 + 2*(exercises-1);
tofile.println("Lifting" + " " + liftminutes + " " + reps);
}
if (exercise == 3) {
int danceminutes = randy.nextInt(90) + 29;
double bpm = 79.9 + (220 - 79.9) * randy.nextDouble();
tofile.println("Dancing" + " " + danceminutes + " " + bpm);
}
}
toFile.close(); //saving output file
} // end main
} // end CreateFile class
The variable name is toFile. The compiler is complaining about the use of 'tofile'.

SQLServerException Invalid column name

I have a problem that doesn't appear always, but it do it most of the times. In my huge java forecast class I have some ResultSets, and when I execute the routine I get:
com.microsoft.sqlserver.jdbc.SQLServerException: El nombre de columna DistanciaMision no es vßlido.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.findColumn(SQLServerResultSet.java:626)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getString(SQLServerResultSet.java:2301)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.etaMSR(Forecast.java:1109)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.phase2(Forecast.java:662)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.setData(Forecast.java:166)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.main(Forecast.java:81)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.execute(Forecast.java:71)
at org.quartz.core.JobRunShell.run(JobRunShell.java:199)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:546)
The column exists, so I don't know what is the problem...
The code line is this one:
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
The same problem appears on other columns but it usually crash here.
Thank you!
Edit: ok, this is the whole method:
private static void etaMSR() throws Exception, SQLException {
/**
*
* Calculem ETAN MSR - Mision - Seguimiento - Restricciones conductor
*
*
**/
System.out
.print("Get data from iTIM forecast&forecastAUX DDBB ....... ");
myStatement = MSSQLServerAccess.connection();
// Distancia mision, ruta, hora mision anterior, hora
rs = getTable("SELECT dbo.WebForecast.IdConductor, dbo.WebForecast.IdMision, dbo.WebForecast.IdMisionAnterior, dbo.WebForecast.DistanciaMision, "
+ " WebForecast_1.HoraIniMis AS himanterior, dbo.WebForecast.HoraFiMis AS hfmactual, WebForecast_1.Ciudad AS CiudadOrigen,"
+ " dbo.WebForecast.Ciudad AS CiudadDestino, dbo.Distancias.Ruta, dbo.WebForecast.HoraDistancia AS HoraDistancia"
+ " FROM dbo.WebForecast AS WebForecast_1 INNER JOIN"
+ " dbo.Distancias ON WebForecast_1.Ciudad = dbo.Distancias.Origen RIGHT OUTER JOIN"
+ " dbo.WebForecast ON WebForecast_1.IdMision = dbo.WebForecast.IdMisionAnterior AND dbo.Distancias.Destino = dbo.WebForecast.Ciudad"
+ " WHERE (dbo.WebForecast.IdConductor <> '') AND (CONVERT(datetime, '"
+ df.format(fechaDia)
+ "') <= dbo.WebForecast.HoraFiMis) "
+ " AND WebForecast_1.HoraIniMis <= CONVERT(datetime, '"
+ df.format(fechaDia) + "') ");
System.out.println("[ok]");
while (rs.next() && (rs.getString("IdConductor") != "") && org.apache.commons.lang.StringUtils.isNumeric(rs.getString("IdConductor"))) {
int initialodometer = 0;
String start = null;
if (rs.getString("HoraDistancia") != null) {
start = rs.getString("HoraDistancia");
}
if (rs.getString("himanterior") != null) {
start = rs.getString("himanterior");
}
if (start != null) {
ResultSet myrs = null;
Timestamp tobjetivo = rs.getTimestamp("himanterior");
long boundtime = 7200000; // 3600000 = 60m = 1h
Timestamp tini = (Timestamp) rs.getTimestamp("himanterior")
.clone();
Timestamp tfin = (Timestamp) rs.getTimestamp("himanterior")
.clone();
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
int contador = 0;
long bestdiff = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') " + "AND CONVERT(datetime, '"
+ df.format(tfin) + "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor")) + "')");
int j = 0;
while (!myrs.next() && (j < 20)) {
// En caso de no encontrar en las 2h antes y despues nada:
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
myrs.close();
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') "
+ "AND CONVERT(datetime, '" + df.format(tfin)
+ "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "')");
j++;
}
if (myrs.next()) {
initialodometer = myrs.getInt("Odometer");
bestdiff = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
contador++;
while (myrs.next()) {
long pretendiente = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
if (pretendiente <= bestdiff) {
bestdiff = pretendiente;
initialodometer = myrs.getInt("Odometer");
}
contador++;
}
}
myrs.close();
}
// Get Odometer distance at the moment
if (!rs.getString("IdConductor").isEmpty() && !rs.getString("IdConductor").equals("") ) {
ResultSet myrs = null;
int myodometer = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT MAX(DT) AS DT, MAX(Odometer) AS Odometer"
+ " FROM dbo.DriverEvents"
+ " WHERE (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "')) ");
if (myrs.next()) {
myodometer = myrs.getInt("Odometer");
if (initialodometer == 0)
initialodometer = myodometer;
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
if (distancia_restante < 0)
distancia_restante = (float) 0;
Timestamp ETAN = null;
Calendar cal = Calendar.getInstance();
if (rs.getTimestamp("himanterior") != null && rs.getTimestamp("himanterior").toString() != "") {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
if (cal.after(Calendar.getInstance())) {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
}
if (cal.before(Calendar.getInstance())) {
cal = Calendar.getInstance();
}
} else {
if (rs.getTimestamp("HoraDistancia") != null)
cal.setTimeInMillis(rs
.getTimestamp("HoraDistancia").getTime());
}
myStatement = MSSQLServerAccess.connection();
rs2 = getTable("SELECT TOP (100) PERCENT CardId, DT"
+ " FROM dbo.DriverEvents"
+ " GROUP BY CardId, DT"
+ " HAVING (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "'))");
if (rs2.next()) {
ETAN = getETAN(rs, distancia_restante, cal);
} else {
ETAN = getETA(rs, distancia_restante, cal, 1);
Statement myStatement2 = MSSQLServerAccess.connection();
myStatement2.executeUpdate("UPDATE WebForecast "
+ "SET ETAmsr = '" + df.format(ETAN)
+ "', KmsDiff = '" + distancia_restante.intValue()
+ "' " + "WHERE IdMision = '"
+ rs.getString("IdMision") + "'");
} else {
}
}
}
rs.close();
}
And the statement, maybe i'm doing something wrong?:
private static Statement conStatement(Properties properties){
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // Load the JDBC driver
String dbURL = "jdbc:sqlserver://"
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbserverIP")
+ ";DatabaseName="
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbName")
+ ";SelectMethod=Cursor;"; // Connect to a server and database
String userName = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userName");
String userPwd = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userPwd");
Connection dbConn;
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
//log.info("Connection Successful!");
Statement myst = dbConn.createStatement();
return myst;
} catch (Exception e) {
log.error(e);
System.out.println(e);
return null;
}
}
Thanks guys :) Could be something wrong with the statement?
remember that Java is case-sensitive and so can be your table on SQL depending on the way you created them, actually depending on the collation on your DB. If your database is created with a Case Sensitive collation then all object names will be Case Sensitive.
try to check the exact columns name of the column on SQL and access it using [] and the exact case

Resources