How to reverse a number in java in a user generated program - java

My teacher wants me to be able to ask this question an infinite number of times until the user decides to terminate it themselves. This works for the most part however, If I input a number too big I get an error because its a int data type. I have tried longs and doubles to but for some reason I get answers like infinity or the negative of the numbers. How do I fix this so I can put in as long of a number that I want and still get the positive integer reversal? Thank You so Much. Please keep it simple. This is literally my 5th computer class in my life.
import java.util.Scanner;
public class reverseInt3
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int number;
int reverse = 0;
int number2;
int reverse2 = 0;
char repeat;
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
System.out.println("Reverse of entered number is "+reverse);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
while( repeat == 'Y' || repeat == 'y')
{
System.out.println("Please enter your new set of numbers");
number2 = keyboard.nextInt();
keyboard.nextLine();
while( number2 != 0 )
{
reverse2 = reverse2 * 10;
reverse2 = reverse2 + number2%10;
number2 = number2/10;
}
System.out.println("The reverse of entered number is "+reverse2);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
}
}
}

First let's talk about your problem:
If the user input goes beyond the bound of int, long or double your program provides a negative reverse.
That's because when you try to store a very big number in smaller capacity variable, an overflow happens and after that your stored number is not valid and if you try to print it you will get a negative number instead which is not the exact negative for the user input.
If you want to overcome this, one way is to store the user input in a String variable. Then you can check if the input (which is stored in a String type variable) is really an integer or not, and if it was, you can reverse it.
I don't think this is actually what your teacher want you to do. Because the algorithm of reversing an integer (you implemented) can not be used to reverse such a big integer stored in a String variable. So I think your code is good and get it easy because probably your teacher don't expect you to maintain very big integers now. If you so worry about some bigger integers you can use long instead of int but as you know it has its own limitation about 18 digits approximately and it should not be bigger than Long.MAX_VALUE.
Your code is good for the start and I'm going to express some advice in order to provide a better and cleaner code:
It's obvious that you've repeated these part of codes:
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
and
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
and
System.out.println("Reverse of entered number is "+reverse);
If you studied methods so far, you may want to define these two first blocks in two different methods. One is responsible for getting input from user and the other one is responsible for getting an int as input and return the reversed int (If you used long for user input, this method's input and output should be of type long).
Another tip is why repeat those blocks? Why have two number and number2 variables and also reverse and reverse2?
Isn't it better to omit them and write your while for the repetition of the process in the first time too? Start by initializing the char repeat = 'Y'; and omit the first time you manually get the job done outside of the while( repeat == 'Y' || repeat == 'y') loop.
Hope this helps.

Related

Creating a game with loops that compares a secret number to user input

I was asked to create a mastermind game for school. The project never ran properly and I believe I went about the process in the wrong way. While the assignment is already past due I would like to know where I went wrong. Keep in mind we have still not gone over arrays.
This was the assignment description:
Your program will choose a random 4 digit number as the secret number. Your program must prompt the user to enter a 4 digit number as their guess. The program will respond with a message indicating how many of the digits in the user’s guess are the same as the digit in the same position in the secret number. For example, if the secret number is 3749, and the user’s guess is 9753, then the program would respond with the message You matched 1, because only one of the digits (the 7) in the user’s guess is the same as the digits in the same position in the secret number. The program will allow the user to continue to enter guesses until they guess the correct secret number. After the user has entered the secret number, the program will output a count of the total number of guesses the user took to find the secret number. Then the program will ask the user if they would like to play again. If the user answers “yes”, then the program will choose another random 4 digit number and play continues as described above.
Where was the best place to start for this assignment?
What was the best way to use loops?
How do I select different parts of the secret number?
Any help I can get now will help me catch up in the class.
import java.util.Scanner;
public class Assignment04 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("----- MASTERMIND -----");
System.out.println("Guess the 4 digit number!");
int secretNumber = (int)(Math.random() * 1000 + 1);
int usersGuess = 0;
int counter = 0;
int guessCount = 1;
for(int i=0; i<guessCount; guessCount++) {
System.out.print("Enter your guess: ");
usersGuess = in.nextInt();
if (String.valueOf(usersGuess).substring(0,0)==String.valueOf(secretNumber).substring(0,0));
{
guessCount ++;
counter ++;
break;
if (String.valueOf(usersGuess).substring(1,1)==String.valueOf(secretNumber).substring(1,1));
{
guessCount ++;
counter ++;
break;
}
if (String.valueOf(usersGuess).substring(2,2)==String.valueOf(secretNumber).substring(2,2));
{
guessCount ++;
counter ++;
break;
}
if (String.valueOf(usersGuess).substring(3,3)==String.valueOf(secretNumber).substring(3,3));
{
guessCount ++;
counter++;
break;
}
System.out.println("You matched " + guessCount);
if(counter==4);
{
System.out.println("Congratulations! You guessed the right number in " + counter + "guesses");
System.out.println("Would you like to play again? (Yes/No)");
}
}
}
}
}
This is all I was able to come up with.
So few points
Your for loop condition (i < guessCount) shouldn't be driven by the guess count because it should continue looping until they guess correctly.
You'd maybe want e.g. a boolean named "continueLooping" which is true and a while condition evaluating that instead of a for loop.
If the guessCount (which is summing the number of times the correct digits were aligned) is 4 then "continueLooping" would be set to false if the user said "No" when asked "Would you like to play again?"
You shouldn't be breaking after each matched digit. What if the first digit matches and the second digit matches? The break after the first match will stop the second digit ever being counted and the loop will exit
You want to check the length of their input to make sure it's 4 digits long
You'd want to use .equals() method of String rather than == as String is a reference type meaning equality is checked using equals() not the "==" operator (that is for checking primitive equality or exact reference equality)
Your "counter" should only increment once at the beginning of every loop
You GuessNumberRandomizer is wrong: it will produce 3 digit numbers only. Use this for 4 digits:
int secretNumber = (int)(Math.random() * 10000 + 1);
Also, I would suggest using String input or better yet, parse the integer input to String and use charAt() method for comparison instead. Also your usage of break may create some errors if more than 1 one digit was guessed correctly.
The first loop is is not really a good case scenario for a for loop. You should use a while loop. While will continue iterating, possibly infinitely, until the condition on which it's evaluated is no longer true.
Since your program should continue until the user guesses, or until he guesses right and doesn't want to play anymore, you should have a boolean "flag" which tells the game it should continue the loop. If the game has been won (when the correct guesses in a turn is equal to 4) then you should prompt the user if they want to continue playing, and if they say no, you just turn off the flag and the program exits.
Something like this
boolean continue = true;
int correctGuesses;
int numberOfTimesAttempted = 0;
while(continue){
numberOfTimesAttempted++;
correctGuesses = 0;
//Your game logic
if(correctGuesses == 4){
System.out.println("Do you wish to continue? Y or N");
char answer = sc.nextLine();
if(char.toUpper('N'){
continue = false;
System.out.println("It took you " + numberOfTimesAttempted + "to win!");
}
}
}
As some users pointed out, you should also have logic to verify that the user enters strictly 4 numbers.
Rather than comparing each number individually, simply convert the number to a char array and create a for loop that iterates through it. if the char at the current index is equal to the one in the secret number, increase the number of guess counts.
At the end of each loop, print the number of correct guesses. If number of guesses is 4, the user wins.

Unlimited number of user inputs

I have an assignment to make a program which allows the user to enter an unlimited
set of numbers until 0 is entered, to print the smallest and largest number, and to say if they are odd or even.
I am comfortable with everything except on how to allow the user to enter as many numbers as desired and am unsure on how to start this. Should I be using loops or another method?
Please note I only began learning Java last week and so am unfamilliar with the language
Many thanks!
I am comfortable with everything except on how to allow the user to enter as many numbers as desired and am unsure on how to start this. Should I be using loops or another method?
Since this is a homework, and you probably do not want us to do your homework for you. This is what you can do:
do{
//prompt user for input
//prompt user to continue (y/n)
//if 'n' was given
//proceed = false;
}while(proceed);
You can use a do-while or while loop. You can now prompt user for input infinitely till they decide to stop.
Update 1: (According to changes in question)
Terminating condition: when 0 is received as input:
do{
//prompt user for integer input
//if (input == 0)
//break; (exit loop)
//store input
}while(input != 0);
***Try to do it on your own.Use this for reference only.
I know its not right to give away the code as it is for your assignment.Just use (understand and learn)this if you didn't get the output.
int n=0,temp=0,z=0,i=0,j=0;
int []a=new int[1000]; //as size is not given by user assign the array with a much greater value
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Object for BufferedReader class used for reading elements
do{
System.out.print("Enter the number:");
a[n]=Integer.parseInt(br.readLine()); //String to integer conversion
n++;
System.out.println("Do you want to enter more numbers(0/1):");
z=Integer.parseInt(br.readLine());
}while(z!=0);
//Sorting
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
//Now after sorting the smallest number will be in the first location ie;
//"0" so inorder to check it is even or odd we take check its remainder when it is divided by 2.
if(a[0]%2==0){
System.out.println("The smallest number is : "+ a[0] + " & the number is even");}
else{
System.out.println("The smallest number is : "+ a[0] + " & the number is odd");}
if(a[n-1]%2==0){
System.out.println("The largest number is : "+ a[n-1] + " & the number is even");}
else{
System.out.println("The largest number is : "+ a[n-1] + " & the number is odd");}
A sample output is as follows :

Get user to input integers

I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}

