This question already has answers here:
Local variables of same name in same scope, IDE display error but when I run the program, no run time error results
(3 answers)
Closed 4 years ago.
I just wanted to say that I am new at java and I have been practicing and getting a LITTLE better. I'm trying to make a very simple banking system where you have the options to create an account, deposit and withdraw money. I'm a bit stuck at this current time though and hoping someone could help me out.
I'm trying to take input from the user and then create a new object instance with the user input in the parameters and it's giving me and error. Here is the code line it's giving me the error on, thank you!
It's prompting me with the error on the: bankAccount object creation line for the userName String variable.
case 1:
System.out.println("Please Enter Your Name: ");
String userName = input.nextLine();
System.out.println("Please Enter a 4 digit pin number: ");
int pinNumber = input.nextInt();
int accountNumber = rand.nextInt(5100 - 1100) + 1000;
System.out.println("Account Created with the following credentials:\n " +
"Name: " + userName + "\n" +
"Account Number: " + accountNumber + "\n" +
"Pin Number: " + pinNumber);
bankAccount userName = new bankAccount(userName, accountNumber);
break;
With java, you cannot make a local variable with the same name, even though the data types are different.
userName is already used as a String variable so you cannot make a new bankAccount named userName. You could name it userAccount though.
Example:
bankAccount userAccount = new bankAccount(userName, accountNumber);
You could then add this to an array or Map to reference that particular userAccount later.
bankAccount[] accounts = new bankAccount[];
//several lines of code
bankAccount[0] = userAccount;
or
Map<String, bankAccount> bankAccount accounts = new HashMap<String, bankAcount>();
//several lines of code
bankAccount.put(userAccount.userName, userAccount);
To retrieve the userAccount of a certain user, you can do this later in the program.
bankAccount userAccount = bankAccount.get("bob");
This is get the bankAccount that has "bob" as the userName.
I imagine you're doing this as an independent project. If you have the time, it could be a good idea to learn some java from codecademy to get a better understanding of the basics.
You have created the variable userName twice in line number 2 and 10. in java you cannot create the same variable name even though they have two types.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm learning the basics of Java, and wanted to practice something. So found a page of some programing problems and I get stuck at this problem:
2) Write a program that asks the user for her name and greets her with her name.
3) Modify the previous program such that only the users Alice and Bob are greeted with their names.
I've made well the 2nd but I have trouble with 3rd one.
System.out.pritnln("Please enter your name ");
Scanner input = user new Scanner(System.in);
String user_name;
user _name = input.next();
if(user_name == "Alice"){
System.out.println("Hello " + user_name + ", sweet name.");
if(user_name=="Bob"){
System.out.println("Hello " + user_name + ", sweet name.");
}
}
Don't use == for string comparison in Java unless you're really sure that is what you are doing. Use:
user_name.equals("Bob")
I actually use equalsIgnoreCase() as my standard approach unless I'm sure it should be case-sensitive.
I'm creating a banking system and can't seem to store the name of the customer names in an array. The last customer name is just overridden on the next customer. These are the lines concerning the array.
ArrayList<String> allnames1 = new ArrayList<String>();
System.out.println("Please enter account holders name:");
allnames1.add(sc.nextLine());
System.out.println("Account Created. Overview and Balance: " + "\n" + allnames1);
After this happens the user is taken back to the "Main Menu" in another class.
allnames1.add ("a")
allnames1.add ("b") is enough.
If it doesn't work; I think its because allnames1 is newly created every time.. or sc.nextline is wrong.
I want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried writing
System.out.println("If you take" + stepsOne * firstNum + "steps in a 10 second interval, you could potentially achieve...");
and just about every variation I can think of but I keep getting error messages. Apparently javac hates me for some reason. :/
Also, whenever the greeting displays, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
Here's my code:
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner userInputScanner = new Scanner(System.in);
int firstNum;
firstNum = 6;
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello," + userName + ". How many steps do you take in a ten second interval?");
String stepsOne = userInputScanner.nextLine();
System.out.println("If you take" + stepsOne + "steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute:");
System.out.println ("Number of steps per hour:");
}
}
There is a crucial difference between the string 123 and the integer 123 - the first is merely a sequence of characters, which have no mathematical meaning. You need to parse the string, meaning that you must construct an integer based on the characters of the string. There's a built-in method for this (although it's very interesting to do it yourself too): Integer.parseInt().
String stepsOneString = userInputScanner.nextLine();
int stepsOne = Integer.parseInt(stepsOneString);
Now, stepsOne is an integer on which you can perform mathematical operations. However, Integer.parseInt() throws an exception that you'll need to handle. At this point in your course, I'm guessing that you're expected to use the built-in conversion capabilities of the Scanner:
int stepsOne = userInputScanner.nextInt();
This will essentially perform the two above steps for you.
I strongly recommend that you read up on the subject of data types, which will explain the above concepts.
Once you have a string representing a number, you can use Integer.parseInt() to get an integer from it.
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
Here is a complete program with improved spacing.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine(); //Asks user name
System.out.println("Hello, " + userName +
". How many steps do you take in a ten second interval?");
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
System.out.println("If you take " + steps +
" steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute: " + (6 * steps));
System.out.println ("Number of steps per hour: " + (60 * 6 * steps));
}
}
Basically, I just want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried typing
First problem is stepsOne is String, so it can't be used to perform arithmetic on (at least not they type you're trying). So you need to convert it to a int
int stepsOneInt = Integer.parseInt(stepsOne);
nb: This will throw a NumberFormatException if the String can't be converted to a int value, so beware of that
Now you can use it to perform other arithmetic tasks
System.out.println("If you take " + (stepsOneInt * firstNum) + " steps in a 10 second interval, you could potentially achieve...");
Also, whenever the greeting displays in javac, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
That's because you don't add any spaces before you print the value
System.out.println ("Hello, " + userName + ". How many steps do you take in a ten second interval?");
Not sure to understand your issue...
You can't do stepsOne*firstNum as stepsOne is a String.
If stepsOne must be an int, just do this:
int stepsOne = userInputScanner.nextLine(); //Asks user a nb
I'm trying to write a program that needs to stop when the target of £500 has been met. I have to use a DO WHILE loop to do this.
It needs to record how many donations it receives before it reaches £500, also it needs to record the name of the person with the highest donation given and what the largest donation was.
I cannot get the program to update the name of the person with the highest donation. The code I have so far is below. Please tell me where I am going wrong.
I have a red line coming up under 'namemax' when I try to call it at the end outside of the loop, saying 'not initialized'
enter codeimport java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 11/02/2015
* Time: 15:45
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class DoWhile
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
final double TOTAL=500;
String name,namemax;
double donation, donationTotal=0,currentMax=0;
int howManyDonation=0;
do
{
System.out.println("Please enter your name below");
name = keyboard.next();
System.out.println("");
System.out.println("Please enter the amount you would like to donate below");
donation = keyboard.nextDouble();
howManyDonation++;
donationTotal = donationTotal+donation;
if(donation>currentMax)
{
currentMax=donation;
namemax=name;
}//if
}//doWhile
while(donationTotal!=TOTAL);
System.out.println("The total number of donations is " + howManyDonation);
System.out.println("The largest donation was " + currentMax);
System.out.println("The name of the person with the largest donation is " + namemax);
}//main
}//class
here
Just change this line
String name,namemax;
into this:
String name,namemax = null;
Furthermore, change this
while(donationTotal != TOTAL);
into this:
while(donationTotal < TOTAL);
You have a pretty simple problem here. You are updating namemax inside of an if loop only. That means that as far as the code is concerned, there is a possible situation in which it could never be assigned. In practice, because of what you are doing, that can't actually happen but the compiler doesn't understand that.
To fix it,
change
string name,namemax;
to
string name;
string namemax = "";
That should take care of it.
it gives at least one sutuation where namemax not will be set. So you have to initialize the string.
Simply change
String name,namemax ;
To
String name,namemax = null;
or
String name,namemax = "";
The compiler can't guarantee that you'll actually set the namemax before you exit the loop. You should initialize namemax to the empty string to fix this problem.
I'm writing a program that creates an object which holds to inputs from the user and stores it in an ArraySortedList. One of the requirements is to check and see if the particular object is already in the list. The trouble I'm having is whenever I input a secound set of information I get an error.
//Global variables at the top
ListInterface <Golfer> golfers = new ArraySortedList < Golfer > (20);
Golfer golfer;
//Function Variables
Scanner add = new Scanner(System.in);
Golfer tempGolfer;
String name = ".";
int score;
while(!name.equals("")) //Continues until you hit enter
{
System.out.print("\nGolfer's name (press Enter to end): ");
name = add.next();
System.out.print("Golfer's score (press Enter to end): ");
score = add.nextInt();
tempGolfer = new Golfer(name,score);
if(this.golfers.contains(tempGolfer))
System.out.println("The list already contains this golfer");
else
{
this.golfers.add(this.golfer);
System.out.println("\nYou added \'Golfer(" + name + "," + score + ")\' to the list!");
}
}
Error Message:
Exception in thread "main" java.lang.NullPointerException
at ArrayUnsortedList.find(ArrayUnsortedList.java:67)
at ArrayUnsortedList.contains(ArrayUnsortedList.java:110)
at GolfApp.addGolfer(GolfApp.java:90)
at GolfApp.mainMenu(GolfApp.java:52)
at GolfApp.main(GolfApp.java:24)
I'm almost sure it's something to do with how the variable is referenced but I'm not really sure how I could fix it, I have a lot of trouble with variable referencing.
Your golfer variable is not initalized.
try with :
this.golfers.add(tempGolfer);
regards.