I'm coding a program to calculate factorials but can't seem to figure out the part where it actually prints out the final value.
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter integer value: ");
int x=scan.nextInt();
System.out.print(x+"!=");
int y=0;
for(int i=x;i>0;i--) {
//y=x*i;
y=i*(i-1);
if(i==1)
System.out.print(i+"=");
else
System.out.print(i+"*");
//for (int j=2;j>=1
}
System.out.print(y);
}
}
the program is supposed to display the numbers it multiplied by as well
i.e. INPUT=5
OUTPUT= 5!=5*4*3*2*1=120
or
OUTPUT=5!=1*2*3*4*5=120
First thing you need to do is to put the curly brackets on and then indent,so as to decrease the confusion.
The code below does what you intend to and has the necessary comments
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter integer value: ");
int x=scan.nextInt();
System.out.print(x+"!=");
int y=1;// Initialize to 1 not 0 as you'll be multiplying.
for(int i=x;i>0;i--) {
/*
Iteration by iteration:
i = 5,y= 1-> y = 1*5
i = 4,y= 5-> y = 5*4
So on...
*/
y*=(i);
if(i==1)
{
// Print Equal only if its the last number. Since
we are going 5*4*3*2*1 =. We need this if to print
1 =.
System.out.print(i+"=");
}
else
{
//For other cases just print Number and *.
System.out.print(i+"*");
}
}
// Print the actual output.
System.out.print(y);
}
}
Related
I am trying to write a program to read a series of numbers from the user until -1 is entered. It should then print the average (with decimals) of those numbers (not including the -1). This is what I have so far, but it does not seem to work properly whenever I input -1. This is what I have thus far:
import java.util.Scanner;
import java.util.*;
public class Tute1
{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many numbers you want: ");
int numb = sc.nextInt();
int i =0;
int total =0;
while (i <= numb) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer ");
int myChoice=scan.nextInt();
total=total+myChoice;
i=i+1;
if(myChoice == -1) {
System.out.println("The average is "+ (total+1)/numb);
break;
}
}
System.out.println("The average is "+ total/numb);
}
}
Your code seems a bit odd. Here is how I would do it
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int total = 0;
while (true) {
System.out.println("Enter an integer ");
int myChoice = scan.nextInt();
if (myChoice != -1) {
total = total + myChoice;
i += 1;
} else {
break;
}
}
float average = total / i;
System.out.println("The average is " + average);
}
Hope this helps. You can add try-catch and stuff to make it so that user does not exploit this
Few things:
first of all you dont need to create a new scanner as your code inside the while loop. Its because the while loop is inside you function scope so every thing you declare on you function the while loop knows about. (It does not work the other way around)
second your breaking condition should be inside the while loop the if with break is redundant and unnecessary.
third thing you should get rid of numb as its doing nithung
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int numb = sc.nextInt();
int i =0;
int total =0;
while (numb != -1)
{
total=total+numb;
i=i+1;
int numb = sc.nextInt()
}
System.out.println("The average is "+ total/i);
}
}
I think this solution is smaller and more elegant
I'm having a hard time with my second method, The method declaration is:
public static void displayOutput(int loopCount)
The method is called from the main() and is passed the valid input value which determines repetition. The method displays the output pattern only and returns nothing. Every 3rd line displays a space and 3 asterisks
I know I'm not calling each method right in the main() and I know that displayOutput(int loopCout) is wrong.
Could someone explain this to me or use an example that would help write the program?
public static void main(String[] args) {
int repeat;
Scanner goGet = new Scanner(System.in);
repeat = getValidValue(goGet); //Uncompilable source code -Erroneous sym type
displayOutput(repeat);
}
public static int getValidValue() {
int input;
do {
Scanner getInfo = new Scanner(System.in);
System.out.print("Enter an integer Greater than zero: --> ");
input = getInfo.nextInt();
} while (input <= 0);
return input;
}
public static int displayOutput(int loopCount) {
int i;
for (i = 0; i < loopCount; i++) {
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon.*** ");
}
return loopCount;
}
You are passing a value to method getValidValue which doesn’t take any value.
Also displayOutput is returning loopcount but you are not catching it anywhere so after asterisk it is not displaying anything.
The problem is to find the smallest palindrome integer after the given number.
Input the number of integers i.e test cases.
Input the integers in an array.
Output: The next palindrome integer corresponding to each integer in the array respectively.
There are various methods to solve this problem(many solutions on SO as well), but I cannot figure out why I can't get the output from this code. From running the code many times, I have concluded that if any test case needs more than 1 increment to become a palindrome, the program goes into an infinite loop somehow.
Eg. If I input 100 as a test case, the output is 101.Similarly, if I enter 908, I get 909 as output. But if I enter 108, I do not get 111 as the output.
Please bear with my silly mistakes, I'm new to coding in Java. Thanks
import java.util.Scanner;
class nextPalindrome {
public static void nextPalindromeGenerate(int n)
{
int flag=1;
int digit; //to store the mod value
int rev=0; //reverse of the number
int original; //dummy to store the original number
if(n<10)
{ System.out.println(n+1); //If number is single digit, next smallest palindrome is n+1
flag=0;
}
while(flag!=0)
{ ++n;
original=n;
while(n>0) //loop for reversing the number
{
digit=n%10;
rev=rev*10+digit;
n=n/10;
}
if(rev==original) //check if original equals the reverse(original)
{
System.out.println(rev);
flag=0;
}
else flag=1;
}
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] palinList=new int[n];
for(int i=0;i<n;i++)
{
palinList[i]=sc.nextInt();;
}
for(int j=0;j<n;j++)
{
nextPalindromeGenerate(palinList[j]);
}
}
}
You increment n to the next integer to test for being palindromic(!), save it in origingal, then trash n to see if it is a palindrome. But you never reset n for the next iteration.
The problem was extremely trivial, merely resetting rev, digit and n to meaningful values. The working program is as follows :
import java.util.Scanner;
class nextPalindrome {
public static void nextPalindromeGenerate(int n)
{
int flag=1;
int digit; //to store the mod value
int rev=0; //reverse of the number
int original; //dummy to store the original number
if(n<10)
{ System.out.println(n+1); //If number is single digit, next smallest palindrome is n+1
flag=0;
}
original=n;
while(flag!=0)
{ rev=0;digit=0;
n=++original;
while(n>0) //loop for reversing the number
{
digit=n%10;
rev=rev*10+digit;
n=n/10;
}
if(rev==original) //check if original equals the reverse(original)
{
System.out.println(original);
flag=0;
}
else flag=1;
}
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] palinList=new int[n];
for(int i=0;i<n;i++)
{
palinList[i]=sc.nextInt();;
}
for(int j=0;j<n;j++)
{
nextPalindromeGenerate(palinList[j]);
}
}
}
in this code i want to take no. of testcases by keyboard input and rest is the same problem. only what i am doing is like. if i take 2 test cases then it shud be print the result based on both cases after taking the complete input. For example: INPUT testcases : 2 //case1// 5(no of building) 7 5 2 11 1 //case2// 3(no. of building) 1 2 3 OUTPUT 7//OUTPUT FOR 1ST CASE// 0//OUTPUT FOR 2ND CASE// HOPE, NOW PROBLEM IS CLEAR
import java.util.Scanner;
public class Komal {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("enter the test cases");
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
System.out.println("total no of building");
int n=sc.nextInt();
int ar[]=new int[n];
for(int j=0;j<n;j++)
{
System.out.println("enter the heights");
ar[j]=sc.nextInt();
}
for(int j=1;j<ar.length;j++)
{int sum=0;
if(ar[0]<ar[i])
{
break;
}else
{
sum += (ar[0]-ar[i]);
}
System.out.println(sum);
}
}
}
}
Here is the complete code. Luckily i had my laptop running and this isn't a very difficult program.
public class TillGreater{
public static void main(String args[]){
int[] ar = {5,4,2,7,1};
int sum=0;
for(int i = 1 ; i < ar.length;i++){
if(ar[0]<ar[i]){
break;
}else{
sum = sum + (ar[0]-ar[i]);
}
}
System.out.println(sum);
}
}
try this:
public static int SumUntilBigger(int[] a)
{
int sum=0;
for(int i=1;i<a.length;i++)
{
if(a[i]<=a[0])
sum+=a[0]-a[i];
else
return sum;
}
return sum;//will reach this statement if all the elements are bigger than the first one
}
this compares each element with the first element and when the element is bigger it just return the sum and exits from method, if all elements are bigger than the first one just return the sum of all differences.
you can use it in main like this:
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter the size of the array");
int size=s.nextInt();
int[] a=new int[size];
System.out.println("enter the array values");
for(int i=0;i<size;i++)
a[i]=s.nextInt();
System.out.println("The differences sum : "+SumUntilBigger(a));
}
I am trying to write a program that repeatedly asks the user to supply scores (out of 10) on a test.It needs to continue until a negative value is supplied. Values higher than 10 should be ignored. I also calculated the average of the inputs. After the scores have been inputted, i need to use a single array to produce a table that automatically fills the test scores and the number of occurrences of the certain test score.
I wanted it to look something like this:
Score | # of Occurrences
0 3
1 2
2 4
3 5
4 6
and so on.. P
I am a beginner and this is my first question, so i am sorry if i made a mistake in posting the question or something.
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main()
{
Scanner kbReader= new Scanner (System.in);
int score[] = new int [10];//idk what im doing with these two arrays
int numofOcc []= new int [10];
int counter=0;
int sum=0;
for (int i=0;i<10;i++)// Instead of i<10... how would i make it so that it continues until a negative value is entered.
{
System.out.println("Enter score out of 10");
int input=kbReader.nextInt();
if (input>10)
{
System.out.println("Score must be out of 10");
}
else if (input<0)
{
System.out.println("Score must be out of 10");
break;
}
else
{
counter++;
sum+=input;
}
}
System.out.println("The mean score is " +(sum/counter));
}
}
You could use a do...while loop like this:
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main(String args[]) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [10];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 10 or negative to break.");
input=kbReader.nextInt();
if (input<0) {
break;
} else if (input>10) {
System.out.println("Score must be out of 10");
} else {
scores[input]++;
counter++;
sum+=input;
}
} while (input>0);
System.out.println("Score\t# of occur...");
for(int i =0; i<10; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}
The formatting can certainly be done better (without c-style tabs) but I don't remember the syntax at the moment.
I think what you need is a List Array! Create ArrayList from array
Think of it as a dynamic array, you don't need to specify the size of the array and it is expanded/made smaller automatically.
What you're missing is a while loop. Here is a nice way to loop through a Scanner for input. It also catches numbers greater than 10 and provides an error message:
public static void main() {
Scanner s = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int response = 0;
while (response >= 0) {
System.out.print("Enter score out of 10: ");
response = s.nextInt();
if (response > 10) {
System.out.println("Score must be out of 10.");
} else if (response >= 0) {
list.add(response);
}
}
// Do something with list
}