The Student Union is organising a student trip and they are determining how many cars are required.
Prompt the user to enter the total number of students going on the trip.
Then determine how many cars are required (5 to a car) and how many students are left without transport.
import java.util.Scanner;
class P2Trip
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
int students;
int space = 5;
int sum;
System.out.println("How many students are going today?: ");
students = input.nextInt();
sum =(students / space);
System.out.println("Ammount of cars needed: " + sum);
}
}//code works fine, but im not sure how to get a remainder of students without a lift.
From your comment, it looks like you just need help with who will be left without a car. You need to use modular division (some people call it remainder) with the percent sign (%). Here is the line of code you are missing:
System.out.println("Amount of people without a car: "+students%sum);
The full code for the program is:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) [
Scanner s=new Scanner(System.in);
int carCapacity=5;
System.out.println("How many students?");
int students=s.nextInt();
int cars=students/carCapacity;
int leftOver=students%carCapacity;
System.out.println("Cars needed: "+cars);
System.out.println("Students left over: "+leftOver);
}
}
Have a look at the remainder/modulo operator here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
In my view, there are two corrections you can do in your program:
sum = (student/space);
int leftstudent;`
leftstudent=(students%space);
System.out.println("left students without transport are " +leftstudent);
You might want to check the modular division operator in Java.
Division / Divisor = coefficient
Division % Divisor = remainder
To find the remainder of number students for example you will have to use "%".
Related
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.
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 program I'm trying to write needs to input a user-defined number of Int values and produce the product of those values, and then determine all of the factors of that product. The values will be input through a Do-While Loop until the user enters a negative number, and then all the positive numbers will be multiplied together to form a product in the form of a Double. I'm fairly certain I can figure out how to get the factors of the product, but when it comes to finding the actual product I'm completely at a loss. Here is the code I've written so far, minus my failed attempts at producing a product.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int Value;
double Product;
do
{
System.out.print("Value: ");
Value = in.nextInt();
}
while (Value>=0);
}
This is all I've been able to figure out, looping the Value prompt until a negative Int is entered. As far as getting the product I've tried If-Statements both inside and outside the loop, but either my code is wrong or my statements are wrong, or more likely I'm just trying the wrong method. I'm not asking anybody to write the code for me, but if somebody could point me in the right direction I would very much appreciate it.
What tips would you suggest to determine the product from an unknown number of user-difined values?
You should set product variable to be initially equal to 1 and multiply the value of product by the input number each time the user writes a number.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int value;
double product=1;
do
{
System.out.print("Value: ");
value = in.nextInt();
product *= value //product= product * value;
}
while (value>=0);
System.out.println("Product is: "+product);
}
I just wrote a lab that is supposed to flip two coins 500 times and count how many times heads and tails were flipped and is supposed to calculate the percentage to the tenth. I remember the template for Decimal formatting, but forgot how to use it. Can somebody help? My program is as follows:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Lab97a
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
DecimalFormat accuracy=new DecimalFormat("0.0");
Dice coin;
int numCoin;
int numHeads;
int numTails;
int count;
double percentageHeads;
double percentageTails;
coin=new Dice(2);
numHeads=0;
numTails=0;
System.out.println("A coin is tossed 500 times. The results are asfollows: ");
for (count=1;count<=500;count=count+1)
{
numCoin=coin.roll();
if (numCoin==1)
{
numHeads+=1;
}
if (numCoin==2)
{
numTails+=1;
}
}
percentageHeads=numHeads/5;
percentageTails=numTails/5;
System.out.println("Heads was flipped "+numHeads+" times,
"+percentageHeads+"%.");
System.out.println("Tails was flipped "+numTails+" times, "+percentageTails+"%");
}
}
It looks like you just need to format the accuracy with e.g. accuracy.format(percentageHeads). See NumberFormat.format(double) that DecimalFormat extends.
You can use the String.format method for this, as described here:
System.out.println(String.format("Heads was flipped %d times, %.2f %%"), numHeads,percentageHeads);
I'm using this basic and crude code below for calculating prime numbers then exporting them to a text file:
import java.util.Scanner;
import java.io.*;
public class primeGenerator{
public static void main(String[] args)throws Exception {
Scanner kb = new Scanner(System.in);
String prime;
long num = kb.nextLong();
long i;
long z=0;
while(z==0){
for (i=2; i < num ;i++ ){
long n = num%i;
if (n==0){
break;
}
}
if(i == num){
writer(num);
}
num=num+2;
}
}
public static void writer(long num) throws Exception {
FileWriter writer = new FileWriter("prime.txt",true);
String prime= ""+ num;
writer.write(prime);
writer.write(" ");
writer.flush();
writer.close();
}
}
I would like to find primes beyond the Primative long's range and apparently big integer is the way to go about it. So how do i alter my code to do so?
Do you really need this? Having numbers bigger than can be handled by long means you want to test numbers bigger than 9223372036854775807. If your for-loop can test a hundred million divisions per second, it will still take it 2923 years to determine if that number is prime - and longer for larger numbers, of course.
A common optimization is to only test divisions up to sqrt(num). If you haven't found anything then, the number is prime.
Well, use BigInteger wherever you've currently got long. Instead of using % you'll use mod, instead of incrementing you'll use i = i.add(BigInteger.ONE), instead of == 0 you'll use equals(BigInteger.ZERO) etc.
Use Scanner.nextBigInteger instead of Scanner.nextLong, too.
Given that this looks like homework of some description (possibly self-set, of course) I won't write out the whole code for you - but if you have specific problems, feel free to ask.