How to make it so only ints from the array can be chosen? Also how to find biggest integer from integers chosen?

I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.

How to check how many Divisors there's in a whole number and How to express a factorial equation to Odd numbers?

So my homework tells me to write the equation for a ODD number, the equation must be a factorial if and only if the number is odd.
In my head I the structured came like this (until I don't know how to use the factorial)
import java.util.*;
public class apple {
public static void main(String args []) {
Scanner var = new Scanner(System.in);
int m;
System.out.println("Type in your first number: ");
m = var.nextInt();
if (m==0){ //i don't know if m==0 express the condition to be whole numbers, please tell me which is.
//here I need to check how many divisors there is for my statement
}else if //Again, i don't know how to proceed here, i need to place the condition if M is ODD, how?
//here i need to state (what i guess) the equation of factorial number (in which case, if and only if is odd)
// and than print the results out. That is all the job it needs to be done.
}
}
}
So it seems like you want to print out the factorial of a number if you have an odd number and the divisors of the number if it is even. You haven't specified a way to present the divisors, so here's one way you could do it:
Scanner var = new Scanner(System.in);
int m;
long x=1; //for the factorial, we want to store in a long to combat data overflow
System.out.println("Type in your first number: ");
m = var.nextInt();
//if the input is odd we calculate its factorial
if (m%2==1){
for (int i = 1;i<=m;i++)
x*=i;
System.out.println(m+"!: "+x);
}
else{
System.out.println("1 is a divisor for "+m);
System.out.println("2 is a divisor for "+m);
if (m%3==0)
System.out.println("3 is a divisor for "+m);
//and so on for more divisors of m
}
A first note, you need to add "throws IOException" after your close parentheses in the main declaration since you are asking the computer for input.
How to detect if a number is odd. x=number.
if(x%2==1)
//Then the number is odd
else
//The number is even
How to detect if the number is a whole number: whole meaning an integer greater than 0. You already know its an integer (Thats what you are asking for with nextInt().) so all you need to say is:
if(m>0)
//Then it is whole
Please clarify on anything this did not answer, your question was a bit vague.

Categories