"error: variable keyboard is already defined in method main(String [])" - java

I'm getting several error messages when I try to run my program, the main one which bothers me being "error: variable keyboard is already defined in method main(String [])"
Am I supposed to but main(String []) more than once in my program, or just in the beginning as I have it? What else could be wrong here?
Here is the beginning of my program:
public static void main(String[]args)
{
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard = new Scanner(System.in);
firstName = keyboard.nextString();
System.out.println("Enter your last name:");
Scanner keyboard = new Scanner(System.in);
lastName = keyboard.nextString();
System.out.println("Enter the number of movies downloaded:");
Scanner keyboard = new Scanner(System.in);
moviesDownloaded = keyboard.nextInt();
System.out.println("Enter the cost per movie:");
Scanner keyboard = new Scanner(System.in);
movieCost = keyboard.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
Scanner keyboard = new Scanner(System.in);
stateResidency = keyboard.nextInt();

You should only declare and initialize keyboard once and then use it. So remove all lines of the type: Scanner keyboard = new Scanner(System.in); apart from the first one.
Otherwise you try to declare the same variable multiple times and thus java complains.

I'm guessing this has been long solved by this point but I came across it and I really like closure, because Ivaylo Strandjev answer was not chosen. Also in case anyone else stumbles across this.
The error is saying you defined the variable keyboard in this scope already and you are trying to define it again.
like Ivaylo Strandjev was saying.
You can try the following:
1 remove the declaration portion
public static void main(String[]args) {
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard = new Scanner(System.in);
firstName = keyboard.nextString();
System.out.println("Enter your last name:");
keyboard = new Scanner(System.in); //-----changed
lastName = keyboard.nextString();
System.out.println("Enter the number of movies downloaded:");
keyboard = new Scanner(System.in); //-----changed
moviesDownloaded = keyboard.nextInt();
System.out.println("Enter the cost per movie:");
keyboard = new Scanner(System.in);//-----changed
movieCost = keyboard.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
keyboard = new Scanner(System.in);//-----changed
stateResidency = keyboard.nextInt();`
or this, change the new variable names
public static void main(String[]args){
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard1 = new Scanner(System.in);
firstName = keyboard1.nextString();
System.out.println("Enter your last name:");
Scanner keyboard2 = new Scanner(System.in);//-----changed
lastName = keyboard2.nextString();
System.out.println("Enter the number of movies downloaded:");
Scanner keyboard3 = new Scanner(System.in);//-----changed
moviesDownloaded = keyboard3.nextInt();
System.out.println("Enter the cost per movie:");
Scanner keyboard4 = new Scanner(System.in);//-----changed
movieCost = keyboard4.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
Scanner keyboard5 = new Scanner(System.in);//-----changed
stateResidency = keyboard5.nextInt();`

You don't need to initialize Keyboard every time you use it. You can declare it once at the top of the program, and just call keyboard.next() each time you want to get something from it.

Related

How to avoid using the dummy lines?

I'm fairly new to programming so I'm currently stuck on figuring out how to make my code work cleaner. As of right now there are some random dummy lines in my code to make sure i dont skip part certain part of the loops. I was wondering if there are any ways to avoid it.
public static void main(String arg[]) {
String CandidateID;
String Name;
String Option1;
int Test1;
int Test2;
String dummy;
Scanner sc = new Scanner(System.in);
ArrayList<TestResult> StudentResults = new ArrayList<TestResult>();
do {
dummy = sc.nextLine();
System.out.println("Enter student data? y/n");
Option1 = sc.nextLine();
if (Option1.equals("y")) {
System.out.println("Enter Candidate ID:");
CandidateID = sc.nextLine();
System.out.println("Enter Name:");
Name = sc.nextLine();
System.out.println("Enter Test 1:");
Test1 = sc.nextInt();
System.out.println("Enter Test 2:");
Test2 = sc.nextInt();
TestResult TestResult = new TestResult(CandidateID, Name, Test1, Test2);
StudentResults.add(TestResult);
}
}
while (!Option1.equals("n"));
If you don't use the value inside the dummy variable, you can just execute sc.nextLine(); without assigning its return value to a variable.
It'll have the same effect, because the function is still being called.

Pass user input value from class to class on Java

I am working on the parking ticket simulator of the starting out with Java book, so the idea is to ask the user to input the officer's name, officer's badge number and some other other information, I have that information in the class ParkingCarSimulator class located on ParkingCarSimulator.java,
All of that is working fine, now in class called PoliceOfficer located in PoliceOfficer.java file, I would like to know if I can access the user input from the main method in the ParkingCarSimulator into the PoliceOfficer class.
Any ideas will be appreciated, here is the code I have:
import java.util.Scanner;
public class ParkingCarSimulator {
public static void main(String[] arsg)
{
String officerName, Make, carModel, carColor, carLicense;
int badgeNumber, minOnCar, minPurchased;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the officer's name");
officerName = keyboard.nextLine();
System.out.println("Enter the officer's badge number");
badgeNumber = keyboard.nextInt();
System.out.println("Enter the car's make");
Make = keyboard.nextLine();
System.out.println("Enter the car's model");
carModel = keyboard.nextLine();
System.out.println("Enter the car's color");
carColor = keyboard.nextLine();
System.out.println("Enter the car's liscence number");
carLicense = keyboard.nextLine();
System.out.println("Enter minutes on car");
minOnCar = keyboard.nextInt();
System.out.println("Enter the number of minutes purchased");
minPurchased = keyboard.nextInt();
}
}
Here is PoliceOfficer.java
public class PoliceOfficer
{
String policeName = ParkingCarSimulator.officerName;(this throws an error)
}
To create a PoliceOfficer, you need to give it a constructor then instanciate it in the main code
public class PoliceOfficer{
String policeName;
int badgeNumber;
public PoliceOfficer(String policeName, int badgeNumber){
this.policeName = policeName;
this.badgeNumber = badgeNumber;
}
}
use
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the officer's name");
String officerName = keyboard.nextLine();
System.out.println("Enter the officer's badge number");
int badgeNumber = keyboard.nextInt();
PoliceOfficer po = new PoliceOfficer(officerName, badgeNumber);
}

Grading weight not calculating correctly

public class FinalMarkCalculator
{
/**
* This method is used to caculate the students mark
*/
public static void main(String[] args)
{
//Assigning the string a variable that holds the students name
String studentName;
//Initalizing a keyboard scanner
Scanner keyboardStudentName = new Scanner(System.in);
//System printing out the question
System.out.print("Enter the students name: ");
//Assigns the string studentName to the users input
studentName = keyboardStudentName.nextLine();
//Assigning the double a variable that hold the students assignment marks as a integer
double assignmentMarks;
//Assigning the string a variable that hold the students assignment marks
String assignmentMarksInput;
//Initalizing a keyboard scanner with the variable
Scanner keyboardAssignmentMarks = new Scanner(System.in);
//Asking the user for assingment marks while printing students name
System.out.printf("Enter %s's mark for Assignments (Max. 140): ", studentName);
//Taking the user input and assigning it to our string assignmentMarksInput
assignmentMarksInput = keyboardAssignmentMarks.nextLine();
//Converting the user input from a string to a double
assignmentMarks = Double.parseDouble(assignmentMarksInput);
//Assigning the double a variable that hold the students Mid-Term exam marks as a integer
double midTermExamMark;
//Assigning the string a variable that hold the students assignment marks from user input
String midTermExamMarkInput;
//Initalizing a keyboard scanner with the variable
Scanner keyboardExamMidTermMark = new Scanner(System.in);
//Asking the user for the Mid-Term Exam mark while printing students name
System.out.printf("Enter %s's mark for Mid-Term Exam (Max. 60): ", studentName);
//Taking the user input and assigning it to our midTermExamMarkInput
midTermExamMarkInput = keyboardExamMidTermMark.nextLine();
//Converting the user input from a string to a double
midTermExamMark = Double.parseDouble(midTermExamMarkInput);
//Assigning the double a variable that hold the students Mid-Term exam marks as a integer
double finalExamMark;
//Assigning the string a variable that hold the students assignment marks from user input
String finalExamMarkInput;
//Initalizing a keyboard scanner with the variable
Scanner keyboardFinalExamMark = new Scanner(System.in);
//Asking the user for the Mid-Term Exam mark while printing students name
System.out.printf("Enter %s's mark for Final Exam (Max. 85): ", studentName);
//Taking the user input and assigning it to our midTermExamMarkInput
finalExamMarkInput = keyboardFinalExamMark.nextLine();
//Converting the user input from a string to a double
finalExamMark = Double.parseDouble(finalExamMarkInput);
//Printing grade report title
System.out.println("Grade report" + "\n------------");
//Printing the students name
System.out.println(studentName + "\n");
//Printing the assignments mark
System.out.printf("%.2f/140 worth 15%%\n", assignmentMarks);
//Printing the Mid-Term exam mark
System.out.printf("%.2f/60 worth 40%%\n", midTermExamMark);
//Printing the Final exam mark
System.out.printf("%.2f/85 worth 45%%\n", finalExamMark);
double finalMark = (assignmentMarks*.15)+(midTermExamMark*.40)+(finalExamMark*.45);
//Printing the total calculated final mark
System.out.printf("\n\nFinal Mark: " + finalMark);
}
}
My code runs fine but it does not do the math correctly and I can't seem to figure out why even if I put everything perfect it still doesn't equal 100%.
This is the equation I'm using and I think this is how it should be done:
(assignmentMarks*.15)+(midTermExamMark*.40)+(finalExamMark*.45)
The maths should be
double finalMark = (assignmentMarks/140*15)+(midTermExamMark/60*40)+(finalExamMark/85*45);
Also I think it is better to not declare (and then later) initialize your variables - do in one step
double assignmentMarks = Double.parseDouble(assignmentMarksInput);
Also just use one Scanner
Scanner scanner = new Scanner(System.in);
and use it for all input
String studentName = scanner.nextLine();
....
String assignmentMarksInput = scanner.nextLine();

Store in an ArrayList

How could i store the below code in an array list using Java? Im stuck. Your help will be greatly appreciated.
System.out.println("Please enter Officer's First Name");
firstName = input.next();
officerObject.setOfficerFirstName(firstName);
System.out.println("Enter Officer's Last Name");
lastName = input.next();
officerObject.setOfficerLastName(lastName);
System.out.println("Enter Officer's Badge Number");
badgeNum = input.next();
officerObject.setOfficerBadgeNum(badgeNum);
System.out.println("Enter Officer's Precint");
precint = input.next();
officerObject.setOfficerPrecint(precint);
Create an array list with List<YOUR OBJECT TYPE> array = new ArrayList<>(); and then use array.add(officerObject); to add it to the array list.
Well as he said use a List look
First it could be use like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Officer officerObject = new Officer();
System.out.println("Please enter Officer's First Name");
officerObject.setOfficerFirstName(input.next());
System.out.println("Enter Officer's Last Name");
officerObject.setOfficerLastName(input.next());
System.out.println("Enter Officer's Badge Number");
officerObject.setOfficerBadgeNum(input.next());
System.out.println("Enter Officer's Precint");
officerObject.setOfficerPrecint(input.next());
List<Officer> officer = new ArrayList<Officer>();
officer.add(officerObject);
for(Officer of: officer){
System.out.println(of.getOfficerFirstName());
System.out.println(of.getOfficerLastName());
System.out.println(of.getOfficerBadgeNum());
System.out.println(of.getOfficerPrecint());
}

how to get a scanner to read a pre-set variable

i am trying to use a scanner to get user input to add a new item to a stock list i have created, the item must possess the attributes itemID, itemDesc, price, quantity, and reorderlevel.
How would i go about reading the user input, and recognising it as one of those variables i've created, and then adding it to my list?
I've had a go, but it doesnt appear to recognise them as my variables
Any help would be much appreciated.
Thanks
MY ATTEMPT:
else if (i==1)
{
StockListInterface.doAddItem(item);
System.out.println("Add New Item");
System.out.println("****************");
System.out.println("Enter ID :>");
Scanner scanner1 = new Scanner(System.in);
String itemID = scanner1.nextLine();
System.out.println("Enter Description :>");
Scanner scanner2 = new Scanner(System.in);
String itemDesc = scanner2.nextLine();
System.out.println("Enter Price :>");
Scanner scanner3 = new Scanner(System.in);
String price = scanner3.nextLine();
System.out.println("Enter Quantity :>");
Scanner scanner4 = new Scanner(System.in);
String quantity = scanner4.nextLine();
System.out.println("Enter Re-Order Level :>");
Scanner scanner5 = new Scanner(System.in);
String reOrderLevel = scanner5.nextLine();
System.out.println("Enter another? (Y/N) :>");
}
You don't need to create a new Scanner every time you take an input. You can use the previously defined scanner as follows:
else if (i==1)
{
StockListInterface.doAddItem(item);
System.out.println("Add New Item");
System.out.println("****************");
System.out.println("Enter ID :>");
Scanner scanner1 = new Scanner(System.in);
String itemID = scanner1.nextLine();
System.out.println("Enter Description :>");
String itemDesc = scanner1.nextLine();
System.out.println("Enter Price :>");
String price = scanner1.nextLine();
System.out.println("Enter Quantity :>");
String quantity = scanner1.nextLine();
System.out.println("Enter Re-Order Level :>");
String reOrderLevel = scanner1.nextLine();
System.out.println("Enter another? (Y/N) :>");
}
Also you should consider adding one more line at the end, to get the input of 'Y' or 'N' as follows:
String addAnother = scanner1.nextLine();
One problem in your code i can see is you are creating Object of scanner every time when you get input.
I Suggest you to use class BufferedReader like this. It works perfectly.
BufferedReader br = null
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String tmp = br.readLine();
} catch(IOException ie){
System.out.println(e)
}
br.readLine() : always returns String
You need to convert String into related to datatype. Let's say i want to convert that string to integer, Then i can use wrapper class like this
Integer num = Integer.parseInt(tmp);
You don't need to create a new scanner every time you want to read input, just use
Scanner scanner = new Scanner(System.in);
and then every time you want to read input use
scanner.nextLine()
but if you know you're reading in an int etc you can use specific methods like
scanner.getInt()
see here for more information

Categories

Resources