Java declaration/ variable scope issues - java

I'm relatively new to java, and after much searching, I just can't pair up any solutions of related issues to mine. I'm trying to implement a very simple method to write to/ read from an array, and it's not being recognized by the compiler. "Keyboard" is a "variable not recognized" either. Here's a declaration of the array, with the method a bit further down that works on it... (first time long time btw :) Many thanks in advance...
private static void loadMakeModelYear()
import java.util.Scanner;
String [][] makeModelYear = {{"Make", "Model", "Year"},{"Blank", "Blank", "Blank"}};
private static void loadMakeModelYear()
{
for (int i = 0; i < 3; i++)
{
System.out.println("Please enter a " + makeModelYear[i][0]);
makeModelYear [i][1] = keyboard.nextLine();
}
}

This is just a guess, but your code appears to use keyboard with a lowercase k, while your error message uses Keyboard with a capital K. Check the case of your variables.

I juste rewrote your example as it may explain things better here.
import java.util.Scanner;
class SomeClass
public static void main(String...args) {
loadMakeModelyear();
}
static String[][] makeModelYear = new String[][] {
{"Make", "Model", "Year"},
{"Blank", "Blank", "Blank"}
};
private static void loadMakeModelYear() {
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("Please enter a " + makeModelYear[0][i]);
makeModelYear [1][i] = keyboard.nextLine();
}
}
}
There are a lot more resources for Java than there is for C#. One site that is often very useful (to me at least) is Real's howto (check out the Java index).

What IDE are you using for this? NetBeans does a decent job of providing most VS2010 functionality.
I do not see keyboard declared. Do you declare it elsewhere?
"keyboard" is not a special object in Java giving you access to the real life keyboard, if that helps.

My My My ..... Oh my dear, you're grossly confused in the way Java language operates. Lets look at your code more closely.
1.) Firstly, import statement should be the first statement in your file. The only statement which can come before import is the package statement.
but the glaring mistake which you're doing is by declaring methods like this. In java the scope of any method is bound to a class. This is not declarative style programming, where you can declare a stand-alone method. The same argument holds for your array as well, this array and method must be part of some class, even if they are static.
3.) Secondly, you are using a variable keyboard, but you have not declared it anywhere.
I hope you do realize that you're just using the wrong paradigm. Say this after me, "Java is purely OO "
Regards
AViD

I think I see your problem. This is just a guess, and I'm not sure if you have already done this. In the case that you haven't you might want to set your reference variable keyboard to the Scanner class. This can be done by:
Scanner keyboard = new Scanner(System.in);

Related

Why do I get 'Bash (input): command not found' error when using a string for the input, but when I change that part of the code to integers, it works?

