I am creating a mutliple function process and I am having a small issue with he first function. Here is the code:
import java.util.Scanner;
public class BradySkuzaLab8
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int functionchoose = 0;
int a = 0;
int b = 0;
int c = 0;
int Maxval = 0;
do
{
System.out.println( "Which function would you like to run?");
System.out.println( "1) Max int funtion." );
//System.out.println( "2) ");
//System.out.println( "3) ");
//System.out.println( "4) ");
//System.out.println( "5) ");
//System.out.println( "6) ");
//System.out.println( "7) ");
System.out.println( "8) Quit" );
functionchoose = kb.nextInt();
if(functionchoose == 1)
{
System.out.println("Please input a: ");
a = kb.nextInt();
System.out.println( "Now b: ");
b = kb.nextInt();
System.out.println( "And c: ");
c = kb.nextInt();
System.out.println(Maxval);
}
}
while(functionchoose != 8);
{
}
}
public static int Maxval(int a, int b, int c)
{
int Maxval;
Maxval = Math.max(a, Math.max( b, c));
return Maxval;
}
}
After I enter a, b, c, I set the function to choose the max value but it always prints out 0 for me. I was wondering what I was doing wrong in this instance
You have a confusing situation where you have named a variable and a method the same thing. What you need to do is change your println line to
System.out.println(Maxval(a,b,c));
But in reality, it is a bad idea to have a variable and a method with the same name. I'm not sure exactly what you're planning on doing with the variable Maxval, but for now, you don't need it and can just get rid of it by deleting the line that says
int Maxval = 0;
Related
On the snippet below, I have two functions doing exactly the same (read_array and read_array2), look up an item in an array. The only difference is the data type of the arguments (string[], string and int[] int). Creating two similar functions seems quite unelegant.
Is there a way to handle both in a generic way in one function?
void main () {
/* get index of string in array */
string[] arr = {"one", "two", "three"};
int index = read_array(arr, "two");
print(#"$index\n");
secundary ();
}
void secundary () {
/* get index of int in array */
int[] arr = {1, 2, 3};
int index = read_array2(arr, 2);
print(#"$index\n");
}
public int read_array (string[] arr, string needle) {
for (int i=0; i < arr.length; i++) {
if(needle == arr[i]) return i;
} return -1;
}
// write a separate function because other data type? ughh...
public int read_array2 (int[] arr, int needle) {
for (int i=0; i < arr.length; i++) {
if(needle == arr[i]) return i;
} return -1;
}
You can use Generics, but you have to be careful with some things.
First of all you can't pass an array of value type (i .e. int[]) to a generic function, see this question for reference:
Vala: Passing a generic array corrupts values
Second you need to pass some sort of equality test function that you have to write once for every type.
Here is a working example:
public delegate bool EqualFunc<T> (T l, T r);
bool str_equals (string l, string r) {
return l == r;
}
bool int_equals (int? l, int? r) {
return l == r;
}
public int read_array<T> (T[] arr, T needle, EqualFunc<T> equal_func) {
for (int i = 0; i < arr.length; i++) {
if (equal_func (needle, arr[i])) {
return i;
}
}
return -1;
}
void main () {
// get index of string in array
string[] arr = {"one", "two", "three"};
int index = read_array (arr, "two", str_equals);
print(#"$index\n");
secondary ();
}
void secondary () {
// get index of int in array
int?[] arr = {1, 2, 3};
int index = read_array (arr, 2, int_equals);
print(#"$index\n");
}
Boxing a value into a nullable value like this is quite ugly, but I don't know a better way to fix the mentioned compiler problem ...
If you're willing to use libgee you can use a Gee.ArrayList which will also work.
I'm trying to make this project. When i try to compile this code:
#include <mysql.h>
char *host, *user, *pass, *db;
int isconnected = 0;
void setup()
{
Serial.begin(9600);
host = "localhost";
user = "root";
pass = "";
db = "arduino";
isconnected = mysql_connect(host,user,pass,db);
if(isconnected){
Serial.print("Connected to ");
Serial.println(host);
}
else{
Serial.println("Connection failed.");
}
mysql_close();
}
void loop(){}
Maybe problem is with libraries or Arduino IDE. I get these errors and warnings:
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:
In function 'void setup()':
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:30:7:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
host = "localhost";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:31:7:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
user = "root";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:32:7:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
pass = "";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\examples\ConnectToMysql\ConnectToMysql.ino:33:5:
warning: deprecated conversion from string constant to 'char*'
[-Wwrite-strings]
db = "arduino";
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp: In
function 'String mysql_result_query(String, String)':
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp:67:10:
error: converting to 'String' from initializer list would use explicit
constructor 'String::String(int, unsigned char)'
return 0;
^
C:\Users\Mateusz\Documents\Arduino\libraries\mysql\mysql.cpp:71:10:
error: converting to 'String' from initializer list would use explicit
constructor 'String::String(int, unsigned char)'
return 0;
^
exit status 1
Edit:
There is library mysql.cpp.
#include "mysql.h"
int mysql_connect(char *host, char *user, char *pass, char *db){
Serial.print("host=");
Serial.println(host);
Serial.print("user=");
Serial.println(user);
Serial.print("pass=");
Serial.println(pass);
Serial.print("db=");
Serial.println(db);
Serial.println("mysql_connect()");
int x = Serial.read();
if(x == '-')
return 0;
while( x <= 0){
x = Serial.read();
if(x == '-')
return 0;
}
return x-48;
}
int is_mysql(){
Serial.print("is_mysql()");
int x = Serial.read();
if(x == '-')
return 0;
while( x <= 0){
x = Serial.read();
if(x == '-')
return 0;
}
return x-48;
}
void mysql_close(){
Serial.println("mysql_close()");
}
int mysql_query(char *query){
Serial.print("query=");
Serial.println(query);
int x = Serial.read();
if(x == '-' || x == '0')
return 0;
while( x <= 0){
x = Serial.read();
if(x == '-' || x == '0')
return 0;
}
return x-12;
}
String mysql_result_query(String query, String field){
String res = "";
String q = "query=" + query + "&field=" + field;
Serial.println(q);
res = Serial.readString();
if(res == "-")
return 0;
while(res.length() <= 0){
res = Serial.readString();
if(res == "-")
return 0;
}
return res;
}
And there is mysql.h:
#ifndef mysql_h
#define mysql_h
#include "Arduino.h"
int mysql_connect(char *, char *, char *, char *);
void mysql_close();
int is_mysql();
int mysql_query(char *);
String mysql_result_query(String, String);
#endif
I don't know how to solve this. I could'nt find any solutions. Sorry for my english :)
You need to initialize your variables at the beginning.
Try this:
#include <mysql.h>
char *host = "localhost", *user="root", *pass="", *db="arduino";
int isconnected = 0;
void setup()
{
Serial.begin(9600);
isconnected = mysql_connect(host,user,pass,db);
if(isconnected){
Serial.print("Connected to ");
Serial.println(host);
}
else{
Serial.println("Connection failed.");
}
mysql_close();
}
void loop(){}
The erros are comming from your mysql_result_query function. You are returning 0 for a function that returns a String.
Try this.
String mysql_result_query(String query, String field){
String res = "";
String q = "query=" + query + "&field=" + field;
Serial.println(q);
res = Serial.readString();
if(res == "-")
return "";
while(res.length() <= 0){
res = Serial.readString();
if(res == "-")
return "";
}
return res;
}
Here I'm returning an empty string. You can check it later with the length() method.
I have an exercise and I don't know how to solve it well!
I want write a C program that give from user the information of a student and then save it to file A.txt. After that reverse the first name, last name and student number and save it to file B.txt.
For example:
john
lopez
123456
It changes to:
nhoj
zepol
654321
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
struct student {
char fname[SIZE];
char lname[SIZE];
char num[SIZE];
}st;
int main()
{
FILE *in, *out;
char ch;
int tmp=0,flag=0,i;
printf("INPUT First name: ");
scanf("%s", &st.fname);
printf("INPUT Last name: ");
scanf("%s", &st.lname);
printf("INPUT personal num: ");
scanf("%s", &st.num);
in= fopen("A.txt", "w");
fputs(st.fname, in);
fputs(st.lname, in);
fputs(st.num, in);
fclose(in);
in= fopen("A.txt", "r");
out=fopen("B.txt", "w");
fgets(st.fname, strlen(st.fname)+1,in);
strrev(st.fname);
fputs(st.fname, out);
printf("\n%s", st.fname);
fgets(st.lname, strlen(st.lname)+1, in);
strrev(st.lname);
fputs(st.lname, out);
printf("\n%s", st.lname);
fgets(st.num, strlen(st.num)+1, in);
strrev(&st.num);
fputs(st.num, out);
printf("\n%d", st.num);
fclose(in);
fclose(out);
return 0;
}
If you want to copy the data to a file, then you first need to put the data in some dynamic memory allocation and then after reversing the content required in dynamic memory, you need to copy it into your file.
this is the program to reverse the each word in given string
#include
#include
void reverse_string(char*);
void reverse_words(char*);
int main() {
char a[100];
gets(a);
reverse_words(a);
printf("%s\n", a);
return 0;
}
void reverse_words(char *s) {
char b[100], *t, *z;
int c = 0;
t = s;
while(*t) { //processing complete string
while(*t != ' ' && *t != '\0') { //extracting word from string
b[c] = *t;
t++;
c++;
}
b[c] = '\0';
c = 0;
reverse_string(b); // reverse the extracted word
z = b;
while (*z) { //copying the reversed word into original string
*s = *z;
z++;
s++;
}
while (*s == ' ') { // skipping space(s)
s++;
}
/*
* You may use if statement in place of while loop if
* you are assuming only one space between words. If condition is
* used because null terminator can also occur after a word, in
* that case we don't want to increment pointer.
* if (*s == ' ') {
* s++;
* }
*/
t = s; // pointing to next word
}
}
/*
* Function to reverse a word.
*/
void reverse_string(char *t) {
int l, c;
char *e, s;
l = strlen(t);
e = t + l - 1;
for (c = 0; c < l/2; c++) {
s = *t;
*t = *e;
*e = s;
t++;
e--;
}
}
Then you can try using fputc, i.e., reading char by char along with a loop to get your data line by line as 3 lines.
char *ch;
for(i=0;st.fname[i];i++)
{
ch=getc(st.fname[i]);
fputc(ch,in);
}
repeat the same even for st.lname and st.num
Is there any efficient way to find the binary representation of binary representation of a given number n ?
Where 1 <= n <= 600000
Example : Lets take n = 2
So, binary representation of 2 is 10
Then, the answer is the binary representation of 10, i.e., 1010
This is off the top of my head, should be fast enough for most purposes. Works for values upto and including 1,048,575.
using System;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
checked
{
uint i = 0;
while (true)
{
try
{
BinaryOfDecimalRepresentation(++i);
}
catch { Console.WriteLine("Works until " + i); break; }
}
while (true)
{
uint input = 0;
try
{
input = uint.Parse(Console.ReadLine());
}
catch { }
Console.WriteLine(
BinaryOfDecimalRepresentation(input) + " : " +
UInt64ToString(BinaryOfDecimalRepresentation(input)));
}
}
}
static ulong BinaryOfDecimalRepresentation(uint input)
{
checked
{
ulong result = 0;
for (int i = 0; i < 32; i++)
if ((input & 1 << i) != 0) result += (ulong)Math.Pow(10, i);
return result;
}
}
static char[] buffer = new char[64];
static string UInt64ToString(ulong input, bool trim = true)
{
for (int i = 0; i < 64; i++)
buffer[63 - i] = ((input & (ulong)1 << i) != 0) ? '1' : '0';
int firstOne = 0;
if (trim) while (buffer[firstOne] == '0') firstOne++;
return new string(buffer, firstOne, 64 - firstOne);
}
}
}
I have the following classes in a .h:
class Register {
int content;
public:
Register ();
}reg;
class Simulator {
int op1, op2, initial_pos;
Register RA, RB, RC, RD, PC, SP, FP;
bool zero, neg;
int mem[1024];
public:
Simulator (int, int, const std::string);
void Memdump ();
void Exec_next ();
}sim;
and the definition for the simulator constructor is as follows:
Simulator::Simulator (int i, int j, int k, std::string fname) {
FILE* instructions;
valA = 0;
valB = 0;
valC = 0;
valP = 0;
valE = 0;
op1 = 0;
op2 = 0;
zero = false;
neg = false;
valid1 = false;
valid2 = false;
PC::content = 0;
FP::content = j;
SP::content = j;
initial_pos = k;
for (int i = 0; i < 1024; i++)
mem[i] = 0;
//Read input file
if (instructions = fopen (filename, 'r') == NULL) {
cout << "Error 404: file not found\n";
exit (404);
}
for (int i = 0; !feof (instructions); i++)
fscanf (instructions, "%d\n", &(mem[i + initial_pos]) );
fclose (instructions);
}
but when i try to compile this code i get the following error message:
./TP1.h:45:2: error: no matching constructor for initialization of
'class Simulator'
}sim;
^
./TP1.h:42:3: note: candidate constructor not viable: requires 3
arguments, but 0 were provided
Simulator (int, int, const std::string);
^
./TP1.h:10:7: note: candidate constructor (the implicit copy
constructor) not viable: requires 1 argument, but 0 were provided
why isn't g++ finding the constructor?
Nevermind. I'm using 1 less argument than required.