Sum of Numbers (expected output issue) - java

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

Related

Can't get results from boolean to appear correctly

My program asks the user for a number and then decides if the number is between the range of two randomly generated numbers or outside of it. Everything works fine, except the program keeps giving the result that the guessed number is outside the range, even when it is inside the range. Not sure how to get the answer to show correctly. Boolean result = true is there since a "Cannot find symbol" error appears if it is not.
Code:
public static int getValidGuess(Scanner get)
{
int num;
System.out.print("Guess a number: --> ");
num = get.nextInt();
return num;
} // getValidGuess end
public static boolean displayGuessResults(int start, int end, int num)
{
int n1, n2;
boolean result = true;
Random gen = new Random();
n1 = gen.nextInt(99) + 1;
n2 = gen.nextInt(99) + 1;
if(n1 < n2)
{
start = n1;
end = n2;
} // if end
else
{
start = n2;
end = n1;
} //else end
if(num > start && num < end){
result = true;
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Good Guess!");
} //if end
if(num < start || num > end){
result = false;
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Outside range.");
} //if end
return result;
} // displayGuessResults end
public static void main(String[] args) {
// start code here
int start = 0, end = 0, num = 0, input;
Scanner scan = new Scanner(System.in);
String doAgain = "Yes";
while (doAgain.equalsIgnoreCase("YES")) {
// call method
input = getValidGuess(scan);
displayGuessResults(start, end, num);
System.out.print("\nEnter YES to repeat --> ");
doAgain = scan.next();
} //end while loop
} //main end
Your displayGuessResult should be improved:
public static boolean displayGuessResults(int num) {
boolean result = true;
Random gen = new Random();
int n1 = gen.nextInt(99) + 1;
int n2 = gen.nextInt(99) + 1;
int start = Math.min(n1, n2);
int end = Math.max(n1, n2);
System.out.println("\nThe 2 random numbers are " + start + " and " + end);
if(num >= start && num <= end){
result = true;
System.out.println("Good Guess!");
} else {
result = false;
System.out.println("Outside range.");
}
return result;
} // displayGuessResults end
and you have to call it using input read from the Scanner:
input = getValidGuess(scan);
displayGuessResults(input);

Java Factorial On JOptionPane

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);
}

How to output random letters in java and get the total, high score and lowest score?

Basically, I'm trying to output random uppercase letters and the loops go on forever what am I doing wrong?
I've tried other methods using java.util.Scanner for my input dialog but other than that I can't see what's wrong.
import javax.swing.*;
public class SlotMachine {
public static void main (String[] args) {
String HOWN = JOptionPane.showInputDialog ("Enter how many times you are going to play");
int HOW = Integer.parseInt (HOWN);
double counter = 0;
System.out.println("You chose to play " + HOW + " times");
for (int i = 0; i<HOW; i++) {
for (int b = 0; b<3; i++) {
double result = Math.random();
result = Math.round (result );
result = result * ((90 - 65)+1) - 65;
char resultF = (char)result;
counter = counter + result;
System.out.println ("");
System.out.println("you got: " + resultF + " which is " + result + "in ASCII code");
System.out.println("your total is: " + counter);
}
}
}
}
You have done
for (int b = 0; b<3; i++)
instead of the correct
for (int b = 0; b<3; b++)
This should help your loop terminate.

how to find StickNumbers

