How to avoid running my program 10 times for 10 answers? - java

Once I run my program, it works, but after I input my first integer, it stops returning boolean values and just reads my input back to me. I want it to read multiple integers and tell me if they are prime numbers, how would I do that?
import java.util.Scanner;
public class PrimeCalculator{
public static boolean IsPrimeNumber(int Number){ //Tells me if it's a prime number
int Num = Number;
int x = 0;
for (int i=0;i<=Num;i++){
if(Num%(i+1)==0){
x++;
}
}
Boolean TwoFactors = (x==2);
return TwoFactors;
}
public static void main(String[] args){ // this prints out true/false depending on input
System.out.println("Enter a number");
Scanner Reader = new Scanner(System.in);
int IntRead = Reader.nextInt();
System.out.println(IsPrimeNumber(IntRead));
}
}

you should use do-while loop
int counter = 0;
do
{
counter++;
int IntRead = Reader.nextInt();
System.out.println(IsPrimeNumber(IntRead));
}
while(counter < 10);
or the for loop version:
for(int i = 0; i < 10; i++)
{
int IntRead = Reader.nextInt();
System.out.println(IsPrimeNumber(IntRead));
}
in your main method

Related

How to determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

Switched to BigInteger and progam does not run any more

So right I was creating a program that made palindromic numbers based on this project. My program would work for the smaller numbers, but integer can only compute a small amount of numbers, so I changed necessary integers to BigInteger(). After doing this Ive ran into some problems that Im not really sure of. Would anyone have any advice as to how to make this work?
public class Main {
public static final boolean DEBUG = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//gets the number from the console
int number = input.nextInt();
if(DEBUG) System.out.println("Got your number!");
if(DEBUG) System.out.println("Bout to makePalendrome!");
makePalendrome(number);
}
public static boolean isPalendrome(BigInteger number){
String numberString = number.toString();
for(int i = 0; i < numberString.length(); i++){
if(numberString.charAt(i) != numberString.charAt(numberString.length() - 1 - i)) return false;
}
return true;
}
public static void makePalendrome(int input){
int steps = 0;
BigInteger number = new BigInteger((input + ""));
if(isPalendrome(number)) printResult(input, steps, number);
while(!isPalendrome(number)){
String numberString = number.toString();
String reversed = "";
for(int i = 0; i < numberString.length(); i++){
reversed += numberString.charAt(numberString.length() - 1 - i);
}
BigInteger numReversed = new BigInteger(reversed);
number.add(numReversed);
steps++;
}
printResult(input, steps, number);
}
public static void printResult(int number, int steps, BigInteger palendrome){
System.out.printf("The number %d becomes palendromic after %d steps, and becomes the number: %d%n", number, steps, palendrome);
System.exit(0);
}
}
Your code goes into infinite loop while(!isPalendrome(number)) because,
number.add(numReversed);
this doesn't change the value of number. You need assign it back.
number= number.add(numReversed);

Stepping Through Array & Returning Matched/Non-Matched Value in Array Based on Search Term

In my searchForANumber method, I'm trying to display if a number is found within my array or not. The problem is, I'm using and if, else to determine if the searchValue matches a value in the array statement in my for loop, and when I do this, the last variable in the array is tested, and my returned value is based on only the final value. How can I make so that my return phrase is based on all elements in the array and not just the last one? Do I use a while, do-while, switch loop? Any help is appreciated.
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your minimum number: ");
int minNumber = input.nextInt();
System.out.println("Enter your maximum number: ");
int maxNumber = input.nextInt();
int[] array = new int[(maxNumber-minNumber)+1];
int[]readInArray = new int[maxNumber-minNumber+1];
readInArray=readNumbers(minNumber, maxNumber, array);
printNumbers(readInArray, minNumber);
searchForANumber(readInArray, minNumber);
sumNumbers(readInArray);
printBackward(readInArray);
}//end of main method
private static void printBackward(int[] readInArray) {
for (int i=(readInArray.length-1);i>0;i--){
System.out.print(readInArray[i] + " ");
}
}
private static void sumNumbers(int[] readInArray) {
int total = 0;
for (int i=0;i<readInArray.length;i++){
total = total + readInArray[i];
}
System.out.println(total);
}
private static void searchForANumber(int[] readInArray, int minNumber) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number to search for: ");
int searchValue = input.nextInt();
boolean returnValue = false;
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i])
returnValue=true;
break;
}// end of for
System.out.println(returnValue);
}
private static void printNumbers(int[] readInArray, int minNumber) {
for (int i = 0; i < readInArray.length;i++) {
System.out.print(readInArray[i] + " ");
minNumber++;
}
System.out.println(" ");
}
private static int[] readNumbers(int minNumber, int maxNumber, int[] array) {
for (int i = 0; i < array.length;i++) {// input grades for each students
array[i]=minNumber;
minNumber++;
} // end of for loop
return array;
} // end of readArray method
}//end of class
you can do it in two ways.
make your method searchForANumber return boolean.
private static boolean searchForANumber(int[] readInArray, int minNumber) {
//before for loop
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i])
return true;
}
return false;
}
use break and a boolean
private static void searchForANumber(int[] readInArray, int minNumber) {
//before for loop
boolean found = false;
for (int i = 0; i < readInArray.length;i++) {
if (searchValue == readInArray[i]){
found = true;
break;
}
}
if(found)
System.out.println("Found");
else
System.out.println("Not Found");
}

