I have a question with this program I wrote for class. It is functioning exactly the way I need it to except for one minor detail. My while-loop is adding an extra "+" on the end of my print statement.
public class Fractions
{
public static void main (String[] args)
{
//-----declare variables-----
int numOfFractions = 0,
numerator = 0;
double total = 0;
DecimalFormat df1 = new DecimalFormat("#0.##");
Scanner stdIn = new Scanner(System.in);
//----Welcome MSG------
System.out.println("");
System.out.println("\t* * * Welcome to Fractions * * * ");
System.out.println("");
//-----get numOfFractions------
System.out.print("Enter the number of fractions: ");
numOfFractions = stdIn.nextInt();
//----begin loop-------
numerator = 1;
while(numerator <= numOfFractions)
{
while(numOfFractions > 0)
{
System.out.print("" + numerator + "/" + numOfFractions + " " + "+" + " ");
total += (double)numerator / numOfFractions;
numOfFractions--;
numerator++;
}
}
System.out.println("");
System.out.println("");
System.out.print("The total: " + df1.format(total));
System.out.println("");
System.out.println("\nThanks for using the Fraction Adder program\n");
} // end main
} // end pgm
Here is a picture of my output
There are many ways to do this a simplest approach can be by simply using if/else condition, try this:
public class Fractions
{
public static void main(String[] args)
{
// -----declare variables-----
int numOfFractions = 0, numerator = 0;
double total = 0;
DecimalFormat df1 = new DecimalFormat("#0.##");
Scanner stdIn = new Scanner(System.in);
// ----Welcome MSG------
System.out.println("");
System.out.println("\t* * * Welcome to Fractions * * * ");
System.out.println("");
// -----get numOfFractions------
System.out.print("Enter the number of fractions: ");
numOfFractions = stdIn.nextInt();
// ----begin loop-------
numerator = 1;
while (numerator <= numOfFractions)
{
while (numOfFractions > 0)
{
if (numOfFractions > 1)
{
System.out.print("" + numerator + "/" + numOfFractions + " " + "+" + " ");
}
else
{
System.out.print("" + numerator + "/" + numOfFractions + " ");
}
total += (double) numerator / numOfFractions;
numOfFractions--;
numerator++;
}
}
System.out.println("");
System.out.println("");
System.out.print("The total: " + df1.format(total));
System.out.println("");
System.out.println("\nThanks for using the Fraction Adder program\n");
} // end main
} // end pgm
Usually you check if the element you want to print is the last (or the first) element and then add the separator, or not. Here's a simplified example, since I think it's easier to understand what's happening:
String[] arr = new String[] { "a", "b", "c" };
for (int i = 0; i < arr.length; i++) {
if (i > 0)
System.out.print("+");
System.out.print(arr[i]);
}
We print the separator + only for elements at index > 0 and before the actual value. You could also reverse this and print the separator for all elements at index < arr.length - 1 after the actual value.
When using Java 8 you could also use StringJoiner and print the contents after the loop, like this:
String[] arr = new String[] { "a", "b", "c" };
StringJoiner joiner = new StringJoiner("+");
for (int i = 0; i < arr.length; i++)
joiner.add(arr[i]);
In your code this would look something like this:
// ...
StringJoiner joiner = new StringJoiner(" + ");
while (numerator <= numOfFractions) {
while (numOfFractions > 0) {
joiner.add(numerator + "/" + numOfFractions);
total += (double) numerator / numOfFractions;
numOfFractions--;
numerator++;
}
}
System.out.println(joiner.toString());
// ...
Related
I need to print the common divisors between two positive integers that were entered. They need to be printed in ascending order. If they are relatively prime, "1" needs to be printed. The code I have here is nowhere near correct. I'm really confused on how to use the loops properly while keeping it in ascending order.
Sample input:
Integer a: 8 Integer b: 12
Sample Output:
Common divisors of 8 and 12:
1
2
4
8 and 12 are not relatively prime.
Alternate Input:
Integer a: 8 Integer b: 9
Common divisors of 8 and 9:
1
8 and 9 are relatively prime.
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1 = scnr.nextInt();
int num2 = scnr.nextInt();
System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
int div1 = 0;
int div2 = 0;
int same = 0;
for (int i=1;i<=num1;i++) {
while (div1 <= num1) {
div1 = num1/i;
}
while (div2 <= num2) {
div2 = num2/i;
}
if (div1 == div2) {
div1 += same;
System.out.println(same);
System.out.println(num1 + " and " + num2 + " are not relatively prime.");
}
if (div1 != div2) {
System.out.println(1);
System.out.println(num1 + " and " + num2 + " are relatively prime.");
}
}
}
}
You can try something simple like the below:
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1 = scnr.nextInt();
int num2 = scnr.nextInt();
System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
for(int i = 1; i<= Math.min(num1,num2); i++){
if(num1%i==0 && num2%i==0) {
System.out.println(i);
}
}
}
}
Scanner input = new Scanner (System.in);
num1 = input.nextInt();
num2 = input.nextInt();
List<Integer> list = new ArrayList<>();
for(int i=0; i<=Math.min(num1,num2);i++){
if(num1%i==0 && num2%i==0){
list.add(i);
}
}
System.out.println("Divisors:");
for(int a : list){
System.out.println(a); }
if(list.size()<2){
System.out.print("Not Relatively Prime"); }
else { System.out.print("Relatively Prime");}
A code that gives the multiples of 5 in a given number by the user (x,y). If there is none to display, print "NONE". If there is two to display, separate it with "and". And if theres two or more to display, separate it with comma and "and" in the end of it.
System.out.print("Enter first number: ");
int x = new Scanner (System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
for (;x<=y; x++) {
if(x%5==0) {
System.out.printf("%,d ",x);
}
}
Sample Output:
Enter number: 1
Enter number: 4
The multiples of 5 from 1 to 4: NONE
Sample Output:
Enter number: 8
Enter number: 12
The multiples of 5 from 8 to 12: 10
Sample Output:
Enter number: 1
Enter number: 17
The multiples of 5 from 1 to 17: 5, 10, and 15.
The comma you use in printf isn't a simple character, it's a part of the pattern %,d.
Format String Syntax
If the ',' ('\u002c') flag is given, then the locale-specific grouping separator is inserted by scanning the integer part of the string from least significant to most significant digits and inserting a separator at intervals defined by the locale's grouping size.
You need to move it out of the pattern %d and add a condition to drop a comma for the first matching number.
for (int i = 0; x <= y; x++) {
if (x % 5 == 0) {
System.out.printf("%s%d", (i++ == 0 ? "" : ","), x);
}
}
Or you could write it in a fancy way
String result = IntStream.rangeClosed(x, y)
.filter(i -> i % 5 == 0)
.mapToObj(Integer::toString)
.collect(Collectors.joining(","));
System.out.println(result);
I have shown two working examples that use "," as the only delimiter. It gets a bit trickier for three delimiters ("," and ", and", and " and "). It's a rare case where a switch statement comes in handy.
final List<String> values = IntStream.rangeClosed(x, y)
.filter(i -> i % 5 == 0)
.mapToObj(Integer::toString)
.collect(Collectors.toList());
switch (values.size()) {
case 0:
System.out.println("NONE");
break;
case 1:
System.out.println(values.get(0));
break;
case 2:
System.out.println(String.join(" and ", values));
break;
default:
final String last = values.remove(values.size() - 1);
System.out.println(String.join(", ", values) + ", and " + last);
}
EDIT: I edited my answer to match all sizes of the results-ArrayList:
class Main {
public static void main(String[] args) {
System.out.print("Enter first number: ");
int x = new Scanner(System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner(System.in).nextInt();
System.out.print("The multiples of 5 from " + x + " to " + y + " : ");
ArrayList<Integer> results = new ArrayList<Integer>();
for (; x <= y; x++) {
if (x % 5 == 0) {
results.add(new Integer(x));
}
}
if (results.size() == 0) {
System.out.println("No results to display.");
} else if (results.size() == 1) {
System.out.println(results.get(0));
} else {
for (int i = 0; i < results.size() - 2; i++) {
System.out.print(results.get(i) + ", ");
}
System.out.print(results.get(results.size() - 2));
System.out.println(" and " + results.get(results.size() - 1));
}
}
}
By using the ArrayList, You can store the values and later print them out. The for-loop only prints all elements, but without the last one, which then gets printed with an " and" before it!
I hope you understand how this works.
Let me start with a few tips of your current code. You currently create two Scanners for both your user inputs. It would be best to only create this one, and re-use it. So change:
System.out.print("Enter first number: ");
int x = new Scanner (System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
To:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter first number: ");
int x = scanner.nextInt();
System.out.print("Enter last number: ");
int y = scanner.nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
Next, I would advice to make the step into a variable, so it's easier to change later on (or perhaps ask from the user as input as well):
int step = 5;
...
System.out.print("The multiples of "+step+" from "+x+ " to " +y+ " : ");
...
if(x%step == 0){
...
And now onto your actual problem. Let's first analyse what you want:
You want the separator for most items to be ", " (base case)
You want the separator for the second to last integer in the iteration to be " and "
And the final integer doesn't need any separator anymore, since it's the trailing item
Let's now convert these requirements into code:
for(; x<=y; x++){
if(x%step == 0){
// The last `x` that will be printed, is the x where the difference between y and x
// is smaller than the step-size:
boolean lastNumber = y-x < step;
// The `x` for which we want an " and " separator is the second to last item,
// so the difference between x and y should be smaller than twice the step-size:
boolean showAnd = y-x < 2*step;
// And then we can use these two booleans with a simple ternary-if to determine the
// format we'd want to use in our print:
System.out.printf(lastNumber ? "%d\n"
: showAnd ? "%d and "
: "%d, ",
x);
}
}
Try it online.
Try this, Create a conditional base ending char.
System.out.print("Enter first number: ");
int x = new Scanner(System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
if ((x<5 && y<5) || y/5 == x/5) {
System.out.printf("NONE");
}
else {
while (y > x) {
if (x%5==0) {
System.out.printf("%d", x);
x += 5;
if (x < y) {
if (x + 5 < y) {
System.out.printf(" , ");
} else {
System.out.printf(" and ");
}
}
} else {
x += 1;
}
}
}
This is my solution for this:
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");
int x = scan.nextInt();
System.out.print("Enter last number: ");
int y = scan.nextInt();
String output = "The multiples of 5 from " + x + " to " + y + " : ";
for (; x <= y; x++) {
if (x % 5 == 0) {
output = output + x + ", ";
}
}
output = output.substring(0,output.length() -5) + " and "+output.substring(output.length() -4, output.length()-2);
System.out.println(output);
consider stream api, like
IntStream.range(2, 8).mapToObj(Integer::toString).collect(Collectors.joining(", and "))
My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.
int count, number;//declared count as loop and number as user input
int fact = 1;//declared as 1
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
System.out.println(number);//prints number the user input
if (number > 0) {
for (i = 1; i <= number; i++) {//loop
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
}
create a string and store the numbers.
try something like this.
int count, number;//declared count as loop and number as user input
String s; //create a string
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
int fact = number;//store the number retrieved
System.out.println(number);//prints number the user input
if (number > 0) {
s=String.valueOf(number);
for (int i = 1; i < number; i++) {//loop
fact = fact * i;
s = s +" * "+String.valueOf(number-i);
}
System.out.println(s+ " = " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
Check out this recursive approach: (check negative numbers yourself :D)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}
public static String getFactorialString(int num, String result) {
if (num == 0) return "0 => 1";
if (num == 1) {
result = "" + num + "" + result;
} else {
result = getFactorialString(num - 1, result);
result = "" + num + " x " + result;
}
return result;
}
public static int getFactorial(int num) {
if (num == 0) return 1;
return num * getFactorial(num - 1);
}
I have to read in a file to my project and then read the file line by line to find the percent of upper case and lower case letters. My output should be 4 lines stating the percent of upper and lower for that specific line in the file. This is what I have to far but it doesn't quite work:
Scanner inFile = new Scanner(new File("file.txt"));
int upper = 0;
int lower = 0;
int total;
double percentU = 0.0;
double percentL = 0.0;
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++)
{
if (Character.isUpperCase(line.charAt(x)))
{
upper++;
}
if (Character.isLowerCase(line.charAt(x)))
{
lower++;
}
total = upper + lower;
percentU = upper/total;
percentL = lower/total;
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
}
}
When you divide an int by another int the result will be also an int. So for example if you divide 30 by 50 the result will be 0 instead of 0.6.
More information:
How to make the division of 2 ints produce a float instead of another int?
Integer division: How do you produce a double?
Division of integers in Java
I Just change these lines removed if (Character.isLowerCase(line.charAt(x))):
if (Character.isUpperCase(line.charAt(x))) {
upper++;
}
if (Character.isLowerCase(line.charAt(x))) {
lower++;
}
To:
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
And moved these lines out of while loop:
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
Try this solution it's ok:
public static void main(String[] args) {
Scanner inFile = null;
int upper = 0;
int lower = 0;
int total = 0;
double percentU = 0.0;
double percentL = 0.0;
try {
inFile = new Scanner(new File("C:\\temp\\file.txt"));
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++) {
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
}
}
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Right now my code is this
import java.text.*;
import java.util.Scanner;
public class Homework6_EvenOdd
{
public static void main(String[] args)
{
//Varaiable declaration
int even=50;
int odd=51;
//Loop logic for even
System.out.print("Your even numbers are "+even+", ");
while (even <= 99)
{
even += 2;
System.out.print(even + ", " );
}
System.out.println ();
//Loop logic for odd
System.out.print ("Your odd numbers are "+(odd)+", ");
while (odd + 1 <= 99)
{
odd += 2;
System.out.print(odd + ", " );
}
}
}
I can't figure out how to do this with only one loop.
I don't even know where to start. I can't figure out how I would get the even and odd numbers to print on separate lines if there is only one loop?
Here is variant which produces exact copy of your current output:
public class Homework6_EvenOdd {
public static void main(final String[] args) {
final StringBuilder even = new StringBuilder();
final StringBuilder odd = new StringBuilder();
for (int i = 50; i <= 100; i++) {
if ((i & 1) == 0) {
even.append(i + ", ");
} else {
odd.append(i + ", ");
}
}
System.out.println("Your even numbers are " + even.toString());
System.out.println("Your odd numbers are " + odd.toString());
}
}
import java.text.*;
import java.util.Scanner;
public class Homework6_EvenOdd
{
public static void main(String[] args){
//Varaiable declaration
int even=50;
int odd=51;
//Loop logic for even
System.out.print("Your even numbers are "+even+", ");
while (even <= 99 || odd + 1 <= 99){
if (even <= 99) {
even += 2;
System.out.print(even + ", " );
}
System.out.println();
if (odd + 1 <= 99) {
odd += 2;
System.out.print(odd + ", " );
}
}
}
Though I have to say this code is not much better. There are much better ways to figure out if a number is even or odd (hint modulo).
You can collect each of odd and even numbers with List.
After that you can print them.
ArrayList<String> odds = new ArrayList<>();
ArrayList<String> evens = new ArrayList<>();
for (int i = 50; i < 100; i++) {
if (i % 2 == 0) {
evens.add(String.valueOf(i));
} else {
odds.add(String.valueOf(i));
}
}
System.out.println("Your even numbers are: " + String.join(", ", evens));
System.out.println("Your odd numbers are: " + String.join(", ", odds));
Note: String.join() is for Java 8 or later.