I am stuck with Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
1: Hi there. I don't know why my Java Cannot run. I think that my code is fine. Can anyone help me out?
This was the error message that was displayed after I run. The error message is displayed below.
It would be nice if someone can help me with this code. Thank you
This is the content of my file
A 1 50 3
B 2 1300 104
C 3 9000 900
D 4 1500
where
A - D Represents the transaction code
1 - 4 represents the Employeenumber
50, 1300,9000,1500 represents the retail price
and the last section represents the commission that I have calculated
This is the Question.
A transaction record on a sales commission file contains the retail price of an item sold, a
transaction code which indicates the sales commission category to which an item can belong,
and the employee number of the person who sold the item. The transaction code can contain
the values A, B or C which indicate that the percentage commission will be 6%, 8% or 10%
respectively. Construct an algorithm that will read a record on the file, calculate the commission
owing for that record and print the retail price, commission and employee number.
Convert this to Java
import java.util.Scanner;
import java.io.*;`
public class Question1
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner (new File ("C:\\Users\\leeli\\Desktop\\Assignment2Qns1.txt"));
double retailprice, commission;
String Empnum;
char transcode;
while(input.hasNext())
{
retailprice = input.nextDouble();
commission = input.nextDouble();``
Empnum = input.next();
transcode = input.next().charAt(0);
if (transcode == 'A' || transcode == 'a')
{
commission = retailprice *0.06;
}
else if (transcode == 'B' || transcode == 'b')
{
commission = retailprice *0.08;
}
else if (transcode == 'C' || transcode == 'c')
{
commission = retailprice *0.1;
}
else
{
commission = 0;
System.out.print("Invalid transaction code");
}
System.out.println("Transaction code \t Employee Number \t Retail Price \t Commission");
System.out.println(transcode + "\t" + Empnum +"\t" + retailprice +"\t" + commission);
}
}
}
//run:
//Exception in thread "main" java.util.InputMismatchException
//at java.util.Scanner.throwFor(Scanner.java:909)
//at java.util.Scanner.next(Scanner.java:1530)
//at java.util.Scanner.nextDouble(Scanner.java:2456)
//at Question1.main(Question1.java:18)
//Java Result: 1
//BUILD SUCCESSFUL (total time: 0 seconds)

Your order of reading from file matters a lot, you were getting the error because you were not reading the content in the correct order. You should read content in this order transcode, Empnum, retailprice, commission. This will fix your problem :
transcode = input.next().charAt(0);
Empnum = input.next();
retailprice = input.nextDouble();
commission = input.nextDouble();

Compare the input file and your code:
In the input file, a record consists of a letter followed by two or three numbers.
Your code is trying to read a record as two (floating point) numbers followed by two strings.
So your code is trying to read a letter as if it was a number. That won't work. That is what is causing the InputMismatchException exception.
Solution: Change your code to match the input file's format.
If your sample input file is accurate, changing the order of the nextXXX calls is not sufficient. That doesn't cope with the fact that the "commission" field is optional. Instead, you should read each record using Scanner::nextLine then create a new Scanner to parse the record.
For future reference: you can solve these problems yourself by doing the following:
Read the stacktrace to find the exception that was thrown, where it was thrown, and what your code called to get to the place where the exception was thrown.
Read the javadocs for the exception and (typically) the API method that your code called.
Figure out what the exception means in the context of your program and its input.

Related

Counter Loop - Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Edit: I have found a way to work with CompareTo to help with this problem, but for some reason I cannot get the count down to work.
It's a negative number that needs to get more negative to meet the requirements, but I am missing something here. When I execute the down section it closes the program. So to me this means that I have something messed up and the program isnt seeing the problem and closing.
We are supposed to:
Ask the user for an integer then ask the user if he/she wants to count
up or down. Display a table of numbers where the first column contains
the counter, the second column contains the counter plus 10, and the
third column contains the counter plus 100. Make it so each number
takes up 5 spaces total.
If counting up, the first column should contain numbers 1 through the
user input; If counting down, the first column should contain numbers
-1 through the the negative of the user input;
Do user input validation on the word "up" and "down". Allow for any
case.
import java.util.Scanner;
public class ps1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Comparision string already declared
String up = "up";
String down = "down";
//initialize the counters sum
int sum = 0;
//ask the user for a number
System.out.println("Enter an ending value");
int num1 = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Count up or down?");
String input = keyboard.nextLine();
while (input.equalsIgnoreCase(up) || input.equalsIgnoreCase(down)) {
System.out.println("Count up or down?");
input = keyboard.nextLine();
}
if (input.compareToIgnoreCase(up) == 0) {
if (num1 >= 0)
for (int c = 1; c <= num1; c++) {
sum = sum + c;
System.out.printf("%5d%5d%5d\n", c, c + 10, c + 100);
else
System.out.println("Up numbers must be positive");
if (input.compareToIgnoreCase(down) == 0) {
for (int c1 = -1; c1 <= num1; c1--) {
sum = sum + c1;
System.out.printf("%5d%5d%5d\n", c1, c1 + 10, c1 + 100);
}
}
}
}
}
I see you have figured out core logic. BTW, your code will not compile, there is a syntax error.
Your code would look like this:
print(a a+10 a+100)
I know that it's not valid syntax but you would be able to figure out the correct way to write the code.
To print data properly, you will need following:
https://dzone.com/articles/java-string-format-examples
I would recommend visualizing the output first. In your case, it would look like following: (_are spaces)
Enter an ending value: 2
Direction: Up
____1___11__101
____2___12__102
Also, think about error cases. What will happen in following:
Enter an ending value: -10
Direction: Up
Error: Improper data
You are allowing user to enter a positive num1 and count down using for (int counter1 = -1; counter1 >= num1; counter1--). This makes no sense as counter1 >= num1 resolves to -1 >= 1 which is never true. When direction is down the number must be negative and when direction is up the number must be positive.
You might need to loop until user provides a valid direction. Currently you go down for any input that is not up. A possible solution would be to:
String input;
do {
input = keyboard.nextLine();
} while (!input.equalsIgnoreCase("up") && !input.equalsIgnoreCase("down"));
Please use shorter variable names. counter1 is scoped just to the for loop block so call it i. It's easier to read.
Whichever editor you are using configure auto formatting :)

storing "inputdialog" data in an array

I have written a Java menu console which asks users to select an option. I have successfully compiled the menu system which takes a users input and directs them to a menu page. The first of these pages asks 2 questions using "InputDialog" boxes.
Here is the code for the "InputDialog", when I run the java console i can access and enter information into these boxes fine.
private void enterInfor()
{
String carInfo;
int carHours;
int i = 0;
double fee = Double.parseDouble("7.50");
double sum = 0;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car 1 entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carHours == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
I have the "String" and "int" information to store the information that is input by the user, however I need the program to store at least 20 different inputs which can be accessed later in the console.
I have successfully made a console repeat information and then output the combined answers using a for loop =
"for(int Num=1; Num <= 6; Num++)"
and this allowed me to repeat a set of questions and then compile the information into statistics afterwards but for this console I need the "InputDialog" to only take in one set of answers at a time and then return the user to the initial console menu.
I'm sorry again if this is all pretty vague of information or formats, just need some kind of help on how/where to put the correct code.

Debugger stops working

My program needs to allow the user to input an employee's name and total annual sales. When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. It should then print out the difference between the two numbers.
In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.)
When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code.
I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. (I'm using NetBeans, if that's relevant.)
Any ideas would be much appreciated!
EDIT: Here is the output and error message.
Name? captain America
Input annual sales: 80
Add another employee? yes or no
no
Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58)
package commission;
//Commicaion calulator
import java.util.Scanner;
public class Commission
{
public static void main(String args [])
{
salesPerson[] emps = new salesPerson[10]; //Employee Array
String cont = "yes";
String n="";
double s=0;
int i=0;
salesPerson high = new salesPerson();
salesPerson low = new salesPerson();
// scanner object for input
Scanner keyboard = new Scanner(System.in);
//Enter in employee name
while (cont == "yes"){
System.out.print("Name? ");
n = keyboard.nextLine();
emps[i] = new salesPerson();
emps[i].setName(n);
//Loop of yes or no entering more employees
//If yes add another name if no continue with total Commision
//Enter in the sales amount of commistion
System.out.print("Input annual sales: ");
s=keyboard.nextDouble();
emps[i].pay.annual = s;
System.out.println("Add another employee? yes or no ");
keyboard.nextLine();
cont = keyboard.next(); //Line 46: Debugger stops here.
if (cont =="yes")
i++;
if (i==9){
System.out.println("You have reached the maximum number of employees.");
cont = "no";
}
}
i=0;
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
high = emps[i];
if (emps[i].pay.annual < low.pay.annual)
low = emps[i];
}
double diff = high.pay.annual - low.pay.annual;
System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());
// Output table for composation with increments of $5000
// int tempAnnual =(int) pay.annual;
// for (i=tempAnnual; i<= pay.annual; i+=5000)
// System.out.println(i+" "+ pay.getReward(i));
}
public static class totalPay
{
double salary=50000.0; //Yearly earned 50000 yr fixed income
double bonusRate1=.05; //bounus commission rate of 5% per sale
double commission; //Commission earned after a sale
double annual; //Sales inputted
double reward; // Yearly pay with bonus
double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%
public double getReward(double annual)
{
double rate;
if (annual < 80000)
rate=0;
else if ((annual >= 80000) || (annual < 100000 ))
rate=bonusRate1;
else
rate=bonusRate2;
commission = annual * rate;
reward=salary + commission;
return reward;
}
}
public static class salesPerson
{
String name; //Employee Name
totalPay pay = new totalPay();
public void setName(String n) //Name
{
name=n;
}
public String getName()
{
return name;
}
}
}
You create this array of max size 10:
salesPerson[] emps = new salesPerson[10];
but only create and assign an object reference for each SalesPerson object entered. Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. You then attempt to iterate through the entire array (emps.length is 10 ):
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual)
which leads to the NPE when indexing the first null reference. You need to change your loop to something like:
int numEntered = i; //last increment
for (i=0; i< numEnetered; i++){
if (emps[i].pay.annual > high.pay.annual)
It stops the debugger because it waits for your input using the keyboard. If you type the input and hit enter, the debugger will continue from there on.
By the way, your should read up on naming conventions and coding best practices for java
Your debugger is stopped because it's blocked on input coming in from the Scanner. This is specified in the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That aside, you're fortunate to have entered that code block at all. You're comparing Strings incorrectly, so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. This is also the reason that your NPE occurs; you're initializing elements of your array under false pretenses (== with a String), so:
You may never initialize anything
You may only initialize the first thing (if (cont =="yes"))
I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. The other errors may become easier to see once you start using .equals, but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later.

How to solve this program?

I found this Java exercise :
Create a class Sales that has TotalSales (double) , Commission (double),
Commissi onRate (double), and NoOfItems (integer).
write a java application that asks the user to enter the Total Sales and the number of items then calculates the commission and prints it out.
The commission rate should be as following:
Condition :
Less than 500, commissionRate is 0
Greater than or equal 500 or Number of Items >= 5, commission rate is 5%.
Grater than or equal 1000 or Number of items >=10, commission rate is 10%
..
I wrote this code:
Main Class :
import java.util.Scanner;
public class testSales {
public static void main(String[] args) {
Sales s1 = new Sales();
Scanner get = new Scanner(System.in);
System.out.println("Enter total Sales");
s1.totalSale = get.nextDouble();
System.out.println("Enter number of Items");
s1.NoOfItems = get.nextInt();
if(s1.totalSale < 500){
s1.commission = s1.commissionRate = 0;
}
else if(s1.totalSale >= 500 && s1.totalSale <= 999 || s1.NoOfItems >= 5 && s1.NoOfItems <=9){
s1.commission = s1.commissionRate = s1.totalSale * 5 / 100;
}else if(s1.totalSale >= 1000 || s1.NoOfItems >=10) {
s1.commission = s1.commissionRate = s1.totalSale *10/100;
}
System.out.println(s1.commission);
}
}
One problem in your code is the case where NoOfItems > 5 but totalSale < 500. For this case, the commission will incorrectly be set to 0 because the first if statement eats it.
Please try to be more specific with your question. "this doesn't work and I don't know why" is not easy to help with.
Aside from the point brought up by HedonicHedgehog, there are a few other things to consider:
The sales class only has two global variables, which corresponds to the information entered by the user. The other two fields, commission and commissionRate, are calculated values. Therefore, there is no need to create variables for them. Just add to the sales class accessor methods (getters) that return these values. For example, below is my getCommission() method:
public double getCommission()
{
return totalSales * getCommissionRate();
}
Of course, you can see this method is dependent upon the getCommissionRate() method. Because there is a gap on your requirements with total items, I am ignoring it for now:
public double getCommissionRate()
{
if (totalSales < 500)
return 0;
if(totalSales < 1000)
return .05;
else
return 0.1;
}
Alternatively, you could create a LOCAL commission variable, and set the value before returning it. It is a good programming practice to limit the scope of your variables. In this case, there is not a good reason to have a global commission or commissionRate variables.
Lastly, your test class is simplified because all you need to do is to prompt the user for the two needed fields, and it simply spits out the output because the Sales class provides the calculation needed to figure out the rest:
public static void main(String[] args)
{
Sales s1 = new Sales();
Scanner input = new Scanner(System.in);
System.out.print("Enter total Sales");
s1.setTotalSales(input.nextDouble());
System.out.print("Enter number of Items: ");
s1.setNumOfItems(input.nextInt());
System.out.printf("$%.2f", s1.getCommission());
input.close();
}
I used the printf() method to format the output string. The following is a sample run:
Enter total Sales: 503.45
Enter number of Items: 5
$25.17
Enter total Sales: 1003.67
Enter number of Items: 19
$100.37
Enter total Sales: 45.00
Enter number of Items: 19
$0.00
Remember that this example ignores the number of items because of the reasons already mentioned. Once you figure out what needs to be done to cover of the gap in the requirements, you can modify this code to do the rest. Also remember that your Sales class only requires two fields: totalSales and numOfItems. The other to components (commission, and commissionRate) are calculated; therefore, no global variable or setter methods needed. Just the two getter methods I provided.

multiple while loop comparison (BigDecimal and > 10 )

This is my first post and I have been searching google and stack overflow for the past 24 hours and can not seem to pin down my problem.
I am creating a simple square root program. For the input section I start a 'while' loop. I need it to compare two conditions.
1. is the input a number
2. is the input a number over ten.
I was successful in creating the original program, however I ran into a small problem while debugging. When I put in a vary large decimal or number I would get a run time error.
I discovered that I could use BigDecimal() to solve this problem.
However I am now running into a logic error that I cannot solve no matter how many times I search the internet.
The two conditions that I use in the while loop are:
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
This will make sure that there is a BigDecimal, but will not make sure that the input number is over ten.
Here is the whole program
import java.math.BigDecimal;
import java.util.Scanner;
/**
#author Mike
*/
public class SquareRootingWithoutBigDecimal
{
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in);
double inputNumber = 0.00;
double rootedNumber = inputNumber;
BigDecimal inputNumberBig = new BigDecimal(0.00);
BigDecimal SENTINAL = new BigDecimal(10.00);
String garbage;
double garbageD = 0.00;
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
{
garbage = scan.nextLine();
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
}
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
rootedNumber = inputNumber;
do
{
rootedNumber = Math.sqrt(rootedNumber);
System.out.println(rootedNumber);
} while (rootedNumber >= 1.01 );
}
Any and all help is much appreciated.
-Mike
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
These HAVE to go before you while loop for your logic to work.
Also,
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
I could see this causing a problem. You should use && instead of ||

Categories

Resources