while and for loops - java

How can I add up 3 inputs from the scanner using one variable, and while & for loop only (no array)?CLICK THIS LINK TO SEE IMAGE INCLUDING INSTRUCTIONS
HERE IS THE CODE THE NEEDE TO COMPLETE THE TASK IN THE IMAGE.
import java.util.Scanner;
public class Ass1b
{
public static void main (String[]args)
{
String taxPayerName;
int totalInc;
double totalTax;
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the tax payer==> ");
taxPayerName = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Enter the income for "+ taxPayerName +" ==> " );
totalInc = inNumber.nextInt();
if (totalInc < 18200)
{
totalTax = 0;
System.out.print("The tax that " + taxPayerName + " has to pay is $"+ totalTax);
}
else if(totalInc < 37000)
{
totalTax=((totalInc - 18200)* 0.19);
System.out.print("The tax that " + taxPayerName + " has to pay is $"+ totalTax);
}
else if(totalInc < 87000)
{
totalTax=(3572 +(totalInc - 37000)* 0.325);
System.out.print("The tax that " + taxPayerName + " has to pay is $"+ totalTax);
}
else if(totalInc < 180000)
{
totalTax=(19822 +(totalInc - 87000)* 0.37);
System.out.print("The tax that " + taxPayerName + " has to pay is $"+ totalTax);
}
else
{
totalTax = (54232 + (totalInc - 180000)*0.47);
System.out.print("The tax that " + taxPayerName + " has to pay is $"+ totalTax);
}
}
}

So the main questions seems to be: How can I add up 3 inputs from the scanner?
One scanner can be used multiple times, for example:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("value : " + scanner.nextInt());
}
}
This code would a for loop and one scanner object to ask the user five times for a integer. With this you should be able to complete the exercise. Now you just need to have an additional variable which keeps track of the total tax and then finally calculate the average tax.
In the future try to ask a more specific question, instead of just asking for the answer, because it seems this is a homework assignment. So I tried to help you out with general code, which doesn't answer the question directly.

Related

How to output each stock?

I have to do this program where I have to display the calculation of the profit for each individual stock, but I also have to display the profit for the total amount of stocks. My code only has it so it displays the calculation for all of the stocks:
import java.util.Scanner;
public class KNW_MultipleStockSales
{
//This method will perform the calculations
public static double calculator(double numberShare, double purchasePrice,
double purchaseCommission, double salePrice,
double salesCommission)
{
double profit = (((numberShare * salePrice)-salesCommission) -
((numberShare * purchasePrice) + purchaseCommission));
return profit;
}
//This is where we ask the questions
public static void main(String[] args)
{
//Declare variables
Scanner scanner = new Scanner(System.in);
int stock;
double numberShare;
double purchasePrice;
double purchaseCommission;
double salePrice;
double saleCommission;
double profit;
double total = 0;
//Ask the questions
System.out.println("Enter the stocks you have: ");
stock = scanner.nextInt();
//For loop for the number stock they are in
for(int numberStocks=1; numberStocks<=stock; numberStocks++)
{
System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
numberShare = scanner.nextDouble();
System.out.println("Enter the purchase price" + numberStocks + ": ");
purchasePrice = scanner.nextDouble();
System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
purchaseCommission = scanner.nextDouble();
System.out.println("Enter the sale price:" + numberStocks + ": ");
salePrice = scanner.nextDouble();
System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
saleCommission = scanner.nextDouble();
profit = calculator(numberShare, purchasePrice, purchaseCommission,
salePrice, saleCommission);
total = total + profit;
}
//Return if the user made profit or loss
if(total<0)
{
System.out.printf("You made a loss of:$%.2f", total);
}
else if(total>0)
{
System.out.printf("You made a profit of:$%.2f", total);
}
else
{
System.out.println("You made no profit or loss.");
}
}
}
How can I get it so each individual stock profit gets shown, with the profit of all the stocks together?
Try maintaining a separate Map for profit/loss. You may want to accept Stock Name as an input which will help manage individual stocks effectively.
// Map of stock name and profit/loss
Map<String,Double> profitMap = new HashMap<String,Double>();
After calculating profit/loss, add entry to map
profitMap.put("stockName", profit);
total = total + profit;
At the end of your program, iterate and display profit/loss for each Stock from Map.
for (Entry<String, Integer> entry : profitMap.entrySet()) {
System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
}

Issues with Looping

