Java Factorial On JOptionPane - java

I want to show factorial result and work(calculation) in same JOptionPane dialog box, as example 1x2x3x4x5=120 and spent hours but haven't found a solution. Any help will be highly appreciated. :)
private fun uploadWithTransferUtility(remote: String, local: File) {
String number = JOptionPane.showInputDialog("Please enter the number below ");
int n = Integer.parseInt(number);
long fact = 1;
int i = 1;
if (n<=0){
JOptionPane.showMessageDialog(null," Please enter a possitive number");
}
else{
while(i<=n)
{
if (i==1){
fact = fact * i;
System.out.print(i);
i++;
}
else{
fact = fact * i;
System.out.print("*"+i);
i++;
}
JOptionPane.showMessageDialog(null,"="+fact);
}

You can do it like this
int n = Integer.parseInt(number);
long fact = 1;
int i = 1;
if (n <= 0) {
JOptionPane.showMessageDialog(null, " Please enter a possitive number");
} else {
StringJoiner stringJoiner = new StringJoiner("x"); //You can use "*" if you want
for (i = 1; i <= n; i++) {
fact = fact * i;
stringJoiner.add(i + "");
}
JOptionPane.showMessageDialog(null, stringJoiner.toString() + "=" + fact);
}

Related

My program is breaking out of the first for loop after one iteration

Here is my code. It asks user for terms and definitions, then quizzes the user. (It tells the user the term, and the user types in the answer.) The program uses arrays to store the terms and definitions. If the user doesn't get the definition correct, the program asks the user whether they want to study it again. If so, they will type in yes, and the program will store it on a separate array. After the program quizzes the users on all the terms and definitions, round 2 starts, where the program will quiz the user only on the starred definition. The problem is, the code is only running the for loop (that quizzes the user on round 1) once, and then skips onto round 2. Why is that so? I already tried looking at other people's questions and answers, but I can't seem to find the problem in my code.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i <= number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}
}
for (int i = 0; i <= number_terms; i++)
You have number_terms + 1 iterations. Replace with
for (int i = 0; i < number_terms; i++)
The bug is that the for-loop that you have tagged with the comment "the for loop that isn't working" is not looping through all the definitions. This for-loop after handling the first definition it moves on to handling round 2 instead of continuing the loop to the 2nd definition and so on. The fix requires that you place the closing bracket of this for-loop before the print statement "Now, time for testing definitions you starred!" as shown below. I have added the comment "end for-loop to ensure looping of all definitions" at the for-loop closing bracket that I have moved up in the code below. In addition this for loop's iteration condition should be 'i < number_terms' as the previous posters have indicated.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such " +
"that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i < number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
} // end for-loop to ensure looping of all definitions
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}

Sum of Numbers (expected output issue)

