Incrementing with a fraction based on user input - java

I'm having trouble i need to take a user input and increment it by 1/10 starting at 0 so if the user enters a 5.2 i need to to go through 0.1 0.2 0.3 etc display each and stop at 5.2 until the method is called again and a new input is entered here is what i have but it just runs through up until 10 i understand why it does this just not enough to be able to fix this any help would be appreciated
import java.util.Scanner;
public class SpeedChange {
public double startSpeed;
public double newSpeed;
public void changeUserSpeed(){
Scanner sc = new Scanner (System.in);
System.out.println("How fast would you like to go between 1-10 mph?");
double newSpeed = sc.nextDouble();
for(newSpeed = sc.nextDouble(); newSpeed <= 10.00; newSpeed+=.1 ){
System.out.println(newSpeed);
}
}
}

You need to change your loop content.Since your newSpeed has been specified by the user,you don't need to alter it.You simply need to create a new double variable,say Speed,which will increment in the limit of 0.1 at each iteration and keep running until your Speed equals newSpeed.
for(double Speed=0;Speed<=newSpeed;Speed+=0.1 ){
System.out.println(Speed); }
I hope this clears and solves your doubt!

Your code should instead be
for(double speed=0; speed <= newSpeed; speed+=.1 ){
System.out.println(speed);
}
P.S: double/float is not suitable for this kind of use. Use BigDecimal class to do this.
For details, see http://javarevisited.blogspot.in/2012/02/java-mistake-1-using-float-and-double.html?m=1

Related

Can someone help analyse my java code on an averaging program?

Hi so I've started learning java online for two weeks now, but as I watched those tutorials, I felt the only way I'd actually grasp that information was to practice it. My other programs worked great, but just when I decided to do something spectacular (for me only of course; a java expert would find creating this program mind-numbing), something went terribly wrong. I'd really appreciate if you could take a look at my code below of an averaging program that could average any amount of numbers you want, and tell me what in the world I did wrong.
UPDATE: Eclipse just outputs a random number after typing in just one number and then shuts down the program.
Here is a snapshot where I type in the console to average 6 numbers and then start with the number 7, but for some reason, when I hit enter again, it outputs 8.
package justpracticing;
import java.util.*;
public class average{
int grade = 0;
int average;
Scanner notoaverage = new Scanner(System.in);
System.out.println("Please enter the amount of numbers you'd like the average of! ");
final int totalaverage = notoaverage.nextInt();
Scanner averagingno = new Scanner(System.in);
System.out.println("Start typing in the " + totalaverage + " numbers");
int numbers = averagingno.nextInt();
int counter = 0;
public void averagingnumbers(){
while(counter<=totalaverage){
grade+=numbers;
++counter;
}
}
public void printStatement(){
average = grade/totalaverage;
System.out.println(average);
}
}
It seems that you have created an average Object in another class, and are calling the methods given from a main class.
I don't know what exactly you're having trouble with, but one problem is here:
average = grade/totalaverage;
These 2 variables that you are dividing are both integers. That means that the result will also be an integer. This is called truncation. What you want to do is first convert at least one of the integers to a double:
... = (grade * 1.0) / totalaverage;
You also want your average variable to be a double instead of an integer so that it can be a lot more accurate.

Mind helping a newcomer who hit their first speed bump?