Loop to validate user input

I am fairly new to Java and I am trying to write a small program that asks a user to enter 3 integers between 1-10, stores them in an array and then adds up the integers and tells the user the answer. I have written this so far and it works:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 3 numbers in the range 1 to 10: ");
for (int i = 0; i < numArr.length; i++) {
numArr[i] = keyboard.nextInt();
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My problem is I am also meant to validate the input as in if they enter a double, a string or a number outside the 1-10 range. I have tried a while loop but I just cannot get the program to work, below is what I have so far. If I take out the first while loop the second one works i.e. it checks if it is an integer:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < numArr.length; i++) {
//check if between 1 and 10
while (i > 10 || i < 1) {
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt()) {
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
numArr[i] = keyboard.nextInt();
}
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My question is how do I get it to check if it is an integer and if it is the range 1-10?
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);
for(int i=0; i<numArr.length; i++)
{
//check if between 1 and 10
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
x = keyboard.nextInt();
if(x>0 && x<=10)
numArr[i]=x;
else{
System.out.println("Retry Enter a number in the range 1 to 10:");
i--;
}
}
for (int counter=0; counter<numArr.length; counter++)
{
sum+=numArr[counter];
}
System.out.println("The sum of these numbers is "+sum);
}
}
To check simple use Integer.parseInt() and catch the NumberFormatException (together with Scanner.next()).
Once format is correct you can do an int comparison (i>0 && i<11).
I suggest you to use NumberUtils under org.apache.commons.lang.math
It has isDigits method to check whether given string contains only digits or not:
if (NumberUtils.isDigits(str) && NumberUtils.toInt(str) < 10) {
// your requirement
}
Note that toInt returns zero for big numbers!
Maybe for just this reason adding a whole library seems unnecessary but for bigger projects you will need such libraries like Apache Commons and Guava
You can wrap the System in into a BufferedReader to read whatever the user has to input, then check if its an 'int' and repeat input from user.
I have modified your code a little bit to make it work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Feb11a {
public static void main(String[] args) throws NumberFormatException, IOException
// You may want to handle the Exceptions when calling the getInt function
{
Feb11a tester = new Feb11a();
tester.perform();
}
public void perform() throws NumberFormatException, IOException
{
int[] numArr = new int[3];
int sum = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < numArr.length; i++)
{
int anInteger = -1;
do
{
// First get input from user.
System.out.println("Enter a number in the range 1 to 10: ");
anInteger = getInt(in);
} while (anInteger > 10 || anInteger < 1); // then check for repeat condition. Not between 1 and 10.
numArr[i] = anInteger; // set the number into the array.
}
for (int counter = 0; counter < numArr.length; counter++)
{
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
public int getInt(BufferedReader br) throws NumberFormatException, IOException
{
String str = br.readLine();
int toReturn = Integer.parseInt(str);
return toReturn;
}
}

Java. Program crashes when entering any odd number with even numbers

The program is meant to count how many even numbers that have been inputted by the user. However, when the user inputs even numbers along with odd numbers the program crashes. But when the user enters all odd or even the program works fine. I can't seem to find the error either as the error message returns:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AllEven.getEven(AllEven.java:52)
at AllEven.read(AllEven.java:41)
at AllEven.main(AllEven.java:10)
Java Result: 1
The code for the program is below and any help would be greatly appreciated
import java.util.Scanner;
public class AllEven
{
private static int evenCount;
private static int[] evenArray;
private static int count;
public static void main (String args [])
{
read();//LINE 10
}
public static int [] read ()
{
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the size of the array");
int arrayIn = scanner.nextInt();
if (arrayIn == 0)
{
System.out.println("No Array");
}
else
{
System.out.println("------------------");
}
int userArray [] = new int [arrayIn];
for (int i = 0; i < userArray.length; i++)
{
System.out.println("Please enter a value for position: " + i);
arrayIn = scanner.nextInt();
userArray[i] = arrayIn;
if (arrayIn % 2 == 0)
{
evenCount++;
}
}
getEven(userArray);//LINE 41
return userArray;
}
public static int [] getEven(int[] userArray)
{
if (evenCount > 0)
{
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i]; //LINE 52
count++;
}
print (evenArray);
}
else
{
System.out.println("No even numbers found");
}
return evenArray;
}
public static void print (int [] evenArray)
{
System.out.println();
System.out.println("Even numbers in the array are: ");
for (int i = 0; i < evenArray.length; i++)
{
System.out.println(evenArray[i]);
}
}
}//endprogram
userArray.length is not always equal to evenCount
problematic code
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i];
Your even count is less than the size of the user array, yet you are indexing into the even array count times. You are incrementing count each time you get an item from the input array, and the input array will always be larger than the even array if you enter both even and odd numbers.

Categories