I am having issues with my program. The point is that the user needs to enter a starting number (ex:1) and an ending number (ex:5), the output should be 1+2+3+4+5=15. I, on the other hand, am getting 1+2+3+4+5+. I am unsure as to how to fix it, any help would be greatly appreciated. Thanks!Also is there anyway to not return null? My program keeps asking me to return it to null.
import java.util.Scanner;
public class SumOfNumbers
{
public String getSum(int start, int end)
{
int sum=0;
Scanner scanner = new Scanner(System.in) ; //Scanner used to get keyboard values
System.out.println("Enter your starting number: ");
start = scanner.nextInt(); //first number
System.out.println("Enter your ending number: ");
end =scanner.nextInt(); //second number
for(int i=start;i<=end;i++)
{
sum=sum+i; //calculating sum
scanner.close();
System.out.print(i + "+");
}
return null;
}
}
You currently output + after every number, instead output the first number and then start looping (but in the loop, output a + before every number). Also, don't forget to output the sum after your loop. Something like
int sum = start;
System.out.print(start);
for (int i = start + 1; i <= end; i++) {
System.out.print("+" + i);
sum += i;
}
System.out.println(" = " + sum);
However, since you apparently need to return this result as a String you should be doing something like
int sum = start;
StringBuilder sb = new StringBuilder();
sb.append(start);
for (int i = start + 1; i <= end; i++) {
sb.append("+").append(i);
sum += i;
}
sb.append("=").append(sum);
// System.out.println(sb.toString());
return sb.toString();
And you should probably be using the start and end values you pass to the function (instead of ignoring them and prompting the user in the function).
I have tried to add both of the outputs together in the return statement by making them into strings but no luck
The code above is logically equivalent to (but more efficient then)
int sum = start;
String result = String.valueOf(start);
for (int i = start + 1; i <= end; i++) {
result = result + "+" + i;
sum = sum + i;
}
result = result + "=" + sum;
// System.out.println(result);
return result;
It could also be written more concisely like
int sum = start;
String result = String.valueOf(start);
for (int i = start + 1; i <= end; i++) {
result += "+" + i;
sum += i;
}
result += "=" + sum;
// System.out.println(result);
return result;
Or, if we're using Java 8+, with lambdas like
StringBuilder sb = new StringBuilder(String.valueOf(start));
int sum = IntStream.rangeClosed(start, end).sum();
IntStream.rangeClosed(start + 1, end).forEach(x -> sb.append("+").append(x));
sb.append("=").append(sum);
// System.out.println(sb);
return sb.toString();
hope this will help
class SumOfNumbers
{
public void getSum(int start, int end)
{
int sum=0;
Scanner scanner = new Scanner(System.in) ; //Scanner used to get keyboard values
System.out.println("Enter your starting number: ");
start = scanner.nextInt(); //first number
System.out.println("Enter your ending number: ");
end =scanner.nextInt(); //second number
for(int i=start;i<=end;i++)
{
sum=sum+i; //calculating sum
scanner.close();
if (i==end) {
System.out.print(i );
}
else {
System.out.print(i + "+");
}
}
System.out.print("="+ sum);
}
}
output
Enter your starting number:
1
Enter your ending number:
15
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15=120
Here is a method that will do what you are asking for:
public String output(int startNum, int endNum) {
String reply = "";
int answer = 0;
for (int x = startNum; x <= endNum; x++) {
if (x == startNum) reply = "" + x;
else if (x == endNum) reply = reply + "+" + x + "=";
else reply = reply + "+" + x;
answer += x;
}
reply = reply + answer;
return reply;
}
Here is the output:
System.out.println(output(1,10));
1+2+3+4+5+6+7+8+9+10=55

How to check if a number is a palindrome?

I wrote a piece of code for a class homework. However I thought it was quite long! Is there a more optimized way to do this?
String text = input.readLine();
int num = (text.length())/2;
double letter = (double)(text.length())/2;
String s1 = text.substring(0,num);
int u1 = Integer.parseInt(s1);
if (letter%1==0) {
StringBuffer s2 = new StringBuffer(text.substring(num));
s2 = s2.reverse();
String t2 = s2.toString();
int u2 = Integer.parseInt(t2);
if (u1==u2) {
System.out.println("Palindrome");
} else {
System.out.println("FAIL");
}
} else {
StringBuffer s2 = new StringBuffer(text.substring(num+1));
s2= s2.reverse();
String t2 = s2.toString();
int u2 = Integer.parseInt(t2);
if (u1==u2) {
System.out.println("Palindrom");
}else {
System.out.println("FAIL");
}
}
You don't need to convert the string back to number in order to compare them. You can use string's equals() method to check if they are equal. Check this out (with necessary changes this will work for any string though, not just numbers).
int num = 12300321;
String numString = String.valueOf(num);
String reverseNumString = new StringBuilder(numString).reverse().toString();
if(numString.equals(reverseNumString)) {
System.out.println(num + " is a Palindrome!");
}
else {
System.out.println(num + " is not a Palindrome!");
}
Output:
12300321 is a Palindrome!
Alternate method (using only number manipulation; will work for integers only)
int num = 12300321;
int numCopy = num;
int reverseNumInt = 0;
while(numCopy != 0) {
reverseNumInt = reverseNumInt * 10 + numCopy % 10;
numCopy /= 10;
}
if(reverseNumInt == num) {
System.out.println(num + " is a Palindrome!");
}
else {
System.out.println(num + " is not a Palindrome!");
}
Your code works, but handling the numbers digit by digit is simpler and more readable:
public static boolean isPalindromic(String num) {
for(int i = 0, len = num.length() ; i < len/2 ; i++) {
if(num.charAt(i) != num.charAt(num.charAt(len-i-1))) return false;
}
return true;
}

Java Unexpected Programming Result

I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.

Ask users if user wishes to re-run the program

I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.

Categories