I have this program that I'm writing that mainly runs similar to a simple choose your own adventure game. It's a trouble shooting guide for rocketry, that mainly for personal use. It has simple value inputs, y/n, a,b,c,d, and so on. After a few different segments I decided to ask the user (incase I give it to friends or something) if they would like to hear a tip, if they said yes, the tip would be printed out, if not, the program would continue running. When I tested it, i got the error message: 'bash y: command not found'.
All of the syntax is correct (that was the best answer I could find to try to correct the problem, didn't apply), and I don't know what bash is, and I'm using replit, incase that matters.
I get this error in two different areas, but here is an example of one:
//problem code
class A{
public static void tip(){
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to hear a tip? (y/n)");
String tipA = scan.nextLine();
if (tipA.equals("y")){
System.out.println("blahblahblah");
}
}
}
//there was a typo in this post but not in the actual code, wish it was the actual problem, thanks for pointing it out
Then I changed it to this:
//the 'fixed' code
class A{
public static void tip(){
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to hear a tip? (y(1)/n(2))");
int tipA = scan.nextInt();
if (tipA == 1){
System.out.println("blahblahblah");
}
}
}
It works, but as you can see in the 'fixed' code, the y/n doesn't look as nice, and I am also curious as to why, because I could not find any answers pertaining to this scenario.
The other area is similar, but instead of "y/n", it is 'A, B, C, D' choices.
I have my current workaround, but it would be nice to have a solution to polish the program a bit.
Any help is much appreciated.
It sounds like your problem is confusion about what nextLine does. It doesn't do what 99% of java programmers (and most tutorials) think it does. It's not a bug - it does exactly what the javadoc says, but, it's not what you'd expect.
See This answer that explains precisely what to do. Boils down to:
public static void tip() {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\R");
System.out.println("Would you like to hear a tip? (y/n)");
String tipA = scan.next();
if (tipA.equals("y")) {
System.out.println("blahblahblah");
}
Generally you'd want to make a scanner exactly once (in your main method perhaps), create a new instance of your Main class, set up the Scanner as a field of it, and then reuse it in all your methods. This saves typing, is easier to test, more flexible, etc:
public class ExampleMain {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
s.useDelimiter("\\R");
ExampleMain app = new ExampleMain();
app.scanner = s;
app.go();
}
private Scanner scanner;
private boolean running;
void go() {
running = true;
while (running) {
tip();
// whatever other commands and such you'd like go here
}
}
void tip() {
System.out.println("Would you like to....");
}
}
This also lets you do things like write a method that repeatedly asks for a specific kind of input (say, an integer between 1 and 9, as you're showing a menu with 9 options), and, using a while loop, keep asking if the user fails to enter appropriate responses. Otherwise you have to copy/paste a ton of code which is naturally not how you should be programming.

Java Is okay to put input/output only in main method?

I'm new to Java Programing.
Lately I am doing the Java assignment.
I sew this method in user-defined class
public void intputRank( Scanner s) {
salary = s.nextInt();
}
I was confused because I always want put I/O in main method (like in C++ I only write cin cout in main function). I have 2 reasons for doing this:
It's easy for me to see where my program accept input. When there is something wrong about I/O, I just need to debug the main method.
Scanner is a more complicated Class, use it as parameter would make unknown wrong.
So, kind Stack Overflowers, is it just a bad example or I understand something wrongly?
If it is the latter? Why not
public void inputRank( int asalary) {
salary = asalary;
}
//in main method
Scanner reader = new Scanner(System.in);
int asalary = reader.nextInt();
//then pass the asalary as parameter
If your program needs to be robust, e.g. when prompting for an integer it'll validate the input and re-prompt if bad, then having reusable helper methods is a good thing.
This means that you'll need multiple methods that use Scanner. Now, you can pass the Scanner object in as a parameter, or you can put it in a field, that's entirely up to you.
But the main point is that having code in a method that uses a Scanner is perfectly fine, and it really is a must for robust code, otherwise you'll ruin the DRY (Don't Repeat Yourself) principle.
Example:
public static int promptNonNegativeInt(Scanner sc, String prompt) {
for (;;) {
System.out.print(prompt + ": ");
if (! sc.hasNextInt()) {
System.out.println("** Not a valid number, please try again");
sc.nextLine(); // discard bad input
continue;
}
int value = sc.nextInt();
sc.nextLine(); // discard any extra text on the line
if (value < 0) {
System.out.println("** Number cannot be negative, please try again");
continue;
}
return value;
}
}
Example use
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int value = promptNonNegativeInt(sc, "Enter number");
System.out.println("You entered: " + value);
}
Even more complex is if you need to prompt for an object with multiple fields. Isolating the code that does this is good programming (separation of concern), so writing a promptMyObject(Scanner sc) method is a good thing.
Especially if you need to prompt for various objects. If you leave all prompting code in the main() method, it'll be huge and unreadable. It would be a God method, a variation of the God object:
A God object is an object that knows too much or does too much. The God object is an example of an anti-pattern.
In general, I prefer to write methods that take simpler types over more complicated types. This makes them easier to compose and reuse later on.
In your example, the method that takes an int could be considered better than taking a Scanner, because int is simpler and more common than a Scanner. That being said, the name inputRank kind of implies it's doing to read / receive input, so I would be tempted to rename it to something like applyRank in this case.

Illegal start of type/expression (Bracket placement help?)