I just started learning how to program in Java. Everything was going well so far.. That was until I came across this "bonus" question/problem our teacher gave us to solve as an additional "challenge".
Please click here to view the Question and the Sample input/output (it's an image file)
Note that I'm not allowed to use anything that wasn't taught or discussed in class. So, things like arrays, method overloading, parsing arrays to methods, parseInt, etc. gets ruled out.
Here's what I was able to come up with, so far:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int N; // number of lines of input
double length1, length2, length3; // the 3 lengths
double perimeter; // you get this by adding the 3 lengths
double minperimeter=0; // dummy value
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of triangles you have:");
N = input.nextInt();
System.out.println("Insert the lengths of the sides of these " +
"triangles (3 real numbers per line):");
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
minperimeter = Math.min(perimeter,Math.min(perimeter,perimeter));
}
System.out.printf("The minimum perimeter is %.1f%n", minperimeter);
}
}
My 2 main problems are:
1) The program only stores and works with the 'last' input.
The ones before it get replaced with this one. [update: solved this problem]
2) How do I print the "triangle number" in the final output? [update: solved this problem, too]
So, can anyone please help me come up with a solution that requires only the very basic learnings of Java? If it helps, this is the book we're using. Currently at Chapter 4. But we did learn about Math Class (which is in Chapter 5).
Update: Thank you so much for your replies, everyone! I was able to come up with a solution that does exactly what was asked in my question.
Math.min(perimeter,perimeter) will always give you perimeter. You probably wanted to do Math.min(perimeter,minPerimeter)
Since it's a programming assignment is best if I don't give you the full solution to your second question, but your hint is, in the counter parameter of your for loop. Save that when you update minperimeter, so that you know in which iteration of the loop you found the minimum.
Also, initialise your minPerimeter to 10000 or higher. If you start at 0, Math.Min will never be lower than that.
Change your for loop as:
double minperimeter=-1;
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
if(minperimeter == -1){
minperimeter = perimeter;
} else{
Math.min(perimeter,minperimeter);
}
}
You have to store the smaller perimeter in your variable perimeter.
The hint from your task tells you, that any given perimeter is smaller than 1000. Thus initiate the perimeter to 1000.
In your for-loop then you have to store the smaller perimeter:
perimeter = Math.min(perimeter, length1 + length2 + length3)
if the sum of the edges is smaller than the current perimeter, the smaller value will be stored.
Please note that according to your given task, you have to input 3 doubles within one line.
Alternative Solution
Make an ArrayList and add all perimeter to that list and then find the minimum value from that list.
List<Double> perimeter = new ArrayList<>();
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter.add(length1 + length2 + length3);
}
System.out.printf("The minimum perimeter is %.1f%n", Collections.min(perimeter));

The below code wont execute with some inputs

Sorry for such a basic level question guys. But I'm starter in programming. Not a computers guy. So kindly help me.
In this code when I give input 1000000000, 1000000000, 999999999 the answer should be 4. But my answer is 1. I expect the if statement to execute but it is not executing here.
if you take m*n as a room and "a" as the side as a square tile. Then I want to count MINIMUM no. of tiles required to fill the floor of room. tiles may cover a bit more area but should not leave the room empty. this is my objective. It's working with inputs like 6,6,4 or 15,20,13 etc.
Now its working guys. I had posted the correct code with those minor changes below.
import java.util.Scanner;
public class TheatreSquare {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
float m=input.nextFloat();
float n=input.nextFloat();
float a=input.nextFloat();
long i=(int)(m/a);
long j=(int)(n/a);
if((a*a*i*j)<m*n){
if(a*i<m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j<n){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
}
System.out.println((double)(i*j));
}
}
Your floats are overflowing when you multiply them. Defining m, n and a as doubles will solve the issue:
double m = input.nextDouble();
double n = input.nextDouble();
double a = input.nextDouble();
The int conversion loses precision.
Here in this case, a*a*i*j is equal to m*n Hence the if loop will not execute. Also a*i is equal to m and a*j is equal to n.
Hence i isi and j is 1, so i*j is 1.
You need to allow it to go if it is equal too.
Replace
if((a*a*i*j)<m*n){
if(a*i<m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j<n){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
}
with
if((a*a*i*j) <= m*n){
System.out.println("Entered if block");
if(a*i <= m){
//to check weather it is entering if()
System.out.println("true");
i+=1;
}
if(a*j <= n ){
System.out.println("false");
//to check weather it is entering if()
j+=1;
}
System.out.println("i is:"+ i +"j is:"+j);
}
thankyou #Mureinik, #Uma Lakshmi Kanth, #Diego Martinoia for helping to solve this. All your answers contributed to solve my question. this is working now. as #Mureinik said my floats are overflowing( though I dont know the meaning). I used Double instead of float and that's it. its working. :-)
import java.util.Scanner;
public class TheatreSquare {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
double m=input.nextDouble();
double n=input.nextDouble();
double a=input.nextDouble();
long i=(long)(m/a);
long j=(long)(n/a);
if((a*a*i*j) <m*n){
if(a*i < m){
//to check weather it is entering if()
i+=1;
}
if(a*j < n ){
//to check weather it is entering if()
j+=1;
}
}
System.out.println((long)(i*j));
}
}
The reason for your behavior is that you are reading numbers as floats. Floats have limited precision, so your m n and a are the same value (at runtime). Reading them as long (and getting rid of all the decimal stuff) should help. But, as mentioned in the comment, we don't know what you wanted to achieve!
--- EDIT DUE TO NEW INFO ---
You have to cover an area of m times n square meters. You have an unit of computation of 1 tile, i.e. a times a square meters (both assumed to be decimal).
Assuming you can cut your tile with good-enough precision, your result will be:
Math.ceiling((m*n) / (a*a));
i.e., either your area is an exact multiple of your tiles (and you can always cut them in rectangles to match the shape of the room), or you'll have some "spare" space to fill in, thus you will need 1 more tile, a part of which you'll use to cover the remaining space, and a part of which you'll throw away.

