I'm trying to write a for loop that will take a user input, regardless if it is positive or negative, display the input numbers and then display the sum of the numbers. I can get as far as displaying the numbers, but I am having a hard time getting the summing right.
import java.util.Scanner;
public class DisplayandSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Variable declaration
int size;
int Num1;
int count = 0; //LCV
int sum = 0; //Sum of inputs
String newNum; // Declared string for user input
System.out.println("Please enter an integers and press enter.");
newNum = input.next();
Num1 = Integer.parseInt(newNum);
size = newNum.length();
System.out.print("These are your numbers: ");
if (Num1 > 0) //If number is positive
{
for (count = 0; count <= (size - 1); count++) {
System.out.print(newNum.charAt(count) + "");
}
} else if (Num1 < 0) // If number is negative
{
System.out.print("-");
for (Num1 = 1; Num1 <= (size - 1); count++) {
System.out.print(newNum.charAt(count) + "");
}
}
if (Num1 > 0) //If positive sum
{
for (count = 0; count < (size - 1); count++) {
sum = sum + count;
}
} else if (Num1 < 0) // If negative sum
{
for (Num1 = size; Num1 > 2; Num1--) {
Num1 = Math.abs(Num1);
}
sum = sum + Num1 % 10;
Num1 = Num1 / 10;
}
sum = sum + (0 - Num1);
System.out.println("\nand the sum of your digits is: " + sum);
}
}
When you say "sum of the numbers", I assume you actually mean "sum of the digits"?
Your code is more complicated than it needs to be.
// Variable declaration
int sum = 0; //Sum of inputs
String newNum; // Declared string for user input
System.out.println("Please enter an integer and press enter.");
newNum = input.next();
size = newNum.length();
System.out.print("These are your numbers: ");
for (count = 0; count < size; count++)
{
char ch = newNum.charAt(count);
if (Character.isDigit(ch) {
System.out.print(ch);
sum += (ch - '0');
}
}
System.out.println("\nand the sum of your digits is: " + sum);
Related
I want to count the number of each prime factor of an integer then print the highest number of counts. e.g. 720 = 2^4 * 3^2 * 5^1. so I want to print Maximum Number of Time occurrence = 4 and the number is 2. I try to use Integer.max(), but that didn't work.
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
int num;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
num = in.nextInt();
TreeMap<Integer, Integer> factors = new TreeMap<>();
for (int i =2; i < num; i++){
int count = 0;
while (num%i == 0){
System.out.println(i + " ");
num = num/i;
count ++;
}
if (count > 0){
factors.put(i, count);
}
}
if (num > 2){
System.out.println(num + " ");
factors.put(num, 1);
}
System.out.println( "-------------" );
for( Integer factor : factors.keySet() ){
System.out.println( factor + "^" + factors.get( factor ) );
}
}
}
If you just want the prime which occurs most then you can just check after each prime has been tested. For this, a map is not really necessary. Note that multiple primes may occur the same number of times. If there is a tie, this only saves the first one encountered.
int num;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
num = in.nextInt();
int primeFactor = 0;
int count = 0;
int maxCount = 0;
int inc = 1; // initial increment.
int i = 2; // intitial prime
while (num > 1) {
count = 0;
while (num%i == 0) {
num = num/i;
count++;
}
// here check current count against maxCount and
// alter if required.
if (count > maxCount) {
maxCount = count;
primeFactor = i;
}
if (count > 0) {
System.out.printf("Prime = %d, count = %d%n", i, count);
}
i+=inc; // bump by 1 to get 3 and then
inc = 2; // start incrementing by 2
}
// and print the results.
System.out.println("First highest occuring prime = " + primeFactor);
System.out.println("MaxCount = " + maxCount);
I'm required to code a program that, using a do-while loop, will print 25 prime numbers on a new line. I have everything figured out on it, except for printing out exactly 25 numbers. However, the program is only giving me prime numbers up to the number 25, not 25 prime numbers.
I set a variable "count" to increase every time the loop is run, with the same result. Here's my code (sorry for the length, I would shorten it but I'm worried the whole thing might be messed up):
int firstNum;
int secondNum = 1;
int num;
int count = 0;
System.out.println("Sample run: \n\nPrime numbers");
do {
num = 0;
firstNum = 2;
while (firstNum <= secondNum / 2) {
if (secondNum % firstNum == 0) {
num++;
count++;
break;
}
firstNum++;
}
if (num == 0 && secondNum != 1) {
count++;
System.out.print("\n" + secondNum + " ");
}
secondNum++;
} while(count < 25);
}
}
You need to remove count++; inside first if block to get 25 prime numbers.
Updated Code:
int firstNum;
int secondNum = 1;
int num;
int count = 0;
System.out.println("Sample run: \n\nPrime numbers");
do {
num = 0;
firstNum = 2;
while (firstNum <= secondNum / 2) {
if (secondNum % firstNum == 0) {
num++;
// count++; // <--- Remove this.
break;
}
firstNum++;
}
if (num == 0 && secondNum != 1) {
count++;
System.out.println(secondNum); // Use println() for new line.
}
secondNum++;
} while(count < 25);
}
Here's an example showing how you can iterate through some loop a fixed number of times, and separately calculate your next prime number. I'm clearly not calculating any primes here, just showing how you can separate the two concerns of "loop quantity" and "determine the next prime".
public static void main(String[] args) {
int prime = 0;
for (int k = 1; k <= 25; k++) {
prime = findPrimeAfter(prime);
System.out.println("#" + k + ": " + prime);
}
}
private static int findPrimeAfter(int lastPrime) {
// TODO: find the next prime that is greater than "lastPrime"
return 0;
}
This is the instructions.
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That's value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
This is what I came up so far. It's all good except I need to enter a letter instead of a negative number to quit scanning. I have tried (if( < 0) things) but those didn't work.
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
This is the result.
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
I only need the asterisks. Everything else that is being printed is just for checking purposes.
You can try this:
while(in.hasNextInt()) {
int num =in.nextInt();
if(num <0){
break;
}
else{
arr[currentSize] = num;
currentSize++;
}
}
I need to write a code that takes the users input of numbers and adds them, displays the amount of positives, negatives, zeroes, and the count of the amount of numbers inputted once the user enters the letter 'e'. Im not sure if what i have so far is the correct path (it doesn't compile yet) but this is what i have so far:
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int negative = 0;
int positive = 0;
int zeroes = 0;
int sum = 0;
int count = 0;
do{
System.out.print("Enter a float or 'e' to exit");
int num = input.nextInt();
if(num < 0){
sum += num;
count++;
negative++;
}
if (num > 0){
sum += num;
count++;
positive++;
}
if (num == 0){
sum += num;
count++;
zeroes++;
if (num = e){
System.out.print(sum + count + zeroes + positive + negative);
}
}
} while(true);
}
}
You could do something like this. Please note comments where I've tried to improve:
do{
System.out.print("Enter a float or 'e' to exit");
String entered = input.nextLine();
if("e".equals(entered)){
//print stuff
break;
}else{
int num;
try {
num = Integer.parseInt(entered);
} catch (NumberFormatException e) {
System.out.println("Not a number nor e");
continue; // re-do the loop
}
if(num < 0){//; ends the line, not to be used after if condition
sum += num;
count++;
negative++;
}else if (num > 0){ // num bcan be >0 only if its not <0, so use else
sum += num;
count++;
positive++;
}else{//similar to comment above
sum += num;
count++;
zeroes++;
}
}
} while(true);
my problem is the following. If I input number 2, the code counts it as an odd number.
Remainder for 2 / 2 = 0 so the error doesn't make sense.
Below is the program:
import java.util.Scanner;
public class Ohjelma {
public static void main(String[] args) {
// Tänne voit kirjoittaa ohjelmakoodia. Ohjelmasi voit ajaa
// valitsemalla menusta Run->Run File tai painamalla Shift+F6
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int number = Integer.parseInt(reader.nextLine());
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
while (number != -1) {
System.out.println("Type numbers: ");
sum = sum + number;
number = Integer.parseInt(reader.nextLine());
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + many);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
The main problem is that for the critical part of your program it largely ignores the first input, apart from adding it to the running sum. You want to recast it like this:
Scanner reader = new Scanner(System.in);
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
do {
System.out.println("Type numbers: ");
number = Integer.parseInt(reader.nextLine());
if (number == -1)
break;
sum = sum + number;
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
} while (true);
This will certainly processes even and odd numbers correctly.
Your code reads the second line of input into number before it checks whether number is odd ... and -1 is odd.