scanner skips double type numbers - java

Hello I'm new in java and as i was making a program practicing input/output methods I came to this error:
When I input a int value the program works well, but when I input a double value it shows me this:
Here is my code:
import java.util.Scanner;
public class InpOutp
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in); // creates a scanner
System.out.print("Enter price of a six-pack beer: ");
double packPrice = in.nextDouble();
System.out.print("Give the ml of a can: ");
double canMl = in.nextDouble();
final double CANS_PER_PACK = 6;
double packMl = canMl * CANS_PER_PACK;
// find the price per ml of a pack
double pricePerMl = packPrice / packMl;
System.out.printf("Price per ml: %8.3f", pricePerMl);
System.out.println();
}
}

The problem is the separator. If you wish to use period try this
Scanner in = new Scanner(System.in).useLocale(Locale.US);
EDIT:
Also it is worth to mention, you should use in.nextLine();
after every nextInt() or nextDouble() otherwise you will encoder problems with nextLine when entering text.
Try this
System.out.print("Enter price of a six-pack beer: ");
double packPrice = in.nextDouble();
System.out.println("this will be skipped" + in.nextLine());
System.out.print("Give the ml of a can: ");
double canMl = in.nextDouble();
in.nextLine();
System.out.print("And now you can type: ");
System.out.println(in.nextLine());

The fault was that I was typing the values with . (5.4) and I should type them with , (5,4).

Related

Graphing a function of an input output exchange

Is there a way to graph the values outputted by the following code in a separate class.
import java.util.Scanner;
public class scannerNumber {
public static void main(String []args) {
Scanner originalNumber = new Scanner(System.in); // number for input
System.out.println("Enter a number: "); // asks for input
int firstNumber = originalNumber.nextInt();
double secondNumber = Math.abs((firstNumber*Math.sin(firstNumber)));
System.out.println("Your new number is: " + secondNumber);
originalNumber.close();
}
}
Scanner originalNumber = new Scanner(System.in); // number for input
ArrayList<Double> results = new ArrayList<Double>;// array for results
System.out.println("Enter a number: "); // asks for input
int firstNumber = originalNumber.nextInt();
for(int i=0; i<=firstNumber; i++){
double secondNumber = Math.abs((firstNumber*Math.sin(firstNumber)));
results.add(secondNumber);//add results to an array
}
for(int k:results)
System.out.print(k+" ");
originalNumber.close();
this will create an array that contains y values while x is between [0,firstNumber]
note that this not a complete answer for your question. you should start with basics.
complete tutorial for function drawing in java
. you can use this tutorial but first look at gui for java.

Simple Java way to input decimal and round to nearest integer

I am using the Java SDK to compile. Need I say, I am a beginner.
Here is the code I tried to use to "Ask user to input decimal and code should output an integer. (round to nearest integer)
import java.util.*;
public class readDecimal {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println(“Please enter a decimal number:“);
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
“ rounded to the nearest integer is “ + intNumber);
}
}
What am I doing wrong? I saw the other posts however they seem much to complicated for a beginner. Can you please help?
Thank you,
Diane
Your quotation marks are incorrect; they are unicode for some reason. Replace all the quotations by manual typing them in, in you System.out.println statements.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println("Please enter a decimal number:");
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
" rounded to the nearest integer is " + intNumber);
}
You can round double numbers using Math.round method.
import java.util.*;
public class RoundingDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double num1;
double num2;
System.out.print("Please enter a decimal number: ");
num1 = sc.nextDouble();
num2 = Math.round(num1);
System.out.println(" Rounded to the nearest integer is " + num2);
}
}

why does my scanner(system.in) run twice

