How to initiate Min/Max loops with scanner - java

In this problem, I need to ask the user to input the number of integers they will put in. Then, they will manually input each number. Finally, the program counts the sum and max of all even inputs.
I am having trouble with initiating the value. If I set them to zero, there would be an issue if all the numbers were negative even numbers.
import java.util.*;
public class Exercise07 {
public static void main(String[] args) {
Scanner thing = new Scanner(System.in);
evenSumMax(thing);
}
private static void evenSumMax(Scanner stuff) {
System.out.print("How many integers?");
int times = stuff.nextInt();
int evenSum = 0;
int evenMax = 0;
System.out.println("Number 1 : ");
int value = stuff.nextInt();
if (value % 2 == 0) {
evenSum += value;
evenMax = value;
}
for (int i = 2 ; i <= times; i++) {
System.out.print("Number " + i + " : ");
value = stuff.nextInt();
if (value % 2 == 0) { // if even
evenSum += value;
if (evenMax < value) {
evenMax = value;
}
}
}
System.out.println("Even sum = " + evenSum + ", even max = " + evenMax);
}
}

Set evenMax to the minimum possible number Integer.MIN_VALUE

Related

How to find factorial and show result of counting in console?

public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6

Extending my program with another while loop Java

Firstly, i'm very new to java, so excuse the mess of the code below.
My current program takes input from StdIn and prints out the highest and lowest values entered.
Can this be extended to ask the useר again if they entered an integer that isn't positive? I'm almost certain that a while loop can do the trick, but not sure if one executed with my current code. Once again, i'm very new and come from a music background, so my logical sense isn't the best.
public class PositiveIntegers
{
public static void main(String[] args)
{
do {
StdOut.println("Enter your integers:");
} while (StdIn.isEmpty());
int max = StdIn.readInt();
int min = max;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
if (value > max) max = value;
if (value < min) min = value;
}
do {
StdOut.println("Maximum = " + max + ", Minimum = " + min);
return;
} while (StdIn.readInt() > 0);
}
}
Cheers
You can do it by just adding a single if statement to check if the number given is negative, then print the message to add it again.
Check the ENHANCED code below:
public class PositiveIntegers
{
public static void main(String[] args)
{
StdOut.println("Enter your integers:");
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
// Adding the if-statement here to check if number is negative.
if(value < 0){
StdOut.println("You entered negative number, try positive numbers.");
// just reset the max and min variables..
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
continue;
}
if (value > max) max = value;
if (value < min) min = value;
}
StdOut.println("Maximum = " + max + ", Minimum = " + min);
}
}
First of all you don't need this many loops in your program. Take the user input in while loop and then print that number outside of loop.
Remember to use try-catch for error handling for user input.
Try this way :
try{
do {
StdOut.println("Enter your integers:");
} while (StdIn.isEmpty() && StdIn.readInt() < 0);
}catch(Exception ex){
StdOut.println("Error while taking user input !");
}
A quick answer to this would be
public class PositiveIntegers {
public static void main(String[] args) {
do {
StdOut.println("Enter your integers:");
} while (StdIn.isEmpty());
int max = StdIn.readInt();
int min = max;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
if (value < 0) {
StdOut.println("Please enter a positive integer");
} else {
if (value > max) max = value;
if (value < min) min = value;
}
}
do {
StdOut.println("Maximum = " + max + ", Minimum = " + min);
return;
} while (StdIn.readInt() > 0);
}
}
I made sure to change as little as possible, but this should give you the result you are looking for.

Search and count for single random number in array of 20 integers

