Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have tried making the integer into a string then splitting it like that but then I get an error because I have to multiply that number that is a string but obviously I can't. Here is my code.
import java.util.Scanner;
public class BMI {
public static void main(String[] args) {
Scanner BMI1 = new Scanner(System.in);
Scanner BMI2 = new Scanner(System.in);
Scanner BMI3 = new Scanner(System.in);
String name;
int weightPounds;
int heightFtInches;
int heightInches;
double weightKg;
double heightM;
System.out.print("Please enter your name (e.g. First Last): ");
name = BMI1.nextLine();
System.out.print("Please enter your weight in pounds (e.g. 150): ");
weightPounds = BMI2.nextInt();
System.out.print("Please enter your height in feet and inches (e.g. 6, 8): ");
heightFtInches = BMI3.nextLine();
String[] token = heightFtInches.split(",");
System.out.println();
System.out.println("Body Mass Index Calculator");
System.out.println("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#");
System.out.println();
weightKg = weightPounds / 2.2;
heightInches = heightFtInches * 12;
System.out.println("Name: " + name);
System.out.println("Weight in Kg: " + weightKg);
System.out.println("Height in meters: " + heightInches);
}
}
The nextInt method can be used to read the values for feet and weight. The method will use a space as a delimiter even if the values are entered simultaneously:
int feet = bmi1.nextInt();
int height = bmi1.nextInt();
Here you split the String and don't use it (well after you change heightFtInches to a String)
String[] token = heightFtInches.split(",");
What you want is to convert each into an int (Note this is assuming valid input)
int feet = Integer.parseInt(token[0]);
int inches = Integer.parseInt(token[1]);
Then you can mutliple feet and inches by the correct equatiob to get metric height
Adding to the previous two answers, you have declared heightFtInches as an int but I think it should be a String so you can use the split() method on it.
String[] token = heightFtInches.split(",");
System.out.println();
System.out.println("Body Mass Index Calculator");
System.out.println("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#");
System.out.println();
weightKg = weightPounds / 2.2;
heightInches = heightFtInches * 12;
Your height in feet is now in token[0] so I assume you are looking for something like this:
heightInches = (Integer.parseInt(token[0]) * 12) + Integer.parseInt(token[1]);
Related
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 1 year ago.
Improve this question
I am learning java and I want to create a command-line application that calculates exam percentages based on marks obtained. But the problem is I don't have the idea to set the range of marks obtained while the marks range is between 0 to 100.
Below is the code, I have tried: -
package com.company;
import java.util.*;
public class CbseCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of Physics");
float physics = sc.nextFloat();
System.out.println("Enter marks obtained of Chemistry");
float chemistry = sc.nextFloat();
System.out.println("Enter marks obtained of Math");
float math = sc.nextFloat();
System.out.println("Enter marks obtained of English");
float english = sc.nextFloat();
System.out.println("Enter marks obtained of Computer Science");
float computer = sc.nextFloat();
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained/total)*100;
System.out.println("The percentage obtained is: "+percentage);
sc.close();
}
}
It is not a good idea to try to get Scanner to do that1.
Instead, you should use Scanner to read an int and then test the result that it gives you to check that it is in the correct range. Something like this:
int number;
if (myScanner.hasNextInt()) {
number = myScanner.nextInt();
if (number < 0 || number > 100) {
// handle case where the number is out of range
}
} else {
// handle case where the input is not an integer
}
I will leave it to you to figure out how to map the above onto your application's requirements.
1 - The standard Scanner class doesn't provide a method that reads a number in a given range (and rejects numbers outside of that range). You could conceivably extend the Scanner class with this functionality, but it would be difficult. There are simpler solutions.
I would suggest you to write a function to get a valid input as below :-
public int getValidInput(Scanner in, int range) {
while (in.hasNext()) {
if (in.hasNextInt()) {
int val = in.nextInt();
if (val >= 0 && val < range) { // <-- from "0" to "range".
return val;
}
} else {
in.next();
}
}
return -1;
}
This function is ensuring that the input is given as an integer only and it lies in the range o to range. You can change it as per your requirement.
Consider this method:
static int getMark(String course){
int mark = 0;
boolean valid = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of " + course + ": ");
while(valid){
mark = sc.nextInt();
if(mark < 0 || mark > 100){
System.out.println("Mark must be between 0-100");
} else {
valid = true;
}
}
sc.close();
return mark;
}
This way you can get two birds with one stone, leaving the resulting code as this:
public static void main(String[] args){
int physics = getMark("Physics");
int chemistry = getMark("Chemistry");
int math = getMark("Math");
int english = getMark("English");
int computer = getMark("Computer Science");
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained / total) * 100;
System.out.println("The percentage obtained is: " + percentage);
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm working on a program that calculates the area of either a circle (C), square (S), or rectangle (R), depending on what letter the user inputs. I've tested it and it works fine; the code is below:
import java.util.Scanner;
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
String Shape = input.nextLine();
if (Shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
}
else if (Shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
}
else if (Shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
}
Now, what I want to do is add a loop to the program. For example, if the user inputs C for circle and puts in the number 22 for the radius, they'll get an answer, but I want the program to loop back to the beginning again so that it asks the user "What is your shape?...". Also, if the user types in X instead of C, S, or R, I want the program to quit, but I'm not sure how to add that in, either.
I know that I need to add a 'while' loop, but I was hoping someone could point me in the right direction, because I don't know where to insert that part of the code. Do I add the 'while' loop somewhere at the beginning of the code, after the last "if else" statement, or... Also, I'm not actually sure what to type. Should it be something like,
while (Shape == C, S, R) {
....?
Any help or pointers would be appreciated by any one in the coding community! I will continue to work on this code on my own as well.
I would go for the do, while
So, the program will always do something while the conditions that are set are being accomplished, so you want your program to look something like:
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean thisB = false; /*this is the guy who will tell the loop to stop the execution when the user inserts X*/
String shape;
do{
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
shape = input.next();
if(shape.equalsIgnoreCase("C") || shape.equalsIgnoreCase("S") || shape.equalsIgnoreCase("R")) {
if (shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
} else if (shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
} else if (shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
else if (shape.equalsIgnoreCase("X")) thisB = true;/*or in other words: stop*/
}
while(!thisB);
}
}
Things to consider:
1) Naming conventions, always start variable names with undercase using camelCase, in your example shape started with UpperCase
2) When in a while loop, use only next(), not nextLine() to pick up the values as the latter will duplicate the question in the System.out.Println.
3) The optimum way to do this is to put all your if clauses in a method and call it with the parameter from the Scanner input. Even better would be having a method per shape, as things can get hairy depending on requests
This question already has answers here:
Java: Literal percent sign in printf statement
(4 answers)
Closed 7 years ago.
How do I print a % sign in Java? I have tried "\%", which doesn't seem to work. Any ideas?
Bellow is the code corrected, as mentioned above you should use double % to escape %, i.e: %%
I have also added some new line characters to make the app look more neat.
import java.util.Scanner;
public class test
{
public static void main(String args[])
{
//A Simple Averaging Program
Scanner input = new Scanner(System.in);
//Declare variables:
double total = 0;
double counter = 0;
long mark;
double average;
int numOfPupils;
int totalMarks;
//Ask how many papers the teacher would like to average:
System.out.println("How many student's papers would you like to avarage?");
numOfPupils = input.nextInt();
//Ask how many marks were available to the student to earn:
System.out.println("How many marks were available to the student?");
totalMarks = input.nextInt();
//Repeat the amount of papers times:
while (counter < numOfPupils)
{
//Ask how many marks the student got:
System.out.printf("\nHow many marks did student number %s get? \nStudent %s scored: ", counter + 1, counter + 1);
mark = input.nextLong();
total += mark;
System.out.printf("Student %s scored: %s%%", counter + 1, ((100 / totalMarks) * mark));
counter++;
}
average = total / (counter);
System.out.printf("\nThe average was %s marks.", average);
input.close();
}
}
Off-topic but may need consideration, is that your code will fail in some cases, as you need to handle some invalid inputs.
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 8 years ago.
Improve this question
I am working on an assignment and it is working well so far. But several aspects aren't working. For starters, my counters for int total and int counter won't work. Also my if statements don't seem to be working. I have been scratching my head for several days now.
The assignment calls for a program to input the order number and will loop based on how many orders the customer has. It also calls for customer name, sign type(wood or plastic), the number of characters,and color of characters.
Some more information:
The base price for all signs is $20.
If sign is wood, add $10. If it is plastic add $5.
The first 5 letters/numbers are included in base price, and $2 for each additional character.
Black or white characters are included in base price, there is an additional $8 for colored letters.
If the total charge is more than $100 give 25% discount on total price.
Here is my code right now:
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
System.out.println("Enter your order number");
orderNumber = sc.nextInt();
counter=orderNumber;
counter--;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
do{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
if(signType == "wood") {
i+=10;
}
if(signType == "plastic") {
i+=5;
}
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
if(color != "white" || color != "black") {
i += 8;
}
total= i;
System.out.println("Total is: $" + total);
if( total > 100 ) {
total = (total * 0.25);
System.out.println("The total is " + total );
}
}
while(counter <= orderNumber);
}
}
I added comments to guide you through the changes I made. Also, remember to call the sc.NextLine() function after you get user input so that they can input something different next time (this is called 'flushing' the buffer).
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
//I changed the phrasing just because it is a little confusing
System.out.println("Enter your number of orders");
orderNumber = sc.nextInt();
counter = orderNumber;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
sc.nextLine();
//When you know how many times you want to repeat something (like when a user tells you how many) I prefer using a for-loop, a do while loop works as well though
for(int x=0; x<counter;x++)
{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
//When comparing Strings, there is a function that you can use to compare them rather than using '=='
// It is also good to use the 'equalsIgnoreCase()' function to be more user friendly and robust
if(signType.equalsIgnoreCase("wood")) {
i+=10;
}
if(signType.equalsIgnoreCase("plastic")) {
i+=5;
}
//Flush the buffer (I haven't tested if this is necessary or not, it is good practice though)
sc.nextLine();
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
//Same concept as above, the differene is the ! before the function to test if it is false or not
if(!color.equalsIgnoreCase("white") || !color.equalsIgnoreCase("black")) {
i += 8;
}
}
total = i;
//You will not want to print this out until the end due to the possibility of it being over $100
// System.out.println("Total is: $" + total);
if( total > 100 ) {
//Mathematically speaking, you are making your total a quarter of what the original is, rather than taking a quarter off. You want 75% rather than 25%
// total = (total * 0.25);
total = (total * 0.75);
}
System.out.println("Total is: $" + total);
}
}
You should set counter to the correct starting value (which is presumably 1 in your case):
orderNumber = sc.nextInt();
counter=1;
//counter=orderNumber;
//counter--;
Then at the end of the loop, you should increment your counter:
do{
//code
counter++;
}
while(counter <= orderNumber);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am having two problems with my code.
First: I can't seem to add "$" in the right location (I cant get it to look like $10.00 only 10.00$)
Second: Adding a Scanner class ends up with the program "running" but nothing happening. (if I set gross with a number it runs fine but not with using a scanner class)
import java.util.Scanner;
public class Payment
{
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
//double gross = Keyboard.nextDouble(); will not work
//double gross = 8000; will work
double fed = (0.15 * gross);
double state = (0.035 * gross);
double soc = (0.0575 * gross);
double med = (0.0275 * gross);
double pen = (0.05 * gross);
double hea = 75;
double net = (gross - (fed + state + soc + med + pen + hea));
System.out.println("Paycheck calculation by employee\n");
System.out.printf("Gross Amount:%28.2f%n", gross);
System.out.printf("Federal Tax:%29.2f%n", fed);
System.out.printf("State Tax:%31.2f%n", state);
System.out.printf("Social Security Tax:%21.2f%n", soc);
System.out.printf("Medicare/Medicaid Tax:%19.2f%n", med);
System.out.printf("Pension Plan %28.2f%n", pen);
System.out.printf("Health Insurance %24.2f%n%n", hea);
System.out.printf("Net Pay:%33.2f", net);
}
}
You probably want to print out an input prompt. Regarding currency formatting, you could use the DecimalFormat class.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Payment
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter gross amount: ");
double gross = keyboard.nextDouble();
//double gross = 800; //will work
double fed = (0.15 * gross);
double state = (0.035 * gross);
double soc = (0.0575 * gross);
double med = (0.0275 * gross);
double pen = (0.05 * gross);
double hea = 75;
double net = (gross - (fed + state + soc + med + pen + hea));
DecimalFormat currency = new DecimalFormat("$0.00");
System.out.println("Paycheck calculation by employee\n");
System.out.printf("Gross Amount: %27s%n", currency.format(gross));
System.out.printf("Federal Tax:%29s%n", currency.format(fed));
System.out.printf("State Tax:%31s%n", currency.format(state));
System.out.printf("Social Security Tax:%21s%n", currency.format(soc));
System.out.printf("Medicare/Medicaid Tax:%19s%n", currency.format(med));
System.out.printf("Pension Plan %28s%n", currency.format(pen));
System.out.printf("Health Insurance %24s%n%n", currency.format(hea));
System.out.printf("Net Pay:%33s", currency.format(net));
keyboard.close();
}
}
Answering your first question, you could it like this:
System.out.printf("Gross Amount %28c%.2f%n", '$', gross);
Your second question, i think your problem is the Locale. Depending on your Locale, the input format of a Double, in this case, may be different. You could do:
keyboard.useLocale(Locale.US);
This way, the input of a Double will be the integer part separated by a . from the decimal part. 8000 and 5.5 are valid examples of a Double input.