I have a school project due next week and I'm trying to crack the way to solve this question.
The problem was to develop a program that adds the fractions the user inputs until he types -1.
the input will always be in pair and positive numbers.
Must only use: int, for,while, if, scanner (so no break or arrays)
Preferably with the use of GCD since it's required to println the
reduced sum of fractions
So my questions are this:
can I use a while loop until user types -1 using the scanner?
Is it alright to use the 'while' to let a user type 'infinite' (I am aware that there is no such this in java) number of number until termination?
in the code of the previous question I wrote the common factor for
the equation, how do I write a common factor for an unknown number of
variables
Edit:
here is my code, the problem is, it only runs for 4*n numbers, I need it to be able to run for 2*n numbers: ( like 2/4 or 2/4+1/3+1/2)
Scanner myScanner=new Scanner(System.in);
int a;
int b;
int c;
int d;
int m = a*d + b*c;
int n = b*d;
int r = m%n;
while((a = myScanner.nextInt()) != -1)
{
b = myScanner.nextInt();
c = myScanner.nextInt();
d = myScanner.nextInt();
while (r != 0) {
m=n;
n=r;
r = m%n;
}
m = (a*d + b*c)/n;
n = (b*d)/n;
System.out.println(m);
System.out.println(n);
}
}
A.
It is possible to keep reading input from a scanner until a defined message (in this case pairs of numbers until -1 is entered)
Scanner scanner = new Scanner(System.in);
int num1;
int num2;
while((num1 = scanner.nextInt()) != -1)
{
num2 = scanner.nextInt();
//do stuff with num1 and num2
}
B.
The whole point of A. is to allow variable amounts of input from the user, so unless you have a reason for a hard limit, it should in theory take infinite input
C.
Instead of trying to compute the common factor before you have any numbers, it's easier to compute the common factor as you get the numbers
int newNumerator = numerator1 * denominator2 + numerator2 * denominator1;
int newDenominator = denominator1 * denominator2;
Keeping track of the current numerator and denominator, updating as you get more pairs
This can then have A. be applied to it for infinite input
Scanner scanner = new Scanner(System.in);
int numerator = 0;
int denominator = 0;
int tempNumer = 0;
int tempDenom = 0;
if((numerator = scanner.nextInt()) != -1)
{
denominator = scanner.nextInt();
while((tempNumer = scanner.nextInt()) != -1)
{
tempDenom = scanner.nextInt();
numerator = numerator * tempDenom + tempNumer * denominator;
denominator = denominator * tempDenom;
}
}
Related
Program to check if a given number is present in an arithmetic progression series. User provides T, which is the number of a series that the user also provides.
User provides A, 1st number of series, B, the number to check if present in series and C, the common difference.
The code runs, but won't submit online(shows runtime error). Also, in each case the output is "YES".
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double n;
int k;
int T = sc.nextInt(); //number of times series will be given by user.
while (T != 0) {
T -= 1;
int A = sc.nextInt(); //1st term of the AP series
int B = sc.nextInt(); //to check if this number(B) appears in the series
int C = sc.nextInt(); //common difference
if (A == B) {
System.out.print("YES");
}
n = (((B - A) / C) + 1); // if this formula is right then n should be
//an integer when B is present in series
//or it n should be a float number if B is not in the series
k = (int) n;
if (k == n)
System.out.println("YES");// even when B is NOT in series, "YES" is printed
else
System.out.println("NO");
}
}
}
Java discards the remainder when dividing integers, so despite declaring n as a double, it will always have an integer value. You could replace C with (1.0 * C) to force floating-point division, or use the modulo operator % to sidestep the issue entirely.
I have written the following code, with following conditions. I was not allowed to use any String or Math class, so I used for loops, to break the number down.
It works for e.g 153 and 54883 but for numbers like 4679307774 the Scanner Type gives me back a misMatchExeption. I do understand why, I tried using long type, the program works then, but does not (due to Two`s) give back a correct answer.
I want to know, how to solve that problem, or better said what other things I could try here.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter any Integer above zero here : ");
System.out.println("Enter length of number, from 1 onwards: ");
int num = sc.nextInt();
int pow = sc.nextInt();
int narziss = 0; // TODO mismatchexeption
int single;
int a;
do {
a = 1;
single = num % 10; // takes each chiffre from behind, for as long as for runs.
System.out.println("single modulo : " + single);
num = num / 10;
for (int i = 0; i < pow; i++) {
a *= single;
System.out.println(a);
}
narziss += a;
System.out.println("narziss: " + narziss);
} while (num != 0);
System.out.println(" if the last shown number, " +
"is the same as you have typed in, " +
"you found an so-called armstrong number! ");
}
}
The problem i was asking, can be solved with a type other than Integer.
With long for example... or floating point types.
Be sure to change or cast all involved parts, like scanner, loops and so on.
1.This is my code to convert binary to decimal but its not working.The c value gets repeated for some reasons.
/**
* Created by Ranjan Yadav on 11.10.2016.
*/
public class BinaryToDecimal {
public static void main(String[] args) {
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary = read.nextInt();
int total = 0;
int n = 1;
int c = 0;
int number = 0;
while (binary != 0) {
c = binary % ((int) Math.pow(10, n));
binary = binary / 10;
number = c * (int)(Math.pow(2, (n - 1)));
total += number;
++n;
}
System.out.printf("The decimal of the binary is %d", total);
}
}
You were increasing n by 1 and dividing binary by 10 raised to n at same time. Due to this, you were not able to fetch the unit's digit of binary number after 1st iteration. To solve this issue, you need to get binary modulo 10 (not 10 raised to n) in each iteration and also keep the statement of binary divided by 10.
I have simplified and also made some small changes to your code to increase readability. Here is the corrected main method :
public static void main (String[] args){
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary = read.nextInt();
int total = 0;
int n = 0;
int c = 0;
int number = 0;
while (binary != 0) {
c = binary % 10;
binary = binary / 10;
number = c * (int)(Math.pow(2, n));
total += number;
++n;
}
System.out.println("The decimal of the binary is " + total);
}
The code is working and producing desired results. Let me know in case you have any further doubts.
You can just parse the integer with the parseInt method:
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = read.nextLine();
int decimal = Integer.parseInt(binary, 2); // 2 here means the string "binary" is in binary
If you're not allowed to use that, try this algorithm:
Create a variable total and make it 0.
Loop through the binary string with a for loop like this: for (int i = 0 ; i < binaryString.length() ; i++)
In each iteration, if the character is 1, add Math.pow(2, binaryString.length() - 1 - i). Otherwise do nothing.
I have an assignment in my programming class. It goes like this, I have to make a program which takes the input of the user how many exercises he wants to do. Then he solves simple calculations with random numbers from 1-10 and with random operators. In the end, it should write how many correct and incorrect ones did he get. It also should write the elapsed time of the task.
I did some work, but when I assign a random value to an operation
int operation = (int)(Math.random()*3)+1;
or to a number a and b
int a = (int)(Math.random()*10);
int b = (int)(Math.random()*10);
I always get the same number and operator when I choose for the second or third time my task (because I use a loop). Is there a way to change the same initialized variable or operator during a program. For example that int a=(int)(Math.Random()*10) is initialized in the beginning as for example as 3, and later when the program loops again to initialize it as a different number, for example 6. Are there any others solutions for my problem?
Here is my whole code, for now:
import java.util.*;
import javax.swing.JOptionPane;
public class RandomChar {
public static void main(String[] args) {
char op= ' ';
int operation = (int)(Math.random()*3)+1;
int a = (int)(Math.random()*10);
int b = (int)(Math.random()*10);
String s;
int correct = 0, incorrect=0;
s = JOptionPane.showInputDialog("How many exercises do you want?");
int num = Integer.parseInt(s);
long tStart = System.currentTimeMillis();
while(num>0){
if(operation==1)
op='+';
else if(operation==2)
op='-';
else if(operation==3)
op='*';
String str1 = JOptionPane.showInputDialog(a+" "+op+" "+b+" = ");
int num1 = Integer.parseInt(str1);
if(op=='+'){
if(a+b==num1)
correct++;
else
incorrect++;
}else if(op=='-'){
if(a-b==num1)
correct++;
else
incorrect++;
}else if(op=='*'){
if(a*b==num1)
correct++;
else
incorrect++;
}
num--;
}
long tEnd = System.currentTimeMillis();
long tOverral = tEnd - tStart;
double elapsedSeconds = tOverral / 1000.0;
System.out.println("Correct: "+correct);
System.out.println("Incorrect: "+incorrect);
System.out.println("Elapsed seconds: "+ elapsedSeconds);
}
}
Simply move the calculation of random numbers and the operator into your while-loop. Actually you calculate them once.
while (num > 0) {
int operation = (int) (Math.random() * 3) + 1;
int a = (int) (Math.random() * 10);
int b = (int) (Math.random() * 10);
...
}
So you'll have new numbers and operators in any exercise.
Write a method that computes the sum of the digits in an integer. Use
the following method header: public static int sumDigits(long n)
Programming problem 5.2. Page 212.
Please forgive my newness to programming. I'm having a hard time understanding and answering this question. Here's what I have so far. Please assist and if you dont mind, explain what I'm doing wrong.
import java.util.Scanner;
public class PP52v2 {
public static void main(String [] args) {
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}//main
public static int sumDigits(long n) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
n = input.nextLong();
int num = (int)(n);
int sum;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}//loop
return sum;
}//sumDigits
}//class
Basically, you should not be handling the user input inside of the method. You should be passing the user input into your method. Other than that, everything looks good. I've made that slight change below:
import java.util.Scanner;
public class PP52v2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
long n = input.nextLong();
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}// main
public static int sumDigits(long n) {
int num = (int) (n);
int sum = 0;
while (num > 0) {
sum += num % 10; // must mod - gives individual numbers
num = num / 10; // must divide - gives new num
}// loop
return sum;
}// sumDigits
}// class
Do the prompt
System.out.println("Enter your digits");
n = input.nextLong();
in your main(String[] args) method because n is not currently declared in the scope of the main method.
public static int sumDigits(int num) {
int sum = 0;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new number
} //End loop
return sum;
}
For one, you should not read in the number within this method, as it accepts the number as a parameter. The method should be invoked after calling long inputNum = input.nextLong(); by using int digitSum = sumDigits((int)inputNum).
When writing a method, you have input, output, and side effects. The goal is to choose the right combination of the three so that the method, and program as a whole, words as expected.
It seems like your method is supposed to take a number as input and return each digit added together into one final sum.
Write A Test
Usually when you program, you come up with some code that uses your imaginary function. This is called a test. For a test, this could work:
System.out.println("123 should be 6: " + sumDigits(123));
Choose A Signature
You've already managed to right the correct signature. Nice!
Implement Method
Here's where you're a bit confused. Read through what every line of code does, and see if it is accomplishing your goal.
// set up a scanner for reading from the command line
// and print a message that you expect digits
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
// read the next long number from the input stream
n = input.nextLong();
Why is this part of your method? You already have the number passed in as the argument n.
// cast the number to an integer
int num = (int)(n);
Again, not sure what this is accomplishing, besides the possibility of a bug for large numbers.
// initialize the sum variable to 0.
int sum;
Would be clearer to explicitly set the sum to 0. int sum = 0;
// add the last digit and truncate the number in a loop
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}
// actually return the calculated sum
return sum;
This seems like the only part of the method you need. Hopefully this helps!
Since the input number can be either positive or negative, you need to convert it to its absolute value to get the sum of digits. Then for each iteration, you add the remainder to the total sum until the quotient is 0.
public static int sumDigits(long n) {
int sum = 0;
long quotient = Math.abs(n);
while(quotient > 0) {
sum += quotient % 10;
quotient = (long) quotient / 10;
}
return sum;
}
Your code works fine for me.
i just changed int sum = sumDigits(n) to int sum = sumDigits(0) since n wasn't declared.
To have it done correctly, you just would have to put your scanner into the main method and pass the result of it (the long value) to your method sumDigits(long n).