I am new to java, been self teaching for the last week. I cannot find the reason why the if else statement runs twice. here is the whole code, I know is simple but still trying to learn.
package tickets;
import java.util.Scanner;
public class tickets {
public static void main(String[] args) {
//program designed to ask how many visitors
//are in a party of people and work out
//the total cost of the entry tickets.
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
//adding code that would give a percentage discount for
//4 adults or more
{
if ( adult1.nextInt() >= 4
{
double adult2 =( adult1.nextInt() * percentage);
}else {
double adult2 = (adult * adult1.nextInt());
System.out.println("please enter the amount of consessions");
Scanner consession1 = new Scanner (System.in);
double consession2 = (consession *consession1.nextInt());
System.out.println("please enter the amount of children");
Scanner child1 = new Scanner (System.in);
double child2 = (child * child1.nextInt());
System.out.println( "total"+" " + (adult2 +consession2 + child2) );
System.out.println("hope you enjoy your visit today!");
//woop woop it works!!!!!!!!!!
}
}
}
}
The reason why your program asked for two inputs was because adult1 is the name of your scanner and in your if statement the condition was if the user input is >= 4 then take an Integer input again from the user and multiply that with percentage and store it in adult2, instead this should be done as follows
public static void main(String[] args)
{
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
double adult2 = 0.0 // you dont need to redeclare below
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
// remove this unneccessary bracket {
int num = adult1.nextInt();
if ( num >= 4)
{
adult2 =( num * percentage);
}
else
{
adult2 = (adult * num);
}
System.out.println("Adult2 is " + adult2);
}
Store the int from the scanner and use that value in your ifs and calculations. You're calling nextInt() more than once and each time you get another int.
After you enter the if or else you will wait for more input of the integer type stopping the program.

Using the Math Class to get a powered number and display the results

I get this as a result when i type 9 as input.
Enter a Base Number:
9
Enter a Raised Number:
9
9.0 raised 9.0 times equals 0.0.
0.0 rounded equals 0
End of Program.
to me it seems like the calcPower method might be where i'm having issues but it seems like it's correct.
it looks to me like raisedResult is not being populated after the calcPower method.
can someone please walk me through the steps of where i'm making my mistake.
import java.util.Scanner; // import the scanner utility
public class Chap08
{
//----------------------------------------------Main--------------------------------------------------------------------//
public static void main(String[] args)
{
getInput();
System.out.println();
System.out.println("End of Program.");
}
//----------------------------------------------getInput--------------------------------------------------------------------//
public static void getInput()
{
double baseNumber = 0.0, raisedNumber = 0.0 , raisedResult = 0.0;
Scanner keyBoard = new Scanner(System.in);
System.out.println("Enter a Base Number:");
baseNumber = keyBoard.nextDouble();
System.out.println("Enter a Raised Number:");
raisedNumber = keyBoard.nextDouble();
calcPower(baseNumber,raisedNumber,raisedResult);
dspRaisedNumber(baseNumber,raisedNumber,raisedResult);
keyBoard.close(); // close keyboard scanner
}
//----------------------------------------------calcPower--------------------------------------------------------------------//
public static double calcPower(double baseNumber,double raisedNumber,double raisedResult)
{
raisedResult = Math.pow (baseNumber,raisedNumber);
return raisedResult;
}
//----------------------------------------------dspRaisedNumber--------------------------------------------------------------------//
public static void dspRaisedNumber(double baseNumber,double raisedNumber, double raisedResult)
{
System.out.println(baseNumber + " raised " + raisedNumber + " times equals " + raisedResult + ".");
System.out.println(baseNumber*raisedResult + " rounded equals " + Math.round(baseNumber*raisedResult* 1.0 / 1.0));
}
}
Your calcPower() method returns the value of the computation, but the main method doesn't do anything with the returned value. BTW, the third argument of calcPower() is useless.
You should have, in the main method:
raisedResult = calcPower(baseNumber, raisedNumber);
Think of arguments as inputs to a method, and of the returned value as the output of the method. raisedResult is an output, and thus doesn't have to be passed as argument. It has to be initialized with the output of the method though.
You should also introduce variables only when you need them, and avoid declaring and initializing with useless values at the beginning:
Scanner keyBoard = new Scanner(System.in);
System.out.println("Enter a Base Number:");
double baseNumber = keyBoard.nextDouble();
System.out.println("Enter a Raised Number:");
double raisedNumber = keyBoard.nextDouble();
double raisedResult = calcPower(baseNumber, raisedNumber);
dspRaisedNumber(baseNumber, raisedNumber, raisedResult);
keyBoard.close(); // close keyboard scanner
While you're at it, also avoid using cryptic abbreviations in method names. computePower() and displayRaiseNumber() would be better names for your methods.
Here's your problem:
raisedNumber = keyBoard.nextDouble();
calcPower(baseNumber,raisedNumber,raisedResult);
calcPower returns a value, it does not return the result in the raisedResult value passed in, as java is a pass by value language. Remove raisedResult from the args for calcpower, and use the returned value, like this:
raisedNumber = keyBoard.nextDouble();
raisedResult = calcPower(baseNumber,raisedNumber);
In the calcPower method call, the result is returned. You set the result to a value using the equals sign. In your calcPower method, you're returning a double. I set the result to a double and removed the parameter from the method call where you were expecting the return value.
public static void getInput()
{
double baseNumber = 0.0, raisedNumber = 0.0 , raisedResult = 0.0;
Scanner keyBoard = new Scanner(System.in);
System.out.println("Enter a Base Number:");
baseNumber = keyBoard.nextDouble();
System.out.println("Enter a Raised Number:");
raisedNumber = keyBoard.nextDouble();
double raisedResult = calcPower(baseNumber,raisedNumber);
dspRaisedNumber(baseNumber,raisedNumber,raisedResult);
keyBoard.close(); // close keyboard scanner
}

While statement loop error

Hey I have been having an issue with this code because it has not been looping when I input a value for the String repeat. I am unable to understand whatever it is that I'm doing wrong.
import java.util.Scanner;
public class MpgCalculator
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the MPG and CPM Calculator!");
double startOd, endOd, gallons, cost, mpg, cpm;
String repeat = "yes";
while(repeat.equals("yes")||repeat.equals("Yes")||repeat.equals("y")||repeat.equals("Y"))
{
System.out.println("Please Enter:");
System.out.print("\tYour Starting Odometer Reading: ");
startOd = sc.nextDouble();
System.out.print("\tYour Ending Odometer Reading: ");
endOd = sc.nextDouble();
System.out.print("\tThe Amount of Gallons Used: ");
gallons = sc.nextDouble();
System.out.print("\tThe Cost-per-Gallon That You Spent: ");
cost = sc.nextDouble();
mpg = getMpg(startOd, endOd, gallons);
cpm = getCpm(mpg, cost);
System.out.println("\nYour Miles-per-Gallon is " + mpg + ".");
System.out.println("Your Cost-per-Mile is " + cpm + ".");
System.out.print("Do it again? ");
repeat = sc.nextLine();
}
}
public static double getMpg(double startOd, double endOd, double gallons)
{
double mpg;
mpg = (endOd - startOd) / gallons;
return mpg;
}
public static double getCpm(double mpg, double cost)
{
double cpm;
cpm = cost / mpg;
return cpm;
}
}
Change repeat = sc.nextLine(); to repeat = sc.next(); If you don't need the extra line. It only gets it if you are an the next line, which you are not, so it terminates the program.
The previous use of your Scanner prior to calling repeat = sc.nextLine(); in your while loop is nextDouble. Calling nextDouble does not consume the newline character in the stream from entering the cost per gallon.
Consume the newline character before asking to repeat:
System.out.print("Do it again? ");
String dummy = sc.nextLine(); // Add this line.
repeat = sc.nextLine();
use
repeat = sc.next();
instead of
repeat = sc.nextLine();

Categories