How do I convert from Integer Queue to String? - string

OK, so I have this very simple, very inefficient program, but that's alright, the only thing that I would like to know is how to print the first five numbers of the queue as zeros without changing the values of ssn1 through ssn5.
For example I would like to print 000001111, and not 111111111, but still have those values stored in the queue. Could someone help me with that? I simply would like to hide them.
I am trying to convert the integers of the queue into a string, create a substring, and then print the dummyint five time followed by the substring.
import java.util.*;
public class SSNQueue {
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
Queue<Integer> ssn = new LinkedList<Integer>();
int Dummyssn = 0;
System.out.println("Please enter each digit number of SSN");
System.out.print("Enter digit number 1: ");
int ssn1 = scan.nextInt();
System.out.print("Enter digit number 2: ");
int ssn2 = scan.nextInt();
System.out.print("Enter digit number 3: ");
int ssn3 = scan.nextInt();
System.out.print("Enter digit number 4: ");
int ssn4 = scan.nextInt();
System.out.print("Enter digit number 5: ");
int ssn5 = scan.nextInt();
System.out.print("Enter digit number 6: ");
int ssn6 = scan.nextInt();
System.out.print("Enter digit number 7: ");
int ssn7 = scan.nextInt();
System.out.print("Enter digit number 8: ");
int ssn8 = scan.nextInt();
System.out.print("Enter digit number 9: ");
int ssn9 = scan.nextInt();
ssn.add(ssn1);
ssn.add(ssn2);
ssn.add(ssn3);
ssn.add(ssn4);
ssn.add(ssn5);
ssn.add(ssn6);
ssn.add(ssn7);
ssn.add(ssn8);
ssn.add(ssn9);
Integer.toString(ssn);
String Subssn = ssn.substring(5);
System.out.println("The SSN is:" + ssn);
System.out.println("The last four digits of the SSN are:" + Dummyssn + Dummyssn + Dummyssn + Dummyssn + Dummyssn + Subssn);
}
}

There are several issues here that make it unclear exactly what you are trying to do. For one thing, you read in multiple int values (ssn1, ssn2...ssn9) then add them to a queue. You then call Integer.toString(ssn) . . . I would expect an error on that line. It seems like what you want to do there is use a loop to read the values back out of the queue, assign them to a temporary String variable each time, and then call the substring function on your temporary variable and print out the result. As it is right now, you are calling Integer.toString(ssn) which is on the entire queue and I don't think that will do what you want. The queue is still typed to Integer (Queue). Not to mention that the toString method returns a value which you are supposed to read into another variable or use at the time you call it. Calling it on its own line like that doesn't really achieve anything because even if it is returning some value, it is not being kept by your code for later use.

Related

Code for creating string in a loop to report numbers

I created a code that functions as it is supposed to. I determined the escape function to be -1 for the user to exit the program and used if/else to only add the sum of positive integers.
I know that I have to save the numbers that pass the if statement (only positive numbers) and the only way that I can think of doing this is through a String.
Unfortunately, whenever I attempt to add a string as part of the while loop, it will print the statement over and over again when I only want a single line.
I'm also struggling to set the user input to a single line. I know it has everything to do with the .nextLine() command, but if I pull it outside the brackets (which I've attempted to do) then it reads as an error.
Actually, a source about conversion of Strings to characters or inputs to Strings would be very helpful as well. It's apparent that this is where a good portion of my understanding is lacking.
public static void main(String args[])
{
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3;
System.out.print("Enter positive integers (to exit enter -1):\n ");
//Loop for adding sum with exit -1
while(userNum != -1){
//condition to only calculate positive numbers user entered
if(userNum > 0){
//calculation of all positive numbers user entered
sum += userNum;
str3 = String.valueOf(userNum);}
userNum = s.nextInt();
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);
}
}
I'm hoping for the user input to be printed,
Enter positive integers (to exit enter -1): _ _ ___//with the user
input in the same row.
And...
values from string to read out on same line, not multiple lines.
The variable str needs to be initialized as:
String str3 = "";
and in the loop, each entered number must be concatenated to str.
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3 = "";
System.out.print("Enter positive integers (to exit enter -1):\n ");
while (userNum != -1) {
userNum = s.nextInt();
if (userNum > 0) {
sum += userNum;
str3 += " " + userNum;
}
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);