So I'm very new to java and I'm trying to write a program that will print a correct fine for overdue books. I've read multiple questions like this and most of them involve misplacement of curly brackets, but I cannot find a bracket error anywhere. I keep getting multiple errors in my program, but most of the read "illegal start of type" or "illegal start of expression" Could someone help me with my code/give me some tips on bracket placement?
Here is my code:
public class BookFine
{
public static void main(String[] args)
{
int daysLate = 0;
int bookCost = 0;
int result = 0;
System.out.print("Enter how many days your book is overdue: ");
int daysLate = IO.readInt();
System.out.println("Days Late = " + daysLate);
System.out.print("How much does your book cost(enter in cents): ");
int bookCost = IO.readInt();
System.out.println("Book Cost = " + bookCost);
if (daysLate=<7)
{
result=daysLate*10;
}
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
IO.outputStringAnswer(result);
}
}
There is an issue regarding declaring variable twice in the program. I have corrected the code. Please refer below code.
public class BookFine {
public static void main(String[] args)
{ int daysLate = 0;
int bookCost = 0;
int result = 0;
System.out.print("Enter how many days your book is overdue: ");
daysLate = IO.readInt();
System.out.println("Days Late = " + daysLate);
System.out.print("How much does your book cost(enter in cents): ");
bookCost = IO.readInt();
System.out.println("Book Cost = " + bookCost);
if (daysLate<=7)
{
result=daysLate*10;
}
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
IO.outputStringAnswer(result);
}
}
You appear to have no brackets for your else branch
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
Should be
else
{
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
}
There were several errors in the code I was able to identify.
first the expression:
if(daysLate=<7)
is backwards. It should read
if(daysLate<=7)
Next, at the start of the code just under main you are declaring your variables "daysLate, bookCost". Then, after your line:
System.out.print("Enter how many days your book is overdue: ");
you are redeclaring the variables as:
int DaysLate
Remove the "int" portion on both daysLate and bookCost and it should run fine assuming you have an IO class defined somewhere.
There's a few problems here.
daysLate=<7; I assume that you mean to use the <= operator. Fixing this will resolve the specific error you're asking about
int daysLate = IO.readInt();; The problem with this line is that you've already declared a variable named 'daysLate'. This can be fixed in one of two ways: either remove the 'int' at the start of this line, or remove the original declaration on line 4. (I prefer the former.)
IO.readInt(); there is no class named IO, at least not in terms of what's imported by your code. There are a number of different ways that you can read input from the keyboard, however. If this is your intent (and it appears like it is), you might want to look up the documentation and examples for the java.util.Scanner class. I repeat, there are more than one ways to accomplish this, even if you don't want to use Scanner, so pick your poison :)
IO.outputStringAnswer(result); Same as #3, except that this time it looks like you're trying to output the result somewhere. Perhaps System.out.println() is in order here.
int bookCost = IO.readInt(); Same as #2 and #3. 'bookCost' is already defined in this scope, so you don't need to declare it again (remove 'int'). And again, you will need to write working keyboard input.
Finally--and this isn't an error per se--you should work on your Indent Style. It will greatly help your code readability, which will in turn help you write better code. Code that you and your colleagues enjoy reading is good (and hopefully healthy) code. Most developers these days use the 1TBF style, from my experience.
Oh, and Welcome to Java!

Calling substring Method?

