I'm in the final stages of testing before I release the alpha version of a program I am writing. This may be a silly question but I just can't seem to figure it out. I understand what drjava is telling me, that I'm missing a variable, but I also don't understand because I never made a variable under the name "()". I'm not even sure you can set any type of variable to a open-close parenthesis. Anyways I was testing and while it works, it doesn't the way I want it to. I entered into the scanner "Mr. B." without the quotes of course. The program did not print the B. I'm thinking it might be the space in between Mr. and B, because other inputs with a space did the same. I can not release a version of my program knowing there is a GIANT glitch in the code. I'm wondering why, and I tried to fix it by changing ownersname.next(); to ownersname.nextLine and ownersname.next and ownersname.nextScanner and ownername.nextScanner. This is where the error comes in, when it says it can't find the variable until I change it back to it's original code, which is below.
Scanner ownersname = new Scanner(System.in);
String sownersname = ownersname.next();
System.out.println(sownersname + "? That is a nice name.");
I'm in the final stages of testing before I release the alpha version of a program I am writing.
You're creating a professional application? Please do tell us more about this.
I understand what drjava is telling me, that I'm missing a variable, but I also don't understand because I never made a variable under the name "()". I'm not even sure you can set any type of variable to a open-close parenthesis.
When posting questions here, if you have an error message from the compiler, please post the entire error message with your question. Don't paraphrase it. And indicate by obvious comment in your code, i.e., // ****** error here ***** where the error is occurring.
Anyways I was testing and while it works, it doesn't the way I want it to. I entered into the scanner "Mr. B." without the quotes of course. The program did not print the B. I'm thinking it might be the space in between Mr. and B, because other inputs with a space did the same.
Don't use Scanner#next() which gets only the next token -- the next word before reaching whitespace (here, Mr.), and will not get the rest of the text on the line. Instead use Scanner#nextLine() which gets you the whole line.
For example:
Scanner ownersname = new Scanner(System.in);
// String sownersname = ownersname.next(); // *** not this ***
String sownersname = ownersname.nextLine(); // *** but rather this ***
System.out.println(sownersname + "? That is a nice name.");
I can not release a version of my program knowing there is a GIANT glitch in the code.
Seriously, you're creating a professional application? I'm not yet at that stage, which is why I ask.
I'm wondering why, and I tried to fix it by changing ownersname.next(); to ownersname.nextLine and ownersname.next and ownersname.nextScanner and ownername.nextScanner. This is where the error comes in, when it says it can't find the variable until I change it back to it's original code, which is below.
I'd be curious to see your nextLine() method attempt, because that is the solution. Perhaps you were trying to call the method without using the method parenthesis.
I also assume that you're familiar with the Java API and have looked up the Scanner entry for it. If you did, you would see right away that there is no nextScanner() method for this class. This is one reason I have to wonder about your making a professional application at your stage. Again, I don't feel that I'm at the stage yet to create one yet, so please don't take this as an insult, just a curiosity.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am new to java. Trying to create a function to remove a given string "arg" from myString which is previously set and return a new string not affecting myString. I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string. so if arg has a 7 in it that should still be included in the final string. characters being removed are case insensitive as well.
I have edited the previous code and post, i can now run my code but I am not getting the correct results, I am trying to remove all numbers from arg before using it to remove all the characters. myString method is previously defined and working properly to return a string.
For examplecurrent string "my lucky numbers are 6, 8, and 19.", calling remove("ra6") would return "my lucky numbes e 6, 8, nd 19."
or "my lucky numbers are 6, 8, and 19.", calling remove("6,.") would return "my lucky numbers are 6, 8, and 19."
thank you!
public String remove(String arg) {
char[] charArray=arg.toCharArray();
String result="";
String newString="";
for (int i = 0; i < charArray.length; i++) {
if (!Character.isDigit(charArray[i])) {
result = result + charArray[i];
return result;}}
if (myString==null || myString=="") {
this.myString="";}
if (myString!=null) {
newString= myString.replaceAll(result,"");}
return newString;
}
Here is one way using streams. Just create a stream of characters via the chars() method and allow only letters to pass thru. Then each character to a String and join them together. Then remove that result from the original passed string.
String myString = "abcdTLK123efgh";
String arg = "TLK###123";
String result = remove(arg, myString);
System.out.println("Result = " + result);
prints
Result = abcd123efgh
The method
I modified the method to accept two strings.
the one to remove characters(arg).
and the from which to remove modified arg from myString
it works by
streaming all the characters of arg.
filtering out all but letters and digits
joining them as a string.
and then removing that filtered string from the myString.
public static String remove(String arg, String myString) {
if (myString == null || myString.isBlank()) {
return "";
}
return arg.chars().filter(
ch -> Character.isLetter(ch))
.mapToObj(Character::toString)
.collect(Collectors.collectingAndThen(
Collectors.joining(),
str -> myString.replace(str, "")));
}
Note: If myString is null then assigning an empty string to it will contain nothing to change. Nor an initial empty string. So I just returned an empty String if those conditions existed.
I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string.
The good news is that you can solve it yourself.
The bad news is that the code above is in such a mess that it would be difficult for you to fix it by yourself. (Given your current level understand of Java syntax, way of working, etcetera.)
(Also, there is a long more wrong than the "if it were not for ..." ...)
So here is what I advise you to do.
Save a copy of the current version of the (entire) class somewhere safe so that you can look it again if you need to, or revert to it.
Develop a model of what the method needs to do and how it will do it; see below.
Delete all lines of code between the first { and last } shown in the question. Yes. Delete them.
Compose the new version of the code, one line at a time. As follows:
Add a line.
Compile the code (or let the IDE compile it for you).
Read the compilation error(s) that just appeared.
Understand the compilation errors.
Make the necessary changes to fix the compilation errors. Don't rely on your IDE's facility for suggesting corrections. (The IDE doesn't understand your code, what you are going to add next, or what you are trying to achieve. Its suggestions are liable to be unhelpful or even wrong.)
Repeat until you have dealt with all of the compilation errors that were introduced.
Now you are ready to add another line.
Once you have a complete method, you can then try to run it.
You will most likely find that the code doesn't work. But at least it will be valid Java code. And in the process of doing 4. above, you will (hopefully!) have learned enough Java syntax to be able to read and understand the code that you wrote. And 2. will help you understand what the code you are writing should do.
My other observation is that it looks like you have been adding and removing statements to this code with no clear understanding of what they do or what needs to happen. Maybe you started with some code that did something else ... correctly ... but it is hard to tell now.
Changing things randomly to try to make the code work is not a sensible approach. It rarely works. You need to have a model (or plan) in your head or on paper (e.g. as pseudo-code or flowcharts) about how the code ought to work.
Programming is about 1) developing the model, then 2) translating the model into code. The first part is the hard (and interesting) part. But if you skip the first part, the second part is an essentially random process, and unlikely to succeed.
The problem with starting with someone else's code is that you risk not developing a mental model of how that code works. Let alone the model that you are aiming for.
Finally, a professional programmer will use a version control system for their source code, and make relatively frequent commits of their code to their repository. Among other things, that allows them to quickly "roll back" to an earlier version if they need to, or keep track of exactly what they changed.
It is probably too early for you to learn about (say) using Git ... but it would help you solve your problem if you could just "roll back" all of the changes where you were "messing" with the code to get it to work.
Why am I getting an error while initializing ArrayList with a trailing comma (,) whereas I understand through various websites that Array with trailing comma(s) will create holes and iterating that will skip the holes?
Java:
class ProblemA {
public static void main(String[] args) {
//HashMap<Integer,Integer> map=new HashMap<>();
ArrayList<Integer> map = new ArrayList<>(Arrays.asList(1,2,2,3,2,));
int[] arr = {1,2,2,3,2,};
}
}
hereas I understand through various websites that Array with trailing comma(s) will create holes and iterating that will skip the holes
Not in java it doesn't. That's referring to various other languages where you can e.g. type [, , ,] and this makes a list of 4x "nothing". But java doesn't have that - the closest thing to nothing that java has is null, but you'd have to type it out. List.of(null, null, null, null) would make 'a list of 4x nothing' in java, as near as can be.
So what about java's trailing commas
As per the java language spec, in method invocations, you can't just toss a pointless and completely optional comma at the end of an arguments list. It's simply not valid java. However, when writing an array initializer, you CAN do that. Why? Just cuz. Spec says so. At some point your question boils down to: "What was the language designer thinking" - which is beyond the scope of Stack Overflow. You'd have to ask them.
At any rate, you are allowed to do it, and it does nothing at all. There is zero difference between int[] x = {1,2,}; and int[] x = {1,2};. Both produce a 2-sized array with elements 1 and 2. The trailing comma is completely optional and has absolutely no effect. Whatsoever. Identical class files. Go ahead, try it, compile it, run a byte-differ on the class files that come out. Identical.
But... why?
The reason trailing commas are convenient at times is because of version control systems. Stop thinking about writing 5 lines of script and your first programming lessons for a moment - think working in a bigger team, producing a product that hundreds of thousands of users depend on, where billions of euros just go up in smoke if e.g. a security issue is plaguing the code base.
You want to be capable of working together in teams, which means not all code you look at is written by you, neccessarily. That means you may want to, for any given line, ask the system: Hey, who last changed this line, and can you show me the other stuff they did around that time, and it would be even better if I can see a comment or a link to a ticket in a ticketing system that explains why they did all this, because I need that context to know what's happening.
The solution to that is version control systems, where you 'check in', as a unit of work, a bunch of modifications to existing source files. "Today, I added these 5 lines here, removed these 2 lines here, changed these 2 lines, and added these 2 whole new files. That whole thing comprises the fix for the bug mentioned in ticket 12894". That sort of thing.
Once you have that, you get a convenient route for code review: That your edits aren't just pushed straight into what powers, say, google.com, but that someone else first tests this out and looks at your changes; a second pair of eyes. They can look at exactly what you changed.
And only now can you understand the point of optional trailing commas. They do absolutely nothing, but imagine you have a list of, say, known US states. You might have:
String[] STATES = {
"Alabama",
"Arkansas",
"New york"
};
and then someone wants to add a new state to the list, so they edit that code:
String[] STATES = {
"Alabama",
"Arkansas",
"New york",
"Hawaii"
};
The problem is, technically they changed 2 lines there. They changed the New York line, by adding a comma. That 'noises it all up'.
Let's say I notice that its a bit odd they didn't spell it New York - that Y is customarily capitalized. Possibly some other system requires that it's all lowercase except the first letter, perhaps. I want to see who edited/made that New york line, what ticket is associated with it, and when it happened. So I ask the system and I get.... your edit. The one that added Hawaii - the one that is utterly irrelevant. Only because of that silly trailing comma. A code reviewer will also have to review that edit which also seems pointless.
Imagine instead that we have a policy of always using that pointless trailing comma that does nothing at all, and we started with:
String[] STATES = {
"Alabama",
"Arkansas",
"New york",
};
instead. Now I can add that Hawaii line (adding a pointless trailing comma), and now I haven't noised it up. My 'commit' (list of changes I made, it's a term of art in the Version Control System world) is just the one line adding hawaii, nothing more.
That's the only reason that java, or any other language, allows this concept of 'trailing commas in comma separated lists that do not actually do anything'. They do not create holes or an extra entry. They exist only to keep commits as clean as they can be.
You may correctly conclude I dislike the fact that you can't put trailing commas in method invocations. I'll make a point to mention this when the opportunity arises in amber-dev or what not - I'm pretty sure the structure of the language spec can handle it.
I've been searching around and havn't quite found my answer.
At this moment me and along with my group have created a few classes resembling a Bank with Customer and Account and so on.
I've been struggling lately with trying to improve and secure our code by making our variable called "name" only respond to certain inputs.
In this case, I want to make it only possible for the person to enter name as such:
Atleast 2 words = (For the word part I've seen codes where you count towards the white space between but don't know yet what you do about the last word since there wont be a white space)
Max 4 words = ( Same thing here)
No special signs such as ,!%¤"#()=%/'¨. = ( for this, I've read something about "Matcher and pattern" )
Now I'm quite new to Java and I'm not asking for a code from someone, I'm asking for someone to point me in the right directions regarding codes, because alot of what i've seen like the Matcher and pattern are things that you import with downloading utils and stuff but I reckon that it's not needed and there should be a simpler more basic way as I'm not trying to get ahead of myself with copying codes just to get it done.
So yeah, the String "name" is used alot in our main class "Banklogic" where almost every method that adds something has the variable "name" in it, so it's quite important that I get this done.
I hope I was clear enough and any help would be appreciated! I'm gonna put the alarm for 3 hours before school to see what you guys have come up with so I can try and complete the code before our meeting! Thanks alot in advance :)
Since you asked for hints, you can use Regex to add such rules.
For Numbers only:
if(string.matches("[0-9\\W]")
//allow insertion of data else not
As for rules related Word Count:
string.split("\\W") will create an array separated by space character. You can count the number of elements in this array and allow/disallow input based on that.
As for no signs and only letters:
if(string.matches("[a-zA-Z\\W]")
// Allow Input else not
You can use Document Filter to implement these methods. Document filter will only allow text to be entered if you allow it to.
I hope this helped as a hint.
Also, note that \\W is for whitespaces. If you dont want to allow whitespaces, remove that char.
This is the most effective and simple way of doing the task.
EDIT:
This is a Class I wrote a little while ago to achieve such tasks. Just in case if you are interested....
I'm writing a Mastermind program where it takes input for the guess, but I need to make sure that it only takes 4 characters of input. So if someone entered anything other than 4 characters, it would prompt for reentry. I know this isn't hard at all, I'm just drawing a blank and haven't been able to find an answer on here anywhere.
Lets try to do it, one step at a time.
Get user input in your program. If it's standard input, one way to pull it is with System.in, which is an InputStream.
Store the input in an intermediate variable. The type of this variable can be String.
If needed, cast the value to a type which is the most relevant to your application's requirement. Before that check input for bad values like null.
Perform the logic on the input, which in your case is finding out whether the length of the input is 4.
Prompt again for input if the current one doesn't meet the requirement. One way to do it is to put your relevant code in a loop which terminates only when you get the right input.
And if that doesn't work, you're most welcome to ask again including code that shows your effort.
Is there a website where I can run Java or C++ code online that lets me use cin in c++? Codepad and many others just let you see your program but don't let the user provide input, and I wanted to know if I could find a website that allows that.
Ideone doesn't seem to do the input right : This is supposed to be a game where you enter a word then the letter changes places, and then you need to figure out the word. The code is correct but the website doesnt read the cin right ! http://ideone.com/0PmDX
Ideone does just that this is also in the Info section of the c++ tag.
In your provided code: http://ideone.com/0PmDX you call return main(); which is undefined behaviour and is causing your infinite loops in your code. Try return 0 instead.
Code: http://ideone.com/ymXeH