Apologies for the basic question, I'm new to java and have been stuck on this for days.
I need firstly to convert letters to numbers and then using recursion to get the sum of those numbers. I think I am close but I'm also aware it very messy
public static void main(String[] arg) {
String str= "11";
//////////////////////////
String s = "helloworld";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (!t.isEmpty()) {
t += " ";
}
int n = (int)ch - (int)'a' + 1;
t += String.valueOf(n);
}
System.out.println(t);
//////////////////////////////
int sum=0;
int x=Integer.parseInt(t);
int y=recursion(x);
System.out.println("The Sum of the digits is: "+ y);
}
public static int recursion(int y) {
if(y/10>=1) {
int tempvar =y%10;
int remain=y/10;
return tempvar + recursion(remain);
}
else {
return y;
}
}}
Ok so first of all, this line: int x=Integer.parseInt(t); will crash the program in runtime because the string t has spaces in it. So you need to remove this:
if (!t.isEmpty()) {
t += " ";
}
Second, parsing the string t to int is a problem, because the number in string t can get like very, very large. Parsing this very..very large number to an int will also produce an exception during runtime. So a better way to do this is leaving it as a string, loop over it and just add the digits in it.
I have two solutions here:
I loop on t and add the digits.
I assume you have some constraint on the size of t so as it can be parsed to int (or long), and then use recursion as you want.
public class Main {
public static void main(String[] args) {
String s = "hew";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
int n = (int)ch - (int)'a' + 1;
t += String.valueOf(n);
}
System.out.println("t: "+t);
System.out.println("sum using string: " + getSumUsingString(t));
System.out.println("sum using int: " + getSumUsingLong(Long.parseLong(t), 0));
}
// the string function
private static long getSumUsingString(String t) {
long sum = 0;
for (int i = 0; i < t.length(); i++) {
sum += t.charAt(i)-48;
}
return sum;
}
// recursive function
private static long getSumUsingLong(long num, long sum) {
if (num==0) return sum;
sum += num % 10;
return getSumUsingLong(num / 10, sum);
}
}
Note:
You can use for example, BigInteger class in Java to deal with very large numbers if you really need to parse this string t to a number.
Related
Hi I tried to write my own version of memmove and I find the following code resulting in a segmentation fault. It would be great if someone could help me figure out why this behavior would occur!
However, when I use something like:
char source[20] = "Hello, this is Piranava", the code works fine!
void *memmoveLocal(void *dest, const void *src, unsigned int n)
{
char *destL = dest;
const char *srcL = src;
int i = 0;
if(dest == NULL || src == NULL)
{
return NULL;
}
else
{
// if dest comes before source, even if there's an overlap, we should move forward
// because if there's an overlap (when dest < src) and we move backward, we'd overwrite the overlapping bytes in src
if(destL < srcL)
{
printf("Forward\n");
while(i < n)
{
destL[i] = srcL[i];
i++;
}
}
else // in all other cases (even if there's overlap or no overlap, we can move backward)
{
printf("Backward\n");
i = n - 1;
while(i >= 0)
{
destL[i] = srcL[i];
i--;
}
}
}
return dest;
}
void main()
{
char *source = "Hello, this is ABC";
char *destination = malloc(strlen(source)+1);
memmoveLocal(source+5, source, 5);
printf("Source: %s \nDestination: %s, size: %d\n", source, destination, strlen(destination));
}
However, if I replace
char *source = "Hello, this is ABC";
with
char source[20] = "Hello, this is ABC";
, it works fine!
memmoveLocal(source+5, source, 5);
You are trying to overwrite a string literal, which is not writable.
Did you intend to memmoveLocal(destination, source+5, 5) instead?
char source[20] = "Hello, this is ABC";
That turns source from a string literal into a char[] array initialized with a string literal. The array is writable, so your program no longer crashes.
In Arduino i need a simple array. The keys have to be a string and the values an integer. In PHP it would look like this:
$array["name"] = array(8,4);
$array["second"] = array(1,6);
Is there any way to solve this with Arduino?
Array of struct would be better:
typedef struct keyAndValue_ {
int key;
char value[NAMELENMAX+1];
} keyAndValue_t;
keyAndValue_t myArray[] = {
{123, "Bob"},
{345, "Harry"}
};
for (int x = 0; x <= sizeof(myArray)/sizeof(myArray[0]); x++) {
if (myID == myArray[x].key) {
Serial.println(myArray[x].value);
}
}
In the function xyz(), I am calculating the string value and number of image and I need to return all the value like string and image. So, What I need to take the return type so they will take all value?
<Return-Type> MainWindow::xyz(QString m_ImgPath, int i)
{
try
{
m_ImgPath = Array[i];
QByteArray m_path = m_ImgPath.toLocal8Bit();
char* ImagePath = m_path.data();
obj *m_ThumpDCMReader = obj::New();
TReader->SetFileName(ImagePath);
TReader->Update();
//const QString string = NULL;
const char *str_uchar = TReader->GetMetaData()->GetAttributeValue(DC::string).GetCharData();
string = QString::fromUtf8((char *)str_uchar);
SPointer<ImageData> imageData = TReader->GetOutput();
if (!imageData) { return QImage(); }
/// \todo retrieve just the UpdateExtent
int width = imageData->GetDimensions()[0];
int height = imageData->GetDimensions()[1];
QImage image(width, height, QImage::Format_RGB32);
QRgb *rgbPtr = reinterpret_cast<QRgb *>(image.bits()) + width * (height - 1);
unsigned char *colorsPtr = reinterpret_cast<unsigned char *>(imageData->GetScalarPointer());
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
*(rgbPtr++) = QColor(colorsPtr[0], colorsPtr[1], colorsPtr[2]).rgb();
colorsPtr += imageData->GetNumberOfScalarComponents();
}
rgbPtr -= width * 2;
}
return (Image,string)
}
catch (...) { return QImage(); }
}
SO what i need to add the the return type.So, they will return multiple data.
You can use a QPair<QString, QImage> for that, and use qMakePair to build the values:
QPair<QString, QImage> MainWindow::xyz(QString m_ImgPath, int i) {
try {
// ...
return qMakePair(string, Image);
} catch (...) {
return qMakePair(QString(), QImage());
}
}
The caller can then use .first and .second to access the string and image, resp:
auto values = xyz("",0); // or QPair<QString, QImage> values = xyz("",0);
auto str = values.first;
auto img = values.second;
If you need to extend to more then 2 items, I suggest to use a custom struct, e.g.:
struct StringWithImage {
QString string;
QImage image;
};
// In your return:
return StringWithImage{ string, Image };
// Usage:
auto values = xyz("", 0);
auto str = values.string;
auto img = values.image;
I have a String variable and I want to extract the three substrings separeted by ; to three string variables.
String application_command = "{10,12; 4,5; 2}";
I cannot use substring method because this string can be like any of the following or similar patterns also.
String application_command = "{10,12,13,9,1; 4,5; 2}"
String application_command = "{7; 1,2,14; 1}"
The only thing that is common in these patterns is there are three sections separated by ;.
Any insight is much appreciated.
Thank you
I think you need a split-string-into-string-array function with a custom separator character.
There are already several sources on the web and at stackoverflow (e.g. Split String into String array).
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
You can use this function as follows (with ";" as separator):
String part01 = getValue(application_command,';',0);
String part02 = getValue(application_command,';',1);
String part03 = getValue(application_command,';',2);
EDIT: correct single quotes and add semicolons in the example.
The new SafeString Arduino library (available from the library manager) provides a number of tokenizing/substring methods without the heap fragmentation of the String class
See https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
for a detailed tutorial
In this case your can use
#include "SafeString.h"
void setup() {
Serial.begin(9600);
createSafeString(appCmd, 50); // large enought for the largest cmd
createSafeString(token1, 20);
createSafeString(token2, 20);
createSafeString(token3, 20);
appCmd = "{10,12,13,9,1; 4,5; 2}";
size_t nextIdx = 1; //step over leading {
nextIdx = appCmd.stoken(token1, nextIdx, ";}");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token2, nextIdx, ";}");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token3, nextIdx, ";}");
nextIdx++; //step over delimiter
// can trim tokens if needed e.g. token1.trim()
Serial.println(token1);
Serial.println(token2);
Serial.println(token3);
}
void loop() {
}
Also look at pfodParser which parses these types of messages { } for use by pfodApp.
Do not forget to call delete[] to free the memory after the use of the array, that said here is my solution:
String* split(String& v, char delimiter, int& length) {
length = 1;
bool found = false;
// Figure out how many itens the array should have
for (int i = 0; i < v.length(); i++) {
if (v[i] == delimiter) {
length++;
found = true;
}
}
// If the delimiter is found than create the array
// and split the String
if (found) {
// Create array
String* valores = new String[length];
// Split the string into array
int i = 0;
for (int itemIndex = 0; itemIndex < length; itemIndex++) {
for (; i < v.length(); i++) {
if (v[i] == delimiter) {
i++;
break;
}
valores[itemIndex] += v[i];
}
}
// Done, return the values
return valores;
}
// No delimiter found
return nullptr;
}
Here is an example of how to use:
void loop() {
String test = "1,2,3,4,5";
int qtde;
String* t = split(test, ',', qtde);
for (int i = 0; i < qtde; i++) {
Serial.println(t[i]);
delay(1000);
}
delete[] t;
}
hello everyone i am new to java and i need help on this assignment that our teacher gave us... here is my programm... the objective is everytime i choose a course and time the output will display 1 and everytime the user choose a course or a schedule the output fills up.... sorry if i cant explain it clearly my english is bad.....
import java.io.*;
public class Array2D_input {
public static void main(String[] args)throws IOException {
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
int X=0;
int num=0;
String [] subject={" ","C#Programming","Autocad","Robotics","JavaProgramming"};
String [] time={" ","8:00 - 12:00","12:00 - 4:00","4:00 - 8:00"};
int [][] N=new int[5][4];
do{
System.out.println("SUBJECT ENROLLMENT\n");
System.out.println("Subjects Offered");
for(int s=1;s<=4;s++)
{
System.out.print(" "+s+" - "+subject[s]);
System.out.println();
}
System.out.println();
System.out.print("YOUR CHOICE : ");
int a=Integer.parseInt(in.readLine());
N[4][a]++;
for(int t=1;t<=3;t++)
{
System.out.print(" "+t+" - "+time[t]);
System.out.println();
}
System.out.print("TIME SCHEDULE : ");
int tm=Integer.parseInt(in.readLine());
num=num+1;
System.out.print("More Entries <Y/N> : ");
X=in.readLine().charAt(0);
}
while(X=='Y');
//System.out.print("\n\tENROLLMENT SUMMARY\n");
System.out.print("\t\t TIME SCHEDULE\n");
System.out.print("SUBJECTS\t 8:00-12:00\t 12:00-4:00\t 4:00-8:00\t total" );
for(int s=0; s<5; s++)
{
System.out.print(""+subject[s]);
System.out.println();
for(int t=0; t<4; t++)
System.out.print("\t\t\t "+N[s][t]);
System.out.println();
}
}
}
Here is the revised code for your task, Hope it will help you.
import java.io.*;
public class Array2D_input {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String x = "";
String[] subject = { "C#Programming", "Autocad", "Robotics", "JavaProgramming" };
String[] time = { "8:00 - 12:00", "12:00 - 4:00", "4:00 - 8:00" };
int[][] N = new int[subject.length][time.length];
// Initializing array with default values
for (int i = 0; i < subject.length; i++) {
for (int j = 0; j < time.length; j++) {
N[i][j] = 0;
}
}
do {
System.out.println("SUBJECT ENROLLMENT\n");
System.out.println("Subjects Offered");
for (int s = 0; s < subject.length; s++) {
System.out.print(" " + (s + 1) + " - " + subject[s]);
System.out.println();
}
System.out.println();
System.out.print("YOUR CHOICE : ");
int a = readNumber(in, subject.length);
for (int t = 0; t < time.length; t++) {
System.out.print(" " + (t + 1) + " - " + time[t]);
System.out.println();
}
System.out.print("TIME SCHEDULE : ");
int tm = readNumber(in, time.length);
N[a - 1][tm - 1]++;
System.out.print("More Entries <Y/N> : ");
x = in.readLine();
} while (x.equalsIgnoreCase("Y"));
// System.out.print("\n\tENROLLMENT SUMMARY\n");
System.out.print("\t\t TIME SCHEDULE\n");
System.out.print("SUBJECTS\t 8:00-12:00\t 12:00-4:00\t 4:00-8:00\t Total");
for (int s = 0; s < subject.length; s++) {
int count = 0;
System.out.println();
System.out.println(subject[s]);
for (int t = 0; t < time.length; t++) {
System.out.print("\t\t " + N[s][t]);
count += N[s][t];
}
System.out.print("\t\t " + count);
}
}
/**
* Function to read input from the console and also check for max value
*
* #param in
* #param maxLimit
* #return
* #throws IOException
*/
public static int readNumber(BufferedReader in, int maxLimit) throws IOException {
int choice = 0;
try {
choice = Integer.parseInt(in.readLine());
} catch (NumberFormatException nf) {
System.out.println("Enter integer only:");
choice = readNumber(in, maxLimit);
}
if (choice > maxLimit) {
System.out.println("Enter only given options");
choice = readNumber(in, maxLimit);
}
return choice;
}
}
java 2d array input example:
//Coded BY Anurag Goel
//Basic 2DArray Program
import java.util.Scanner;
public class array2d {
public static void main(String args [])
{
int [][] arr =new int[5][5];
System.out.println("Enter student roll no and their subject codes");
Scanner o = new Scanner(System.in);
for(int i=0;i<5;i++)
{
System.out.println("Enter "+(i+1)+"th student subject codes ");
for(int k=0;k<5;k++)
{
System.out.println("Enter "+(k+1)+"th subject code : ");
arr[i][k]=o.nextInt();
}
}
for(int j=0;j<5;j++)
{
System.out.print(""+(j+1)+"th student subject codes ");
for(int l=0;l<5;l++)
{
System.out.print(" "+arr[j][l]+" ");
}
System.out.println("");
}
}
}