Arduino does not return the desired output via serial port

I would like to send a list of elements inside a structure via serial port but the output produced by Arduino is abnormal.
A little help? What is the reason for this abnormal output?
const int menu_max_item = 20;
int menu_num_item = 0;
typedef struct item_menu{
String text;
void (*func)(void);
} t_item_menu;
t_item_menu arr_menu[menu_max_item];
void menu_add_item(String txt, void (*f)(void)){
arr_menu[menu_num_item].text = txt;
arr_menu[menu_num_item].func = f;
menu_num_item++;
}
void fn_nd_function(){
Serial.println('test');
}
void print_menu_lcd(){
for(int x = 0; x < 4 && x < menu_num_item; x++){
lcd.setCursor(0,x);
lcd.print(arr_menu[x].text);
}
}
void setup(){
Serial.begin(9600);
for(int i = 0; i < 2; i++) menu_add_item("item " + i, fn_nd_function);
}
void loop() {
print_menu_lcd();
delay(1000);
}
Real output
item
tem
em
Desired output
item 1
item 2
item 3
You have a couple of errors...
This code:
void fn_nd_function(){
Serial.println('test');
}
test is NOT a single character is it? So why do you have it in single quotes?
But more importantly this which is the cause of your bad output:
menu_add_item("item " + i, fn_nd_function);
"item" + i is NOT how you concatenate a number to the end of the character string "item". This is C++ not Java or Python. You'll have to build that string separately. Please don't be tempted to use the String class as that can cause other issues.
What is happening now is that you are passing "item" which is a pointer to the character array stored somewhere in memory holding the characters 'i', 't', 'e' and 'm'. When you add 1 to that pointer you end up with a pointer pointing to the 't' and when you add 2 you end up with a pointer pointing to the 'e'. So when you print from those pointers you only get the part after what that pointer points to.
You need to have a line ahead of that to build the string first. Something along the lines of:
char str[7] = "item "; // Note the two spaces to leave room for the digit
str[5] = i + '0'; // Add '0' to convert single digit to ascii
menu_add_item(str, fn_nd_function);

Time complexity of a string compression algorithm