I am very new to Java. So I've created a script to receive input of a score, and then give a mark as output based on this score. My issue is I want the code to repeat to allow for entry of multiple scores, but I can't get it to work.
Edit: I have tried using the methods in the answers but I can't get it right. would it be possible for someone to do implement the loop into my code for me?
Here's my code:
import java.util.Scanner;
public class week4
{
public static void main(String[] args)
{
{
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
}
}
First, let's refactor the main logic into another method called calcGrade():
public void calcGrade() {
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
If we invoke this method, it will load a new student name & score from System.in, calculate the grade then print it.
Okay, the next part will be the loop.
There are 3 types of loop in Java, for/while/do-while.
You can use "for" when you know exactly what times you want to loop.
E.g. You know there is only 10 students in your class, then you can write such codes:
for (int i = 0; i < 10; i++) {
calcGrade();
}
If you don't know the times, but you know there is an exact condition to end the loop, you can use while or do-while. The difference between while and do-while is while can do the condition check first then do the inner logic, and do-while always do the inner logic for once time then check the condition.
E.g. You want to continue the loop when you acquire a String "YES" from the System.in.
System.out.println("Please input the first student info, YES or NO?");
Scanner inText = new Scanner(System.in);
while ("YES".equals(inText.nextLine()) {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
}
Also, you can use the do-while, if you know there are at least one people in the class.
Scanner inText = new Scanner(System.in);
do {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
} while ("YES".equals(inText.nextLine());
Hopes it's clear for you ;)
Easiest wway I can think of is to create a class called student and have variables for name, subjects, scores etc. Have setters and getters if you want or just have a constructor which takes in those inputs. Next have a method like computeGrade(). Creates instances of this student class every time you want some thing.
puclic class Student{
public String mName;
public String mSub1;
.
public int m_scoreSub1;
.
.
public computeScore(int m_score){
* your logic goes here ( the if else one)
}
}
Now just instantiate the class !!!

for loop class assignment gone wrong

I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}

I am stuck on homework assignment Commission Calculation

I need to compare the total annual sales of at least three people. I need my app to calculate the additional amount that each must achieve to match or exceed the highest earner. I figured out most of it and know how to do it if there were only two people in the scenario, but getting third into the equation is throwing me for a loop! Any help is appreciated and thanks in advance! Here's what I have so far, but obviously at the end where the calculations are not going to be right.
package Commission3;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
// Create a new object AnnualCompensation
Commission3 salesPerson[] = new Commission3[2];
// creat two object
salesPerson[0] = new Commission3();
salesPerson[1] = new Commission3();
salesPerson[2] = new Commission3();
//new scanner input
Scanner keyboard = new Scanner(System.in);
//get salesperson1 name
System.out.println("What is your first salesperson's name?");
salesPerson[0].name = keyboard.nextLine();
//get salesperson1 sales total
System.out.println("Enter annual sales of first salesperson: ");
double val = keyboard.nextDouble();
salesPerson[0].setAnnualSales(val);
//get salesperson2 name
System.out.println("What is your second salesperson's name?");
salesPerson[1].name = keyboard.next();
//get salesperson2 sales total
System.out.println("Enter annual sales of second salesperson: ");
val = keyboard.nextDouble();
salesPerson[1].setAnnualSales(val);
//get salesperson3 name
System.out.println("What is your third salesperson's name?");
salesPerson[2].name = keyboard.next();
//get salesperson3 sales total
System.out.println("Enter annual sales of third salesperson: ");
val = keyboard.nextDouble();
salesPerson[2].setAnnualSales(val);
double total1, total2, total3;
total1 = salesPerson[0].getTotalSales();
System.out.println("Total sales of " + salesPerson[0].name +" is: $" + total1);
total2 = salesPerson[1].getTotalSales();
System.out.println("Total sales of " + salesPerson[1].name +" is: $" + total2);
total3 = salesPerson[2].getTotalSales();
System.out.println("Total sales of " + salesPerson[2].name +" is: $" + total3);
if (total1 > total2) {
System.out.print("Salesperson " + salesPerson[2].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[0].name);
System.out.println(" $" + (total1 - total2));
} else if (total2 > total1) {
System.out.print("Salesperson " + salesPerson[0].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[1].name);
System.out.println(" $" + (total2 - total1));
} else {
System.out.println("Both have same compensation $" + total1);
}
}
}
When you take the input from the user, keep track of the highest sales thus far, and the name of the salesperson with the most sales.
Then, instead of checking total1 and total2, you can loop through all three, and compare them to the max. If the current total is less than the max, then calculate the difference. Otherwise, the current total is equal to the max, and you don't need to do the calculation.
I'll leave the actual code for you to figure out.

How to use loops and average in Java [duplicate]

This question already has answers here:
How to get average from given values
(3 answers)
Closed 9 years ago.
My program is supposed to find the average of female, male, and total average GPA of students. And also total female, male, and total students. First it asks if the student is male or female. If you choose male it does the loop, but after it ends. I want my program to go straight into the next choice. Example if you choose male the you'll input female and visa versa.
import java.util.Scanner;
public class practice {
public static void main(String [] args) {
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
System.out.println("Enter GPA");
GPA = keyboard.nextDouble();
if (student.equals("M")) {
while (GPA >=0) {
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
}
if (student.equals("F")) {
while (GPA >=0) {
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
}
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
allAverage = mTotal + fTotal;
totalStudents = maleCount + femaleCount;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total MALE Average GPA: " + mAverage);
System.out.println("Total average: " + allAverage);
}
}
How to use loops and average in Java?
Well, pretty much as in the code in your question, I'd say. Just add a loop around the part that needs a loop, and figure out how you are going to end the looping.
The other problems that leap out at me are:
You seem to be accepting the input in a strange order.
You are calculating allAverage incorrectly. Just look at the code again. The problem should be obvious.
Actually, one of the difficulties with answering this Question is that it is not at all clear how the program as written is supposed to behave. And we can't infer that from what you've shown us. 'Cos what you've written obviously doesn't work ... from a usability perspective.
If you don't understand and can't explain the requirements properly, there is not much chance that you will be able to implement them correctly.
Fixed my code sorry for it being unclear.
import java.util.Scanner;
public class practice
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents, count = 0;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
do{
System.out.println("Enter GPA " + student);
GPA = keyboard.nextDouble();
if (student.equals("M"))
{
while (GPA >=0)
{
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
student = "F";
}
else if (student.equals("F"))
{
while (GPA >=0)
{
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
student = "M";
}
}
while (++count < 2);
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
totalStudents = maleCount + femaleCount;
allAverage = (mTotal + fTotal)/totalStudents;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total average: " + allAverage);
}

Categories