Now it's saying incompatible types: boolean cannot be converted to java.lang.String
What data type is "zipC"?
Code:
public static boolean zipcode(String zip){
if(str.startsWith(112)){
And where else are you using "str" in your program?
Now it's saying incompatible types: boolean cannot be converted to java.lang.String
public static boolean zipcode(String zip){
if(str.startsWith(112)){
If you want to check for range, just use range checks :) lower < x && x < upper
Numbers have a value (x == 12) and an ordering (x < 13). Strings have a value (x == "12"), an ordering (x < "13") and a pattern (x.startsWith("1"), a visual representation).
I value good and pragmatic coding style over program efficiency (but I don't come from a C++ background). The first priority of a programmer should be to have a readable, working and extensible solution. If performance is a concern in the end, start optimizing then
If you have an integer number 12345678 and you divide it by 10, you get 1234567. If you divide it by 100, you get 123456, and you get 123 when you divide by 100000. Therefore, if you know the length of your zipcode, obtaining the first 3 digits is pretty easy. If the length is variable, you can either first determine the length, or use a loop to repeatedly divide by 10 until your result is small enough.I'm assuming something like %112==0 would do the trick right? But if not I'm unsure how to grab those first 3 digits. Math has never been my strong suit:/
zipC was a string. I didn't use str anywhere else I thought it was a part of the method "startsWith".What data type is "zipC"?
And where else are you using "str" in your program?Code:public static boolean zipcode(String zip){ if(str.startsWith(112)){
Gotcha.If you have an integer number 12345678 and you divide it by 10, you get 1234567. If you divide it by 100, you get 123456, and you get 123 when you divide by 100000. Therefore, if you know the length of your zipcode, obtaining the first 3 digits is pretty easy. If the length is variable, you can either first determine the length, or use a loop to repeatedly divide by 10 until your result is small enough.
You can also use the modulo (remainder) operation to extract the last few digits. 12345678 % 10 is 8, for example. If you combine division and modulo you can extract things in the middle (although since I can't think of a single case where this would be useful with integers, you would very likely want to be using strings in those cases anyway).
That was supposed to be used a way to compare with zip. I've removed the str since then.Step through your code and see what is going on.
The first immediate thing I see is you are doing if(str.startsWith(112)){
I am fairly certain you are intending that to be zip. The fact that 'str' hasn't being initialized (or defined) might be causing a misleading error
There you go. Guess you already caught the error then.
In what editor are you working? I'd advise at least an editor with syntax highlighting (be it Notepad++, Vim, Ecplise, ..).Now it's saying incompatible types: boolean cannot be converted to java.lang.String
I had scrapped that a while ago after some testing.Ohhh there is your problem.
zipC (this is a string) = zipcode (zip) (this returns a boolean)
The zipcode function is returning a boolean, but you are trying to assign it to a string. That is where your type mismatch is coming from.
I think I'm confusing myself now as I've got a few different versions of this part opened up. one similar to what you've just typed. But there's always some roadblock.There you go. Guess you already caught the error then.
Since the Boolean is deciding true or false, you need to ensure that the returned value from the function is being used to dictate some decision in the main program.
Instead of assigning to a string, it's pretty easy to say
If true, zipC = "true"
Else, zipC = "false"
Or something to that effect
I'm using Dr.Java.In what editor are you working? I'd advise at least an editor with syntax highlighting (be it Notepad++, Vim, Ecplise, ..).
A few tips:
- Don't be afraid to be verbose. It's okay to have a variable named "zipCodeAsAString" and "zipCodeAsANumber".
- Similarly, functions do things. They have a name and don't be afraid to call them after what they do. "zipcode" would become something like "writeZipCodeToFileAndReturnWhetherItStartsWith112" (and yes, that should be a red flag :P but you'll grow in that when you get the hang of it).
- Try to keep your declarations (the first time you name a variable) as close as possible to its usage. This way it will be clearer what the type is.
This should hopefully help you in more easily tracking the errors. Error tracking is also a skill that you develop with practice.
Don't worry about it. Nothing wrong with that at all and when you debug programs it isn't really that odd to run into some other issue that you have to solved.I think I'm confusing myself now as I've got a few different versions of this part opened up. one similar to what you've just typed. But there's always some roadblock.
Not sure if the code you posted before is your full code but I imagine you have a number of options here. You can literally "break" out of a loop if necessary. Its a keyword that breaks out of a loop and goes to the next statement. Under the right conditions you might also want to "return" from the loop using that keyword.I've seemed to figure out most problems in one version of the code, now I just need to return the zip code from the while loop so that it can pass to the boolean method now. I've returned from a loop before but can't figure it out now.
I've used pseudocode, it just this assignment has really gotten the better of me because of the detail of having to grab digits and a boolean method. I've solved most of my problems, I just need to 1) solve why I'm getting an error about not having initialized "zipcode" within my boolean method 2) solve how to get the method to pull more than one zip code while its in the loop. This is my code now:Don't worry about it. Nothing wrong with that at all and when you debug programs it isn't really that odd to run into some other issue that you have to solved.
Not sure if the code you posted before is your full code but I imagine you have a number of options here. You can literally "break" out of a loop if necessary. Its a keyword that breaks out of a loop and goes to the next statement. Under the right conditions you might also want to "return" from the loop using that keyword.
Also, have you been using pseudo code at all? It could really be beneficial.
public static void main(String[] args) throws IOException{
File myfile = new File("addresses.txt");
Scanner infile = new Scanner(myfile);
int counter = 0,houseNum,zipC;
String street, zip;
while (infile.hasNext()) {
//counts amount of times ran
counter++;
//reads data
houseNum = infile.nextInt();
street = infile.nextLine();
zip = infile.nextLine();
isZip(zip);
//prints read data and counter
//System.out.println(houseNum + street);
//System.out.println(zip);
//System.out.println("Ran " + counter + " times.");
}
}
public static boolean isZip(String zip)throws IOException{
String zipcode;
if(zipcode.startsWith("112")){
PrintWriter ofile = new PrintWriter("All112.txt");
ofile.println(zipcode);
return true;
}
else{
PrintWriter ofile2 = new PrintWriter("allElse.txt");
ofile2.println(zipcode);
ofile2.close();
return false;
}
}
}
1) solve why I'm getting an error about not having initialized "zipcode" within my boolean method
2) solve how to get the method to pull more than one zip code while its in the loop
public static boolean isZip(String zip)throws IOException{
if(zip.startsWith("112")){
PrintWriter ofile = new PrintWriter("All112.txt");
ofile.println(zip);
return true;
}
else {
//stuff
}
}
1)Zip is initialized. Wow, now I see zipcode was an error. Same problem I had earlier this semester with methods and passing arguments. I was thinking that it took string zip from parameters and passed it to a new variable.Question #1: You have both zip and zipcode. Two separate variables. One is initialized and one isn't. Can you tell which? Do you need both?
Question #2: I'm not familiar with the Java Scanner class, but this looks fine to me on the surface. Why do you say it's not pulling more than one zip code? What is it doing instead?
Its set up like:1) -REMOVED- Metaprogram's response is a better response since it has less direct response and is leading you to solve
2) How is the file set up? If you have it so that the zip codes are each on a new line you are already pretty close. If they are separated by commas you have to do something else.
EDIT: The way your program is now I'd assume your file has something like:
123
Main St
10020
789
Side St
10020
And you are looping over this, right? I think your loop would be fine for that kind of setup
Yea, this seems toIt's pointless to check a variable if it's never assigned. You check if zipcode starts with "112" when you create zipcode (but not initialize it) literally the line above it.
(In case you don't know, initializing means assigning a value to the variable, like zipcode = "1234".)
However, there's another loose end in your code: You never use the string zip, which is the local variable you create as a parameter for isZip. ;)
Code:public static boolean isZip(String zip)throws IOException{ if(zip.startsWith("112")){ PrintWriter ofile = new PrintWriter("All112.txt"); ofile.println(zip); return true; } else { //stuff } }
Wouldn't this be a much better solution?
edit: lol beaten twice
public static boolean IsZip112(String zip)throws IOException{
if(zip.startsWith("112")){
return true;
}
else {
return false
}
}
Its set up like:
123 Main St
10020
789 Side St
10020
It's looping but only taking the last zip code, I know it's looping properly as when I read it I included printlns to see if it read all lines in the address file.
houseNum = infile.nextInt();
street = infile.nextLine();
zip = infile.nextLine();
Makes sense, I'll keep this mind going forward thanks.When you start hitting up some design methodology courses, the thing they will harp on will be creating code that does one thing very well, rather doing an amalgamation of things. It might make sense conceptually to separate out the check for your zip, and doing the printing.
Pseudocode would end up something like
1. Read in Zip Code
2. check for zip starting with 112
3. do something with that information
Your function would be reduced to
Code:public static boolean IsZip112(String zip)throws IOException{ if(zip.startsWith("112")){ return true; } else { return false } }
which is much more manageable, and only does one thing.
I've pulled the booean method out and put it after the while loop. I'm not sure how I'd go about the bolded as I was under the assumption the while loop was the way to pull the writing from the file. Also, with the method out wouldn't that mean I'd be testing each zip code in the method manually?I think problem #2 is because you're recreating the file each time through the loop, causing it to overwrite whatever you put there the previosu time. Since that function is supposed to only *check* whether it starts with the prefix, you should pull the writing up outside of that function. Open each file once, OUTSIDE the loop, and then INSIDE the loop only write to it, depending on what isZip returns.
Not using break, I figured it wouldn't be a problem as I was grabbing the data from the zip each loop.My first thought is that
Code:houseNum = infile.nextInt(); street = infile.nextLine(); zip = infile.nextLine();
might have some issues if an address is presented on just two lines. Are you using breakpoints? Are you certain that during the loop that 123 is set as houseNum and Main St becomes street?
I haven't tested something like this before but nextInt() would grab that first 10020 zip code because "123 Main St" is not an int and the scanner would skip it, and then the next line that would be street would get assigned 789 Side st and then zip code would be forced to take the following line which is the last zip code.
I might be mistaken but that is my hunch.
EDIT: Or just listen to metaprogram instead. Lol. His post makes sense.
I've pulled the booean method out and put it after the while loop. I'm not sure how I'd go about the bolded as I was under the assumption the while loop was the way to pull the writing from the file. Also, with the method out wouldn't that mean I'd be testing each zip code in the method manually?
public static void main(String[] args) throws IOException{
// Open a file
File myfile = new File("addresses.txt");
Scanner infile = new Scanner(myfile);
int counter = 0,houseNum,zipC;
String street, zip;
// Until there's no more data in the file.
while (infile.hasNext()) {
counter++;
// Read one entry.
houseNum = infile.nextInt();
street = infile.nextLine();
zip = infile.nextLine();
// Check if it's a zip code.
isZip(zip);
}
}
public static void main(String[] args) throws IOException{
// Open adresses.txt
File myfile = new File("addresses.txt");
Scanner infile = new Scanner(myfile);
int counter = 0,houseNum,zipC;
String street, zip;
// Until there's no more data in the file.
while (infile.hasNext()) {
counter++;
// Read one entry.
houseNum = infile.nextInt();
street = infile.nextLine();
zip = infile.nextLine();
// If it starts with 112, add it to All112.txt
????
// Otherwise, add it to AllElse.txt
????
}
}
So it'd be this thenI think it might help to take a step back and look at the big picture, because it seems like you're getting stuck on little things which are not really the main idea behind this exercise. Break this down into a sequence of steps. Forget about code, just break it down into a set of sentences that describe what you need to do:
If all you read is the main function (as you've currently written it above) you're going to see this sequence of steps:
That's what someone reading the body of the main function is going to see if they don't dig into all of the other stuff and see what your boolean function is going to do. To make this even clearer, we can take your original code and annotate it with comments to see this:
- Open a file
- Until there's no more data in the file
- Read one entry
- Check if it's a zip code
Code:public static void main(String[] args) throws IOException{ // Open a file File myfile = new File("addresses.txt"); Scanner infile = new Scanner(myfile); int counter = 0,houseNum,zipC; String street, zip; // Until there's no more data in the file. while (infile.hasNext()) { counter++; // Read one entry. houseNum = infile.nextInt(); street = infile.nextLine(); zip = infile.nextLine(); // Check if it's a zip code. isZip(zip); } }
Without having the body of isZip here, a casual reader would think your program does nothing. Your'e checking if it's a zip code, and then what? Nothing. To be clear, you are doing more, it just doesn't look like it, because that code is hidden and off somewhere that it shouldn't be.
What you would like it to look like is:
Forget about what this boolean function looks like for a second. Just make your main function look like that.
- Open a file named addresses.txt
- Until there's no more data in the file:
- Read one entry.
- If it starts with 112, add it to All112.txt
- Otherwise, add it to AllElse.txt
Easy, go back to the annotated function I wrote above and add in the new annotations:
Code:public static void main(String[] args) throws IOException{ // Open adresses.txt File myfile = new File("addresses.txt"); Scanner infile = new Scanner(myfile); int counter = 0,houseNum,zipC; String street, zip; // Until there's no more data in the file. while (infile.hasNext()) { counter++; // Read one entry. houseNum = infile.nextInt(); street = infile.nextLine(); zip = infile.nextLine(); // If it starts with 112, add it to All112.txt if(zipCode.startsWith("112")){ PrintWriter ofile = new PrintWriter("All112.txt"); ofile.println(zip); // Otherwise, add it to AllElse.txt else PrintWriter ofile2 = new PrintWriter("allElse.txt"); ofile2.println(zip); } }
Just fill in the question marks with actual code.
You're going to quickly find out (well, you've actually already found out) that every time you open All112.txt or AllElse.txt, it deletes the entire contents. So, you probably want to try to avoid doing that every time. How can you alter the above sequence of steps (not the code! the bulleted list of steps) so that you don't open the files more than once? After you've done that, how can you modify the code above to reflect the new sequence of steps you've written?
Honestly, I don't want to write anymore code here, because there's no way to give any more hints that don't just completely solve the homework for you, and plus you really need to be able to get this if you're going to understand more complicated stuff later.
// If it starts with 112, add it to All112.txt
if(zipCode.startsWith("112")){
PrintWriter ofile = new PrintWriter("All112.txt");
ofile.println(zip);
// Otherwise, add it to AllElse.txt
else
PrintWriter ofile2 = new PrintWriter("allElse.txt");
ofile2.println(zip);
}
}
Yea, it's doing the same thing. Except this time it took the last values of both instead of just the last value overall.Getting closer, but don't you still have tge same problem where you only get the last value?
PrintWriter ofile = new PrintWriter("All112.txt") is opening the output file, its being opened more than once. Pull it out of the loop, but without the loop how does the data get written more than once is what I'm stumped with. Another loop would cause the same problem.Remember what I said. Every time you open the output file it's going to delete whatever wwas there.
Which line opens the output file?
Does that happen once or more than once?
How can you fix it?
Just wanted to thank everyone for their help earlier, I don't know why I struggled so bad with this one. I think after awhile I got a mean case of tunnel vision and then just looking at the code was pissing me off.
void doSomething() {
if (cheapCheck) {
doSomethingExpensive()
}
}
Yea, got it working. What's even more frustrating was that the solution was pretty simple. I think had I more time to just go at it with fresh eyes and not angrily looking at it I probably would've got it.Got it working?
And it happens sometimes. There are times when I'm debugging an issue in the application for like 6 hours and then once I come back with a fresh mind I solve the issue in like 15 minutes. Sometimes you just need to give your mind a rest. Solutions to issues could come to you when its not even the focus of your thoughts.
Yea, got it working. What's even more frustrating was that the solution was pretty simple. I think had I more time to just go at it with fresh eyes and not angrily looking at it I probably would've got it.
I just turned 31 and I started re-education in application development (2 year class)I want to program video games but I'm 30 and have only the very basic knowledge of programming from when i was a kid and read a few C++ / C# / VB.Net books.
Is it too late for me?
I want to program video games but I'm 30 and have only the very basic knowledge of programming from when i was a kid and read a few C++ / C# / VB.Net books.
Is it too late for me?
std::vector<byte> password = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 };
for(int i = 0; i < size; i++)
{
if(!isdigit(password[i]))
return error;
}
Hi folks, looking for a bit of help.
Code:std::vector<byte> password = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 }; for(int i = 0; i < size; i++) { if(!isdigit(password[i])) return error; }
In the following code example, the password input must be decimal only. My isdigit() is not working correctly.
The documentation states: 'Checks if the given character is one of the 10 decimal digits: 0123456789.'
I am inputting 8 hex values but they are getting checked against the ascii values 0x30-0x39 and failing. From reading a bit on SO, do I need to convert my password values to ascii first of all in order to check if all the values are decimal?
Hi folks, looking for a bit of help.
Code:std::vector<byte> password = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 }; for(int i = 0; i < size; i++) { if(!isdigit(password[i])) return error; }
In the following code example, the password input must be decimal only. My isdigit() is not working correctly.
The documentation states: 'Checks if the given character is one of the 10 decimal digits: 0123456789.'
I am inputting 8 hex values but they are getting checked against the ascii values 0x30-0x39 and failing. From reading a bit on SO, do I need to convert my password values to ascii first of all in order to check if all the values are decimal?
Write a loop that prints the value of isdigit for all numbers between 0 and 255, then see if you can figure out your problem
// ********************************************************************************************
// MAIN
// ********************************************************************************************
int main(void) {
int res_code; // Result code from functions
char* message_template = "The window has xxx lines and yyy columns";
int msg_len;
int min_rows = 3;
// Here we start
@01 // Init various settings of our application
msg_len = @02 // Compute length of our template
// Maximal LINES and COLS are set by curses for the current window size.
// Check if the window is large enough to display our message
if ( LINES < @03 || COLS < @03 ) {
// Cleanup special curses settings and restore the normal terminal functionality
@04
// Print a conventional error message via printf.
// Note: this only work after the call to cleanupCursesApp();
printf("Window too small: we need at least%dx%d\n", @05, @05 );
// Set the result code to report the error
res_code = RES_FAILED;
} else {
// Center output
int mid_row = @06
int start_col = @06
// Write letter A to the top left corner of our display
@07 // Move to position
@07 // Put character there
// Write letter B to the top right corner of our display
// Use combination of move() and addch() functions
@08
// Write letter C to the bottom right corner of our display
@09
// Write letter D to the bottom left corner of our display
@10
// Write our message centered onto the display
mvprintw(mid_row, start_col,"The window has %3d lines and %3d columns", @11, @11);
// Refresh the screen in order to show all changes on the screen
@12
// Wait for user to press a key
@13 // make getch to be a blocking call
getch();
// Set the result code to report success
res_code = RES_OK;
// Cleanup special curses settings and restore the normal terminal functionality
@14
}
return res_code;
}
// ********************************************************************************************
// MAIN
// ********************************************************************************************
int main(void) {
int res_code; // Result code from functions
char* message_template = "The window has xxx lines and yyy columns";
int msg_len;
int min_rows = 3;
// Here we start
initializeCursesApplication(); // Init various settings of our application
msg_len = strlen(message_template); // Compute length of our template
// Maximal LINES and COLS are set by curses for the current window size.
// Check if the window is large enough to display our message
if ( LINES < min_rows || COLS < msg_len ) {
// Cleanup special curses settings and restore the normal terminal functionality
cleanupCursesApp();
// Print a conventional error message via printf.
// Note: this only work after the call to cleanupCursesApp();
printf("The window is too small: we need at least %dx%d\n", msg_len, min_rows);
// Set the result code to report the error
res_code = RES_FAILED;
} else {
// Center output
int mid_row = LINES/2;
int start_col = COLS/2;
// Write letter A to the top left corner of our display
move(0,0); // Move to position
addch('A'); // Put character there
// Write letter B to the top right corner of our display
// Use combination of move() and addch() functions
mvaddch(0,COLS-1,'B');
// Write letter C to the bottom right corner of our display
mvaddch(LINES-1,COLS-1,'C');
// Write letter D to the bottom left corner of our display
mvaddch(LINES-1,0,'D');
// Write our message centered onto the display
mvprintw(mid_row, start_col,"The window has %3d lines and %3d columns", LINES, COLS);
// Refresh the screen in order to show all changes on the screen
refresh();
// Wait for user to press a key
// make getch to be a blocking call
getch();
// Set the result code to report success
res_code = RES_OK;
// Cleanup special curses settings and restore the normal terminal functionality
cleanupCursesApp();
}
return res_code;
}
What error are you getting? Also, what is the application exit code and exit codes of the external functions you call?
Sorry I'm a total noob, could you tell me how to do that? I'm on Linux.