How to add the numbers displayed - java

Now how do i add the numbers displayed and print them ?
i got how to display them but cant figure out how to add the number please would be a great help for my project
import java.util.Scanner;
public class ReadNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: \n");
int n = sc.nextInt();
int i = 0;
while(i <= n){
System.out.print(i);
if(i == n){
System.out.print("=");
}
else{
System.out.print("+");
}
i++;
}
}
}

You need another variable for the running total. To be more concise, use a for loop, and handle the i == n outside of the loop.
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: \n");
int n = sc.nextInt();
int i = 0, sum = n;
for (int i = 0; i < n; i++) {
sum += i;
System.out.print(i + "+");
}
System.out.println(n + "=" + sum);

You can create another variable int sum to update the sum of all i's with each loop iteration:
import java.util.Scanner;
public class ReadNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: \n");
int n = sc.nextInt();
int i = 0;
int sum = 0; // Create a sum variable
while(i <= n){
System.out.print(i);
sum+=i; // Add `i` to sum
if(i == n){
System.out.print("=");
System.out.println(sum); // Display `sum` after loops finish
}
else{
System.out.print("+");
}
i++;
}
}
}

Related

count of odd elements of left side and right side please modify my code without exceeding the time limit

My code is O(n^2), please to decrease as O(n).
My question is count of the left side odd numbers and right side odd numbers. If it is equal on the bothsides(left and right) then print the respecive element other wise print the "-1". my code logic was correct it executing the normal text cases, but it was failing to execute the large value of text cases.It shows the error as "time exceeded".It was exceeding the timelimit of the compiler.i want to decrease the time limit of my code.
example: my input is 4 1 4 3 8 and my output:-1 4 -1 -1
example 2: my input is 6 1 3 4 8 5 7 and my output: -1 -1 4 8 -1 -1
enter code here
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int temp = 0;
int count = 0;
int flag = 0;
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
temp = a[i];
for (int j = 0; j < i; j++) {
if (a[j] % 2 != 0) {
count++;
}
}
for (int k = i + 1; k < n; k++) {
if (a[k] % 2 != 0) {
flag++;
}
}
if (count == flag) {
System.out.print(temp + " ");
} else {
System.out.print("-1 ");
}
count = 0;
flag = 0;
}
}
I have not tested it yet but it should work.
Your algorithm is O(n^2) and this one is O(n).
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
}
int total = 0;
for(int i=0;i<n;i++) {
if(a[j]%2!=0) {
total++;
}
}
int leftTotal = 0;
for(int i=0;i<n;i++) {
int k = a[i];
if (k%2!=0) {
leftTotal++;
}
if (leftTotal = (total-leftTotal)) {
System.out.println(k);
} else {
System.out.println(k);
}
}
}
enter code here
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n],flag=0,count=0;
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
if(a[i]%2!=0)
count++;
}
for(int i=0;i<n;i++) {
if(a[i]%2!=0)
count--;
if(flag==count)
System.out.print(a[i]+" ");
else
System.out.print("-1 ");
if(a[i]%2!=0)
flag++;
}
}
}

Given number n, find the factorial of that number

Output is wrong it just multiplying second number with itself.
import java.util.Scanner;
public class trybew {
void factorial(int n) {
long fact = 1;
for(int i=1; i<=n; i++) {
fact *= n;
System.out.println(" "+fact);
}
}
public static void main(String[] args) {
int cnt;
trybew f1= new trybew();
Scanner s= new Scanner(System.in);
System.out.println("Enter Test case ");
cnt=s.nextInt();
int n[]= new int[cnt];
for(int i=0; i<cnt; i++) {
System.out.println("ENter NO:: ");
n[i]=s.nextInt();
}
for(int i=0; i<cnt; i++)
f1.factorial(n[i]);
}
}
void factorial(int n) {
long fact = 1;
for(int i=n; i>=1; i--)
fact *= i;
System.out.println(" "+fact);
}
Your mistake is with your code fact *= n; . You are supposed to use i here.
Change
fact *= n;
To
fact *= i;
Modified code :-
import java.util.Scanner;
public class trybew {
void factorial(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i; // not *=n
System.out.println(" " + fact);
}
}
public static void trybew(String[] args) {
int cnt;
trybew f1 = new trybew();
Scanner s = new Scanner(System.in);
System.out.println("Enter Test case ");
cnt = s.nextInt();
int n[] = new int[cnt];
for (int i = 0; i < cnt; i++) {
System.out.println("ENter NO:: ");
n[i] = s.nextInt();
}
for (int i = 0; i < cnt; i++)
f1.factorial(n[i]);
}
}
Output :-
Enter Test case
2
ENter NO::
4
ENter NO::
5
1
2
6
24
1
2
6
24
120
It is better to use System.out.println(" " + fact); outside the for-loop in function void factorial(int n) .

Average, minimum, maximum