I am fairly new to Java. Over the past few weeks I have been trying to teach myself java. This has been primarily based on tutorials i find online and forums I can find. So keep this in mind and any additional critique you can share is greatly appreciated! I am currently trying to create a calculator that runs off of if-else loops. I'm working on a method that allows the user to derive a function based on the principle that if
f(x)=ax^n+bx^o+cx^p... then f'(x)=anx^n-1+box^o-1+cpx^p-1...
I'm trying to use .split() to separate the parts of the function, perform the changes to the individual parts, and then print them together. I could get most of the way through this but I couldn't convert a string with a negative sign to an integer so I am trying to call a method that uses .substring and then replaceAll to get rid of the negative sign then convert to integer. However, I keep getting a compiling error stating the "actual and formal argument lists differ in length". Can anyone explain why this might be happening?
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class InputInteger
{
public String changeSign(String second) {
String negative = second.substring(0,1);
return negative;
}
public static void splitFunction() {
Scanner o = new Scanner(System.in);
String function = o.next();
String[] parts = function.split("(?=\\+|\\-)");
for (int i = 0; i < parts.length;) {
String[] second = parts[i].split("(?=[0-9]+|[a-z]+|[A-Z]+\\^)");
InputInteger.changeSign();
if (negative = ("-")) {
second = second.replace("-","");
int x = Integer.parseInt(second[0]);
int y = Integer.parseInt(second[2]);
int w = x*y;
int z = y-1;
System.out.println(w + "x^" + z);
i++;
}
}
}
Problem that you are talking about is the method not working . You have to pass argument in the function like
InputInteger.changeSign(function);
or
InputInteger.changeSign(second[i]);
according to requirement
changeSign(String second) should be defined as static
negative variable is not defined
you should compare strings with equals() method
you call .replace(...) on an array, which doesn't have this method
And these are only compile errors, I see at least one runtime problem:
you increase i only in the if which may result in an infinite
loop...
I suggest you use some good IDE like Eclipse or IntelliJ IDEA, which will help you with warnings/errors/etc.
First of all in your code if (negative = ("-")) you have a single "=" and I think you meant to use "==" for comparison. Second, method parseInt() as well as valueOf() (which I prefer to parseInt()) should handle negative numbers just fine. there is no need to remove "-". Yout method changeSign() takes a String argument, also your method ChangeSign() returns String value and you must assign a result to some String: String negative = InputInteger.changeSign(str);. Plus also String class has a method startsWith(String prefix) that fits your better then substring(). Hope this helps. If anything there is an Open source library that provides a Utility for parsing String into Integer (among other things). in That util there is a method
parseStringToInt(String numStr, int defaultValue,
String nullOrEmptyStringErrorMessage, String numberFormatErrorMessage)
That tries to parse a String to Integer and if it does not succeed it returns a default value and never throws an Exception. That method definitely works fine with negative integers. Here is the link to the article about the library.https://www.linkedin.com/pulse/open-source-java-library-some-useful-utilities-michael-gantman?trk=pulse_spock-articles. There you will find the instructions on where to get the library including javadoc and source code.

Java, how to compare Strings with String Arrays

I have been searching here for some time but haven't been able to find the answer to it.
I am basically required to use an array for this assignment from college. And then I am supposed to check that the input (which is also a String) matches whatever's stored within the String array.
I know one can easily compare Strings by using the .equals() method. However, the same method is not working with the String array.
I created the following example of code for the purpose of StackOverflow so you can use it to explain it to me, if you'd like.
What am I doing wrong?
import java.util.Scanner;
class IdiocyCentral {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
/*Prints out the welcome message at the top of the screen*/
System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf("%55s", "=================================\n");
String [] codes = {"G22", "K13", "I30", "S20"};
System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
System.out.printf("Enter one of the above!\n");
String usercode = in.nextLine();
if (codes.equals(usercode)) {
System.out.printf("What's the matter with you?\n");
}
else {
System.out.printf("Youda man!");
}
}
}
I apologize if this has been asked before and I just missed it, if its a double question, I will remove it.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.
if(Arrays.asList(codes).contains(userCode))
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
Iterate over the codes array using a loop, asking for each of the elements if it's equals() to usercode. If one element is equal, you can stop and handle that case. If none of the elements is equal to usercode, then do the appropriate to handle that case. In pseudocode:
found = false
foreach element in array:
if element.equals(usercode):
found = true
break
if found:
print "I found it!"
else:
print "I didn't find it"
If I understand your question correctly, it appears you want to know the following:
How do I check if my String array contains usercode, the String that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
Instead of using array you can use the ArrayList directly and can use the contains method to check the value which u have passes with the ArrayList.
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}

Categories

Resources