So I have to read a sequence of numbers from the console ( 1 to 50 numbers), none of which are equal and print out the numbers for which is true that a|b == c|d (example: 5|32 == 53|2), but I get an NubmferFormatException each time. Why?
import java.util.Scanner;
public class StuckNumbers {
public static void main(String[] args) {
// create Scanner
Scanner input = new Scanner(System.in);
// input count and declare array
System.out.println("input number of numbers");
int count = input.nextInt();
int[] numbers = new int[count];
// check if count is between 1 and 50
if (count < 1 && count > 50) {
System.out.println("Wrong input. Input a number between 1 and 50");
count = input.nextInt();
}
// input n numbers
for (int i : numbers) {
i = input.nextInt();
// check if i = j
for (int j : numbers) {
if (i == j) {
System.out
.println("All numbers must be dist75inct. Try again.");
i = input.nextInt();
}
}
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
if (stuckNumbers(numbers[i], numbers[j]) == stuckNumbers(
numbers[j], numbers[i])) {
System.out.println(i + "|" + j + " == " + j + "|" + i);
}
}
}
input.close();
}
public static int stuckNumbers(int a, int b) {
String firstNum = "a";
String secondNum = "b";
String res = "ab";
int result = Integer.parseInt(res);
return result;
}
}
Look at these lines:
String res = "ab";
int result = Integer.parseInt(res);
"ab" is not a number, so you're going to get a NumberFormatException when you try to parse it as an integer.
Change the firstNum and SecondNum variables from "a" and "b" to Integer.toString(a); OR String.valueOf(a); and similar for b.
public static int stuckNumbers(int a, int b) {
String firstNum = String.valueOf(a);
String secondNum = String.valueOf(b);
String res = "";
res.concat(firstNum);
res.concat(secondNum);
int result = Integer.parseInt(res);
return result;
}
I hope this will remove any Exception being thrown.

Java count longest possible array

I'm doing a coin toss program, and am trying to determine the longest possible run of heads or tails that were tossed. I already have code for determining if toss is heads or tails, but now need to count longest possible run. Help! Here's my code for the basic program.
public static void coin_toss(char [] toss)
{
int s = 0;
try
{
for (s = 0; s <= toss.length; s++)
{
double flip;
flip = (double)(Math.random());
if (flip < 0.5)
toss[s] = 't';
else
toss[s] = 'h';
}//end of for loop to load array
}
catch (ArrayIndexOutOfBoundsException errorMessage)
{
System.out.println("\nSubscript out of bounds");
System.out.println("Subscript went past the limit of " + toss.length);
System.out.println("Last value of subscript was --> " + s);
System.out.println("-------------------------------------------------");
System.out.println(errorMessage);
System.out.println("-------------------------------------------------");
}
}//end of toss coin
public static double percent_heads (char [] toss)
{
double percent_h;
int heads = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 'h')
heads = heads + 1;
}
System.out.println("There were " + heads + " heads results");
percent_h = (double)heads / toss.length;
return (percent_h);
}//end of heads percentage function
public static double percent_tails (char [] toss)
{
double percent_t;
int tails = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 't')
tails = tails + 1;
}
System.out.println("There were " + tails + " tails results");
percent_t = (double)tails / toss.length;
return (percent_t);
}//end of tails percentage function
public static void main(String [] args)
{
int num_toss = 0;
double heads, tails;
double percent_t, percent_h;
DecimalFormat percent = new DecimalFormat ("#0.00%");
System.out.print("How many tosses would you like? --> ");
num_toss = GetInput.readLineInt();
char [] toss = new char[num_toss];
System.out.println("You chose " + toss.length + " tosses");
coin_toss(toss);
heads = percent_heads(toss);
tails = percent_tails(toss);
System.out.println("The percentage of heads was --> " + percent.format(heads));
System.out.println("The percentage of tails was --> " + percent.format(tails));
longest_toss(toss);
java.util.Date today = new java.util.Date();
System.out.println("\nProgram terminated at " + today);
System.exit(0);
}//end of main method
}//end of class
There is a method I came up with.
public static void longest_toss(char[] toss){
int longestrun = 0;
int curlongestrun = 0;
char prevrun = toss[0];
for (int s = 1; s < toss.length; s++)
{
if (toss[s] == prevrun) {
curlongestrun++;
}else {
curlongestrun=0;
}
if(curlongestrun>longestrun){
longestrun = curlongestrun;
}
prevrun = toss[s];
}
System.out.println("Longest run is : " + longestrun + " Coin side : " + prevrun);
}
You can get maximum index of the array toss[] as Integer.MAX_VALUE - 8
Here it is less by 8 because, in the source code of java.util.ArrayList class, it is clearly mentioned that, MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 provided you have sufficient memory to hold the content of array with this much data.
int getLongestHeads(char [] toss){
int longestHeads = 0;
for(char c : toss)
{
if(longestHeads > 0 && c == 'h'){
longestHeads = longestHeads + 1;
}
else{
longestHeads = 0;
}
if(c == 'h' && longestHeads == 0) {
longestHeads = 1;
}
}
return longestHeads;
}

Categories