so in my program is where the user enters list of numbers one at a time, and when I would end the list numbers with the "end" statement which is set to -1, and once I do that I get my average, and maximum, and minimum, my problem is that when I do get the minimum output it would be -1 everytime, I'm having trouble to remove the -1 from the array, any ideas???
import java.util.Scanner; //import scanner to user scanner tool
public class Average { //creating public class
public static void main(String[]args) { //creating public static main
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20]; //creating 20 count array
double sum = 0;
int count = 0;
double average;
int end = -1;
for(int i = 0; i<numbers.length; i++) {
System.out.print("Enter a number: ");
numbers[i] = input.nextDouble();
if(numbers[i]== end) {
break;
}
sum+= numbers[i];
count++;
}
// gets average from user input of numbers
average = sum/count;
System.out.println("Average is: " + average);
double max = maxim(numbers);
System.out.println("Max: " + max);
double min = minim(numbers);
System.out.println("Min: " + min);
}
//method for finding out maximum number from user input
public static double maxim(double[] array) {
double maxNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] > maxNum) {
maxNum = array[i];
}
}
return maxNum;
}
//method for finding out minimum number from user input
public static double minim(double[] array) {
double minNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] < minNum && array[i]!=-1) {
minNum = array[i];
}
}
return minNum;
}
}
You need to docouple part of code that responsible for reading user input from code that compute statistics. And for remove -1 from resulting array you need simple don't put this value to result. When user input random number first check if it is not -1, and after that put it in result. Something like that:
import java.util.Scanner;
public class Average {
public static void main(String[]args) { //creating public static main
double[] numbers = readInputNumbers();
System.out.println("Average is: " + average(numbers));
System.out.println("Max: " + max(numbers));
System.out.println("Min: " + min(numbers));
}
public double[] readInputNumbers() {
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20];
final int endInput = -1;
for(int i = 0; i < numbers.length; i++) {
System.out.print("Enter a number: ");
double nextNumber = input.nextDouble();
if(nextNumber == endInput) {
break;
} else {
numbers[i] = nextNumber;
}
}
return numbers;
}
public static double max(double[] array) {
double maxNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] > maxNum) {
maxNum = array[i];
}
}
return maxNum;
}
public static double min(double[] array) {
double minNum = array[0];
for(int i = 1; i<array.length; i++) {
if(array[i] < minNum && array[i]!=-1) {
minNum = array[i];
}
}
return minNum;
}
public static double average(double[] numbers) {
double sum = 0;
for(int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
return sum / numbers.length;
}
}
In jdk since 8 version your could be simplify this task like this:
import java.util.Scanner;
import java.util.stream.*;
public class Average {
public static void main(String[]args) { //creating public static main
double[] numbers = readInputNumbers();
DoubleSummaryStatistics statistics = DoubleStream.of(numbers).summaryStatistics();
System.out.println("Average is: " + statistics.getAverage()));
System.out.println("Max: " + statistics.getMax());
System.out.println("Min: " + statistics.getMin());
}
public double[] readInputNumbers() {
Scanner input = new Scanner(System.in); //creating scanner input to grab user input
System.out.println("Please enter a list of numbers, entering -1 to end the list: ");
double[] numbers = new double[20];
final int endInput = -1;
for(int i = 0; i < numbers.length; i++) {
System.out.print("Enter a number: ");
double nextNumber = input.nextDouble();
if(nextNumber == endInput) {
break;
} else {
numbers[i] = nextNumber;
}
}
return numbers;
}
}
You could take the input into a temp variables and store it in the array only if it isn't the end flag (-1). E.g.:
for(int i = 0; i<numbers.length; i++) {
System.out.print("Enter a number: ");
double temp = input.nextDouble();
if(temp == end) {
break;
}
numbers[i] = temp;
sum += numbers[i];
count++;
}

How can I find the largest value n in this Collatz Conjecture code I created?

I am a beginner coder, and I am trying to find the largest value of n, but I am having trouble. I have tried to use a for loop to search each element of the array I created, but the code returns 0 every time. Is this method correct? I have tried entering the values of n into an array, but I am not sure if this is the correct method to go about solving this goal.
import java.util.*;
public class CollatzConjecture {
private static int max;
public CollatzConjecture(int maximum){
int max=maximum;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while(n>1)
{
if(n%2 == 0)
{n = n/2;}
else
{n = 3*n + 1;}
System.out.println(n + " ");
count++;
arr.add(n);
arr.get(n);
}
for(int i = 0; i<arr.size()-1; i++)
{
if(arr.get(i) > max)
{
int max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Terminated after " + count + " steps");
}
}
Made some changes, but here you go:
public class CollatzConjecture {
private int max;
public CollatzConjecture() {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while (n > 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
System.out.println(n);
count++;
arr.add(n);
}
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) > max) {
this.max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Largest value of n: " + this.max);
System.out.println("Terminated after " + count + " steps");
scan.close();
}
public static void main(String[] args) {
new CollatzConjecture();
}
}
So if I understand your question correctly, you are just trying to find the maximum value in an array? If so:
int max = arr.stream().max(Integer::compare).get();
or
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++)
max = Integer.max(max, arr.get(i));

program that reads in ten numbers and displays the number of distinct numbers and the distinct numbers separated by one space

I know that this question has been asked before, but not in the the format that I'm writing my code.. Just started taking java classes so I am not familiar with any complex java.. the code below consists of basically all the java I know. Please help! Thanks in advance.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
distinctArray[0] = inputList[0];
for (int i = 1; i < inputList.length; i++)
{
for (int j = 0; j < inputList.length; j++)
{
if (inputList[i] == inputList[j])
{
counter++;
continue;
}
else
{
distinctArray[i] = inputList[i];
}
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<distinctArray.length; x++)
{
if (distinctArray[x] != 0)
System.out.print(distinctArray[x] + " ");
}
}
}
Your logic in the "processing" block seemed off. I modified it to check the current number (outer loop) to all of the known numbers (inner loop). If no match was found, it is appended to the list of known numbers and the count is incremented.
I also modified the "output" code to print the first counter numbers from the list of known numbers. Values past that index are uninitialized.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
for (int i = 0; i < inputList.length; i++)
{
boolean found = false;
for (int j = 0; j < counter; j++)
{
if (inputList[i] == distinctArray[j])
{
found = true;
break;
}
}
if (!found)
{
distinctArray[counter++] = inputList[i];
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<counter; x++)
{
System.out.print(distinctArray[x] + " ");
}
}
}

Categories