This has been bugging me for three days. I'm attempting to read text from a text field, check the length of the value is greater than zero (using the String method length), then create a loop. If the length is not greater than zero, I have to set an error message and an error flag (boolean variable to true). I've dug into the documentation for the String method but I can't seem to get length() to work for me. You can see my experimenting with the code. First time posting, sorry if I'm getting this wrong.
private void setShipmentProperties() {
ship.setEmployeeNum(empNumTF.getText());
if(ship.setEmployeeNum(String(length()) < 0)) {
isDataEntryError = true;
msgLbl.setText("Pay rate must be a numeric " + "value: 1, 2, 3...");
}
ship.setShipmentNum(shipNumTF.getText(this.length()));
if(this.length() < 0) {
isDataEntryError = true;
msgLbl.setText("Pay rate must be a numeric " + "value: 1, 2, 3...");
}
ship.setSupplierName(supplTF.getText());
if(ship.length() < 0) {
isDataEntryError = true;
msgLbl.setText("Pay rate must be a numeric " + "value: 1, 2, 3...");
}
}
A length can't be < 0. The length of a string can't be less than zero.
Related
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);
my code snippet is:
int bs_greaterthan_or_equal(int *a, int key, int low, int high) {
while(low<high) {
int mid = low +(high-low)/2.0;
if(a[mid]<key) {
low = mid + 1;
}
else high = mid;
}
return high;
}
But even when i search a number greater than last element in the array it returns the last index
e.g a[] = {1,3,10,15,20,25,27}
key = 28
It returns 7
But even when i search a number greater than last element in the array it returns the last index
Because that is what it has been designed to do. Technically speaking, it returns the last index + 1.
Notice the condition:
if(a[mid]<key) {
low = mid + 1;
}
When looking for an element that's larger than (or equal to) the last element of the array, the above condition will always evaluate to true. The loop terminates when you reach the last element itself, where low is set to one more than the last index.
When you search for the key 28 in your example, low is repeatedly updated because the above condition always evaluates to true. When mid equals 6, then a[mid] is still lesser than 28, so low is set to mid + 1, i.e 7. At this point, low and high become equal (notice that high was never modified) and the loop terminates. The function returns 7.
If there's something specific that you wish to return (say, -1) upon searching for a number that's greater than or equal to the last element in the array, you can modify your code as follows.
int bs_greaterthan_or_equal(int *a, int key, int low, int high) {
int max_limit = high;
while(low<high) {
int mid = low +(high-low)/2.0;
if(a[mid]<key) {
low = mid + 1;
}
else high = mid;
}
return high == max_limit ? -1 : high;
}
If the array contains a larger or equal element for the given key, high will store its index. Otherwise, at the end, high will remain equal to max_limit, meaning that the search procedure couldn't find such an element, and hence, will return -1.
so I've been struggling with this for a fare old while now and need some help with bool functions. I'm stuck on the search part of helpers in pset3.
I know my selection sort function works, as I used printf to check the numbers are being sorted, and I tested find with a simple linear search to confirm it was working properly.
My code for the search function is as follows:
bool search(int value, int values[], int n)
{
// Set upper and lower limits for mid point calculation
int max = n - 1;
int min = 0;
while (min <= max)
{
// Set the mid point of values as half the difference of the upper and lower limit.
int mid = (max - min)/ 2;
// If the array position we look at for this itteration of mid is equal to the value, return true
if (value == values[mid])
return true;
// If the mid value is less than our value, look at the right half (+1 as we dont need to look at the mid point again)
else if (value > values[mid])
return min = mid + 1;
// Same principle but for the left half of the array
else if (value < values [mid])
return max = mid - 1;
}
return false;
}
As far as I can tell my logic is sound for the actual calculations. I've tried any number of different ways of returning false, such as "if (value < values[mid + 1] && value > values[mid -1]" to return false but to no avail so I've omitted them from the code here. Any help would be greatly appreciated.
Cheers
Tom
I haven't checked the logics of your code, but you can't set a function to return a bool but also use it to return numbers as in
return min = mid + 1;
Or in
return max = mid - 1;
Just set the function to return int instead and use 1 and 0 as true and false.
Also, C doesn't have boolean types unless you are defining them in your code or importing stdbool.h
Edit: just remembered that you can't change the signature of the function, so try creating a function of your own and then calling it inside the already defined search function.
given a string that includes unbalanced brackets of some order, how can I find the first index that is the unbalancing factor of my string and return it?
for example: if the string is: ")" the return value will be 0 ,
if the string is: "(((jjkk))))" the return value will be 10 ,
if the string is: "((" the return value will be 2 ,
I have implemented a function that returns boolean regarding if my string is balanced or not. (T - balanced)
I know it should be some recursive function but just can't figure it out...
Thanks!
A nonrecursive solution (written in pseudosomething loosely resembling C#) ...
string input_str = "this(is(for)(testing))(the)correctness)(of(brackets))";
int left_brackets_cnt = 0;
for (int i=1; i<=input_str.length; i++)
{
switch (input_str.char_at_position(i))
{
case "(": left_brackets_cnt++;
case ")": left_brackets_cnt--;
}
if (left_brackets_cnt < 0)
throw exception("Unmatched right bracket at position "+i);
}
if (left_brackets_cnt > 0)
throw exception("Too many left brackets");
Footnote: Please show appreciation - I typed this on a 3" smartphone! :-)
I found this interview question floating around, and after having given much thought to it, I couldn't really develop a sound algorithm for it.
Given a string of numbers in sequential order, find the missing number.The range of numbers is not given.
Sample Input:"9899100101103104105"
Answer:102
This is a simple problem.
Guess the number of digits for the first number
Read numbers from the string one by one. If the previous number you have read is x, the next number must be either x + 1 or x + 2. If it is x + 2, remember x + 1 as the missed number, continue until the end of the string anyway to verify that the initial guess was correct. If you read something else than x + 1 or x + 2, the initial guess was wrong and you need to restart with (next) guess.
With your example:
9899100101103104105
First guess length 1
read 9
the next number should be either 10 or 11. Read the next two digits, you get 89.
That is incorrect, so the initial guess was wrong.
Second guess length 2
read 98
the next number should be either 99 or 100. Read the next two digits for 99
the next number should be either 100 or 101. Read the next three digits for 100
... 101
... 103 (remember 102 as the missed number)
... 104
... 105
end of input
Guess of length 2 was verified as correct guess and 102 reported as missing number.
The only dififcult part, of course, is figuring out how many digits the numbers have. I see two approaches.
Try a certain number of digits for the first number, decide what the following number should therefore be (there'll be two options, depending on whether the missing number is the second one), and see if that matches the following string of digits. If so, continue on. If the string doesn't fit the pattern, try again with a different number of digits.
Look at the starting and ending portions of the string, and reason the number of digits based on that and the length of the string. This one's a little more handwavey.
digits=1
parse the string like the first number conatins digits digits only.
parse the next number and check if it is sequential correct related to the last parsed one
if it decreases, digit+=1, goto 1.
if it is 2 higher than the last parsed, you might found the gap, parse the rest, if parsing the restis not an increasing sequence, digit+=1, goto 2, otherwise you have found the gap.
if it is 1 higher than the last parsed number, goto 3.
digit+=1, goto 2. (I am not sure if this case can ever happen)
Example:
given: "131416".
1. digits=1
2. parse '1'
3. parse '3'
4. it does not decrease
5. possibly found the gap: parse the rest '1416' fails, because '1' != '4'
=> digit+=1 (digit=2) goto 2
2. parse '13'
3. parse '14'
4. it does not decrease
5. it is no 2 higher than the last parsed one (13)
6. it is 1 higher (14 = 13+1) => goto 3
3. parse '16'
4. it does not decrease
5. possibly found the gap: parse the rest '' passed because nothing more to parse,
=> found the gab: '15' is the missing number
Here is a working C# solution you can check in LINQPad:
void Main()
{
FindMissingNumberInString("9899100101103104105").Dump("Should be 102");
FindMissingNumberInString("78910121314").Dump("Should be 11");
FindMissingNumberInString("99899910011002").Dump("Should be 1000");
// will throw InvalidOperationException, we're missing both 1000 and 1002
FindMissingNumberInString("99899910011003");
}
public static int FindMissingNumberInString(string s)
{
for (int digits = 1; digits < 4; digits++)
{
int[] numbers = GetNumbersFromString(s, digits);
int result;
if (FindMissingNumber(numbers, out result))
return result;
}
throw new InvalidOperationException("Unable to determine the missing number fro '" + s + "'");
}
public static int[] GetNumbersFromString(string s, int digits)
{
var result = new List<int>();
int index = digits;
int number = int.Parse(s.Substring(0, digits));
result.Add(number);
while (index < s.Length)
{
string part;
number++;
digits = number.ToString().Length;
if (s.Length - index < digits)
part = s.Substring(index);
else
part = s.Substring(index, digits);
result.Add(int.Parse(part));
index += digits;
}
return result.ToArray();
}
public static bool FindMissingNumber(int[] numbers, out int missingNumber)
{
missingNumber = 0;
int? found = null;
for (int index = 1; index < numbers.Length; index++)
{
switch (numbers[index] - numbers[index - 1])
{
case 1:
// sequence continuing OK
break;
case 2:
// gap we expect to occur once
if (found == null)
found = numbers[index] - 1;
else
{
// occured twice
return false;
}
break;
default:
// not the right sequence
return false;
}
}
if (found.HasValue)
{
missingNumber = found.Value;
return true;
}
return false;
}
This can likely be vastly simplified but during exploratory coding I like to write out clear and easy to understand code rather than trying to write it in as few lines of code or as fast as possible.