I tried to do an exercice from cracking the code interview book about compressing a string :
Implement a method to perform basic string compression using the counts of
repeated characters. For example, the string aabcccccaaa would become
a2blc5a3. If the "compressed" string would not become smaller than the original
string, your method should return the original string.
The first proposition given by the author is the following :
public static String compressBad(String str) {
int size = countCompression(str);
if (size >= str.length()) {
return str;
}
String mystr = "";
char last = str.charAt(0);
int count = 1;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == last) {
count++;
} else {
mystr += last + "" + count;
last = str.charAt(i);
count = 1;
}
}
return mystr + last + count;
}
About the time complexity of thie algorithm, she said that :
The runtime is 0(p + k^2), where p is the size of the original string and k is the number of character sequences. For example, if the string is aabccdeeaa, then there are six character sequences. It's slow because string concatenation operates in 0(n^2) time
I have two main questions :
1) Why the time complexity is O(p+k^2), it should be only O(p) (where p is the size of the string) no? Because we do only p iterations not p + k^2.
2) Why the time complexity of a string concatenation is 0(n^2)???
I thought that if we have a string3 = string1 + string2 then we have a complexity of size(string1) + size(string2), because we have to create a copy of the two strings before adding them to a new string (create a string is O(1)). So, we will have an addition not a multiplication, no? It isn't the same thing for an array (if we used a char array for example) ?
Can you clarify these points please? I didn't understand how we calculate the complexity...
String concatenation is O(n) but in this case it's being concatenated K times.
Every time you find a sequence you have to copy the entire string + what you found. for example if you had four total sequences in the original string
the cost to get the final string will be:
(k-3)+ //first sequence
(k-3)+(k-2) + //copying previous string and adding new sequence
((k-3)+(+k-2)+k(-1) + //copying previous string and adding new sequence
((k-3)+(k-2)+(k-1)+k) //copying previous string and adding new sequence
Thus complexity is O(p + K^2)

Error in using indexOf not finding char in Arduino String

I have some code that I have no clue why it isn't working.
The code takes a serial input in the form of "xxx,yyy,zzz", where digits can range from 1 to 3 in each number. Because of an odd quirk in an app, it needs to be read as a char, then converted to a string to be handled. The intention is to split into 3 ints, red green and blue, from "RRR,GGG,BBB".
Now this works fine when I manually define String str (see commented code), but when I go and enter it from the serial console, it doesn't want to work. It seems to be coming from the indexOf(',') part, as while using Serial.print(c1);, I found that when I manually entered a string, it returned an index of the comma, but when I used the serial console, it returned -1 (not found).
And yes, the entered string into the console is in the correct format of "RRR,GGG,BBB", I've confirmed that by printing both phone and str independently.
while (Serial.available() > 0) {
char phone = Serial.read();
String str = String(phone);
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
Edit: With the Arduino String class, creating a string from a char is returning more than just one character, eleven in fact.
This:
char phone = Serial.read();
String str = String(phone);
will never create a string in str that has more than 1 character, since that's what you say you want.
This is the code for the Arduino's String(char) constructor:
String::String(char c)
{
init();
char buf[2];
buf[0] = c;
buf[1] = 0;
*this = buf;
}
So clearly your code will create a 1-character long string.
Also, beware of using indexes computed on the full string, on substrings later.
I'm try to guess that you are using these serial API http://playground.arduino.cc/Interfacing/CPPWindows.
while (Serial.available() > 0) {
char buf[12];
int len = Serial.ReadData(buf,11);
String str = String(buf);
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
If you are using other API like http://arduino.cc/en/Serial/Read you should follow these API where Serial is a Stream and read() return just the first available char.
Code was fixed by using a different function.
while (Serial.available() > 0) {
char phone = Serial.read();
str += phone;
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
I'm not sure why this works, and why before I was getting a string with more than one character. But it works!

Char Array Returning Integers

I've been working through this exercise, and my output is not what I expect.
(Check substrings) You can check whether a string is a substring of another string
by using the indexOf method in the String class. Write your own method for
this function. Write a program that prompts the user to enter two strings, and
checks whether the first string is a substring of the second.
** My code compromises with the problem's specifications in two ways: it can only display matching substrings to 3 letters, and it cannot work on string literals with less than 4 letters. I mistakenly began writing the program without using the suggested method, indexOf. My program's objective (although it shouldn't entirely deviate from the assignment's objective) is to design a program that determines whether two strings share at least three consecutive letters.
The program's primary error is that it generates numbers instead of char characters. I've run through several, unsuccessful ideas to discover what the logical error is. I first tried to idenfity whether the char characters (which, from my understanding, are underwritten in unicode) were converted to integers, considering that the outputted numbers are also three letters long. Without consulting a reference, I know this isn't true. A comparison between java and javac outputted permutation of 312, and a comparison between abab and ababbab ouputted combinations of 219. j should be > b. My next thought was that the ouputs were indexes of the arrays I used. Once again, this isn't true. A comparison between java and javac would ouput 0, if my reasoning were true.
public class Substring {
public static char [] array;
public static char [] array2;
public static void main (String[]args){
java.util.Scanner input = new java.util.Scanner (System.in);
System.out.println("Enter your two strings here, the longer one preceding the shorter one");
String container1 = input.next();
String container2 = input.next();
char [] placeholder = container1.toCharArray();
char [] placeholder2 = container2.toCharArray();
array = placeholder;
array2 = placeholder2;
for (int i = 0; i < placeholder2.length; i++){
for (int j = 0; j < placeholder.length; j ++){
if (array[j] == array2[i]) matcher(j,i);
}
}
}
public static void matcher(int higher, int lower){
if ((higher < array.length - 2) && (lower < array2.length - 2))
if (( array[higher+1] == array2[lower+1]) && (array[higher+2] == array2[lower+2]))
System.out.println(array[higher] + array[higher+1] + array[higher+2] );
}
}
The + operator promotes shorts, chars, and bytes operands to ints, so
array[higher] + array[higher+1] + array[higher+2]
has type int, not type char which means that
System.out.println(...)
binds to
System.out.println(int)
which displays its argument as a decimal number, instead of binding to
System.out.println(char)
which outputs the given character using the PrintStream's encoding.

Resources