My variables won't count because the compiler thinks they may not be spawned

I'm making a program for doing sin, cos, tan function and am in progress
However, because I used an if-else statement, it thinks that my variable (stepc) may not be initialized.
Since trig graphs are repetitive, I'm trying to make all graphs under the range of 0 to 360.
import java.util.Scanner;
public class Trigonometry
{
public static void main(String[]args)
{
double answer;
double x;
double stepa;
double stepb;
double stepc;
double stepd;
Scanner scanner = new Scanner (System.in);
System.out.print("Enter number");
x = scanner.nextDouble();
stepa = Math.abs(x);
stepb = stepa / 360 ;
if(stepb > 1) // <-- my functions for step c
{
while (stepb>1)
{
stepc = stepb - 1;
}
}
else
{
stepc=stepb;
}
stepd=stepc*360; // <-- won't consider step c
System.out.println( stepc );
}
}
----jGRASP exec: javac -g Trigonometry.javaenter code here
Trigonometry.java:34: variable stepc might not have been initialized
stepd=stepc*360;
^
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Initialize stepc to some default value when you define it.
You have to assign a value to it before you can use it.
Have you tried giving values to your step[abcd] variables when you initialize them?
Also, if stepb > 1, your code, as written, will never terminate. Do you see why?
As the others have noted, use:
double answer;
double x;
double stepa;
double stepb;
double stepc = 0;
double stepd;
edit: no harm in assigning values to the other variables too.
also, be aware that this loop is probably running infinitely:
while (stepb>1)
{
stepc = stepb - 1;
}

My Newbie Code isn't subtracting both variables

I'm stupid.
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double withdraw = scanner.nextDouble();
double balance = scanner.nextDouble();
int withdraw = 0; int balance;
if (withdraw % 5 == 0 && withdraw<(balance-.5)) {
balance = balance - (withdraw + .5);
System.out.println(balance);
}
else {
System.out.println(balance);
}}}
I'm trying to make it so that the Balance is being subtracted by the Withdrawal amount while incurring a $.50 charge. Unfortunately, it keeps only subtracting the $.50 without subtracting withdraw. Thanks in advance.
FIXED CODE
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double withdraw = scanner.nextDouble();
double balance = scanner.nextDouble();
if (withdraw % 5 == 0 && withdraw<(balance-.5)) {
balance -= (withdraw + .5);
System.out.println(balance);
}
else {
System.out.println(balance);
}}}
Here is the algorithm https://stackoverflow.com/a/14387552/1083704
You have the same problem - a bug in the complex expression, which includes using unknown types. And you must do the same thing to debug your program -- simplify the oneliner into multiple simple expressions, using intermediate variables. Then you can step-by-step debug your code and observe those intermediate values. Being a programmer means being a hacker and you won't be a hacker without learning debugging.
where are you setting the withdraw variable? I'd look there, it sounds like you're adding .5 to a variable that hasn't been assigned a value greater than 0. A real easy way to test in more complex code would be to set withdraw in your code to say a value of 5 right before using it in your balance equation, that way you can tell if the problem is with your equation, or the withdraw variable, the equation looks solid though. Also, you can do
balance -= (withdraw + .5)
It is fairly hard to debug code when given so little information; but my best guess would be an initialization bug - where withdraw has not been initialized correctly and is just at what I'd assume to be its default value, 0
But to be sure, we'd need to know what withdraw is equal to before your print statement.
Could you add a print statement before adding up the balance like so:
System.out.println(withdraw);
balance -= (withdraw + .5);
System.out.println(balance);
And then see whether withdraw is > 0 at runtime? And if not; check that it gets set to your withdraw value before computing the balance.
Even better would be to post your full code snippet, so we can see ourselves I guess.
N.B. a -= b is shorthand for a = a - b

Categories