I have a program that produces an array of 20 integers. Then produces one single random number in the same span. What I am attempting to do is search the array of 20 integers and count how many times this single random number occurs and print the result or if the integer is not present to display "not present". I feel like I am so close but I am getting an incorrect count for the random integer. Thank you in advance. Perimeteres for the search method:
• The method datatype is void because no data will be returned.
• It will have three parameters – the integer array, the size of the array, and the value it will be searching for in the array.
• It will search through the array and count how many times the value was found.
• It will then either print out how many times the value was found or that the value was not found.
My code and sorry if it is not indented properly, still figuring this out:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.println("Single # is: " + (RND_GEN.nextInt(10) + 1));
}
public void searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Single #" + numSearch + " was not found!");
} else {
System.out.println("Single # "+ numSearch + " was found " + count + " times");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numSearch = RND_GEN.nextInt(10) + 1;
searchArray(numbers, numSearch);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
You're almost there. You've already done the work of creating a search method, you're just not calling it. Modify your searchArray method to print out the number of occurrences at the end since it's a requirement that you do.
public void searchArray(int[] randomNumbers, int numSearch) {
int count = 0;
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Single #" + numSearch + " was not found!");
} else {
System.out.println("Single # "+ numSearch + " was found " + count + " times");
}
}
You can then call it like so:
searchArray(numbers, numSearch);
You've made a little mistake in your run() method`:
int numSearch = RND_GEN.nextInt(10) + 1;
System.out.println("Number found this many times: "+ numSearch);
This gives you a random number from one to 10, but you want to count the actual apperence of numbers[0], so you have to use your searchArray() method.
Therefore you have to add a return type and return count:
public int searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
for(int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
return count;
}
Then you get your count by:
int numSearch = searchArray(numbers, numbers[0]);
#Dimi So something like this:
public int searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
for(int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
int numSearch = searchArray(numbers, numbers[0]);
System.out.println("Single # was found: "+ numSearch+" times");

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.

Binary to Decimal Java converter

I am creating a code that allows you to convert a binary number to a decimal number and vice versa. I have created a code that converts decimal to binary but can not workout how to implement the binary to decimal aspect.
My code for decimal to binary is below:
import java.util.*;
public class decimalToBinaryTest
{
public static void main (String [] args)
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
n=in.nextInt();
if(n < 0)
{
System.out.println("Not a positive interger");
}
else
{
System.out.print("Convert to binary is: ");
binaryform(n);
}
}
private static Object binaryform(int number)
{
int remainder;
if(number <= 1)
{
System.out.print(number);
return " ";
}
remainder= number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
An explanation to how the binary to decimal code work would help as well.
I have tried the method of the least significant digit*1 then the next least *1*2 then *1*2*2 but can not get it to work.
Thank you #korhner I used your number system with arrays and if statements.
This is my working code:
import java.util.*;
public class binaryToDecimalConvertor
{
public static void main (String [] args)
{
int [] positionNumsArr= {1,2,4,8,16,32,64,128};
int[] numberSplit = new int [8];
Scanner scanNum = new Scanner(System.in);
int count1=0;
int decimalValue=0;
System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
int number = scanNum.nextInt();
while (number > 0)
{
numberSplit[count1]=( number % 10);
if(numberSplit[count1]!=1 && numberSplit[count1] !=0)
{
System.out.println("Was not made of only \"1\" or \"0\" The program will now restart");
main(null);
}
count1++;
number = number / 10;
}
for(int count2 = 0;count2<8;count2++)
{
if(numberSplit[count2]==1)
{
decimalValue=decimalValue+positionNumsArr[count2];
}
}
System.out.print(decimalValue);
}
}
sample:
00000100
0 - 1
0 - 2
1 - 4
0 - 8
0 - 16
0 - 32
0 - 64
0 - 128
Sum values with bit 1 = 4
Good luck!
int decimal = Integer.parseInt("101101101010111", 2);
or if you prefer to doit your self
double output=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)== '1')
output=output + Math.pow(2,str.length()-1-i);
}
Here is a program which does that.
Make sure the integers you give to int and not too large.
import java.util.Scanner;
public class DecimalBinaryProgram {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true){
System.out.println("Enter integer in decimal form (or # to quit):");
String s1 = in.nextLine();
if ("#".equalsIgnoreCase(s1.trim())){
break;
}
System.out.println(decimalToBinary(s1));
System.out.println("Enter integer in binary form (or # to quit):");
String s2 = in.nextLine();
if ("#".equalsIgnoreCase(s2.trim())){
break;
}
System.out.println(binaryToDecimal(s2));
}
}
private static String decimalToBinary(String s){
int n = Integer.parseInt(s, 10);
StringBuilder sb = new StringBuilder();
if (n==0) return "0";
int d = 0;
while (n > 0){
d = n % 2;
n /= 2;
sb.append(d);
}
sb = sb.reverse();
return sb.toString();
}
private static String binaryToDecimal(String s){
int degree = 1;
int n = 0;
for (int k=s.length()-1; k>=0; k--){
n += degree * (s.charAt(k) - '0');
degree *= 2;
}
return n + "";
}
}
Of course for this method binaryToDecimal you can just do:
private static String binaryToDecimal(String s){
int n = Integer.parseInt(s, 2);
return n + "";
}
but I wanted to illustrate how you can do that explicitly.
do you want this?
private double dec(String s, int i) {
if (s.length() == 1) return s.equals("1") ? Math.pow(2, i) : 0;
else return (s.equals("1") ? Math.pow(2, i) : 0) + dec(s.substring(0, s.length() - 1), i - 1);
}
dec("101011101",0);
This is a version of a binary to decimal converter. I have used plenty of comments also. Just taught I would like to share it. Hope it is of some use to somebody.
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine(); // store input from user
int[] powers = new int[16]; // contains powers of 2
int powersIndex = 0; // keep track of the index
int decimal = 0; // will contain decimals
boolean isCorrect = true; // flag if incorrect input
// populate the powers array with powers of 2
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
// if 1 add to decimal to calculate
if(binary.charAt(i) == '1')
decimal = decimal + powers[powersIndex]; // calc the decimal
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false; // flag the wrong input
break; // break from loop due to wrong input
} // else if
// keeps track of which power we are on
powersIndex++; // counts from zero up to combat the loop counting down to zero
} // for
if(isCorrect) // print decimal output
System.out.println(binary + " converted to base 10 is: " + decimal);
else // print incorrect input message
System.out.println("Wrong input! It is binary... 0 and 1's like.....!");
} // main
} // BinaryToDecimal
I've written a converter that accepts both strings and ints.
public class Main {
public static void main(String[] args) {
int binInt = 10110111;
String binString = "10110111";
BinaryConverter convertedInt = new BinaryConverter(binInt);
BinaryConverter convertedString = new BinaryConverter(binString);
System.out.println("Binary as an int, to decimal: " + convertedInt.getDecimal());
System.out.println("Binary as a string, to decimal: " + convertedString.getDecimal());
}
}
public class BinaryConverter {
private final int base = 2;
private int binaryInt;
private String binaryString;
private int convertedBinaryInt;
public BinaryConverter(int b) {
binaryInt = b;
convertedBinaryInt = Integer.parseInt(Integer.toString(binaryInt), base);
}
public BinaryConverter(String s) {
binaryString = s;
convertedBinaryInt = Integer.parseInt(binaryString, base);
}
public int getDecimal() {
return convertedBinaryInt;
}
}
public static void main(String[] args)
{
System.out.print("Enter a binary number: ");
Scanner input = new Scanner(System.in);
long num = input.nextLong();
long reverseNum = 0;
int decimal = 0;
int i = 0;
while (num != 0)
{
reverseNum = reverseNum * 10;
reverseNum = num % 10;
decimal = (int) (reverseNum * Math.pow(2, i)) + decimal;
num = num / 10;
i++;
}
System.out.println(decimal);
}

Categories