I am creating a program which asks the user to enter two numbers. It will then print the numbers the user entered and the numbers between the two numbers in numerical order. I declared and initialized two variables, which are 'number1' and 'number2'.
int number1;
int number2;
do{
Scanner input = new Scanner(System.in);
System.out.print("Enter the first number: " );
number1 = input.nextInt();
System.out.print("Enter the second number: " );
number2 = input.nextInt();
if(number1 == number2)
{
System.out.println("The numbers you entered equal with each other. Try again.\n");
}
}while(number1 == number2);
if (number1 > number2)
{
for(int a = number2; a <= number1; a++)
{
System.out.print(a + " ");
}
}
else
{
for(int a = number1; a <= number2; a++)
{
System.out.print(a + " ");
}
}
How do I make it so it also prints only the numbers between 'number1' and 'number2'?
The first part of your code was fine, if you want to do it this way.
Scanner scanner = new Scanner(System.in);
int first, second;
do {
System.out.print("Enter the first number: ");
first = scanner.nextInt();
System.out.print("Enter the second number: ");
second = scanner.nextInt();
if (first == second) {
System.out.println("The numbers you entered equal with each other. Try again.\n");
}
} while (first == second);
For the second part, I'd recommend determining which number is which (smaller/bigger) instead of using duplicate code. Also you need to only cycle through numbers in between the numbers you chose, so you have to change your for cycle
//determine which number is bigger/smaller
int smaller = Math.min(first, second);
int bigger = Math.max(first, second);
for(int i = smaller+1 ; i < bigger ; i++){
System.out.print(i + " ");
}
The only odd scenario here is where you input two numbers which are adjacent, which will output no numbers. For example 3 and 4.
int max = Math.max(number1, number2);
for(int i = (max == number1 ? number2 : number1) + 1 ; i < max ; i++) {
System.out.println(i);
}
Related
The following Java program (prints out addition problem of two given numbers) is printing the answer backwards ( for example, 563 instead of 365). How would I modify it so that it prints out the correct answer?
Note: I know that Im completing this problem in an unnecessarily complicated manner, but this is because we are only allowed to use primitive data types.
Thankyou.
//getting the number from user
Scanner linput = new Scanner(System.in);
System.out.print("Enter the first number:");
num = linput.nextInt();
System.out.println ("Enter the second number:");
num2 = linput.nextInt();
System.out.println (num);
System.out.println ("+");
System.out.println(num2);
System.out.println ("=======");
//making a copy of the input number
temp = num;
temp2 = num2;
//counting digits in the input number
while(num > 0)
{
num = num / 10;
count++;
}
while(num2 > 0)
{
num2 = num2 / 10;
count2++;
}
int answer = 0;
while(temp > 0 && temp2>0)
{
digit = temp % 10;
temp = temp / 10;
count--;
digit2 = temp2 % 10;
temp2 = temp2 / 10;
count2--;
answer = digit+digit2;
System.out.print(answer);
}
You problem statement is very unclear. If it's just simple addition of two numbers then you've really overcomplicated your implementation.
Scanner input = new Scanner(System.in);
System.out.print("Enter the first number:");
int num = input.nextInt();
System.out.print("Enter the second number:");
int num2 = input.nextInt();
System.out.print(num + " + " + num2 + " = " + (num + num2));
I totally agree with all comments that this is over complicated to do a sum. But the answer to the initial question why the result is printed backwards is that that you calculate the sum from right to left (units, tens, hundreds, ...) but print them left to right (default behavior of print)
I am making a lottery game and I am wondering if there is a way to type in two integer numbers, like 3 and 4 but type them in as 34 and have them read individually? I need to have them read individually as the game will reward if one of the numbers entered matches one of the randomly generated numbers. My code so far is this:
import java.util.Scanner;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
int guess, guess2, counter;
int win1000, win10, win1;
int number = random.nextInt(10); int number2 = random.nextInt(10);
System.out.println("Welcome to the Super Lottery! \nLet's Play!");
System.out.println("Round 1 - you have 5 chances to win money");
System.out.print("Enter your guess: ");
guess = keyboard.nextInt();
guess2 = keyboard.nextInt();
System.out.println("The lottery number is " + number + number2);
win1 = 1;
win10 = 10;
win1000 = 1000;
counter = 1;
while(counter < 5) {
number = random.nextInt(10); number2 = random.nextInt(10);
System.out.print("Enter your guess: ");
guess = keyboard.nextInt(); guess2 = keyboard.nextInt();
System.out.println("The lottery number is " + number + number2);
counter++;
if(guess == number2 && guess2 == number) {
System.out.println("You guessed both numbers, but in a different order! You win $" + win10);
}
else if(guess == number && guess2 == number2) {
System.out.println("CONGRATULATIONS! You win the Super Lottery!" + win1000);
}
else if(guess == number || guess2 == number2) {
System.out.println("You guessed one number! You win $" + win1);
}
}
}
}
You can use the substring method to separate the numbers by their index so for a visual example:
String numbers = "12345";
System.out.println(numbers.substring(0,1));
System.out.println(numbers.substring(1,2));
System.out.println(numbers.substring(2,3));
System.out.println(numbers.substring(3,4));
System.out.println(numbers.substring(4,5));
}
Which will print out:
1
2
3
4
5
If you want to separate with a comma you could do something like this:
String numbers = "12345";
char[] temp = numbers.toCharArray();
for(int i = 0; i < temp.length; i++) {
System.out.print(temp[i] + ",");
}
Output:
1,2,3,4,5,
Since random.nextInt has 10 as an argument, that means the random generated number will be from 0-9.
With that being said I am going to assume the number that the player will enter will have be from 00 to 99.
You can use a String for that and then split it into two pieces.
Check this code example:
Scanner keyboard = new Scanner(System.in);
String number = keyboard.nextLine();
int guess, guess2;
guess = Integer.valueOf((number.substring(0, 1)));
guess2 = Integer.valueOf((number.substring(1, 2)));
System.out.println(guess);
System.out.println(guess2);
Try something like:
Scanner in = new Scanner(System.in);
int number = in.nextInt();
int firstNumber = number / 10;
int secondNumber = number % 10;
System.out.println("Result: "+ firstNumber + " & " + secondNumber);
I am relatively new to Java and I'm currently learning while, do while and for loops. I want to create an application that displays the sum of the digits of a number using these concepts but I have no idea how. I previously created an application that displayed ONLY THE DIGITS of a number. Here it is.
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
}
I'm trying to think of a possible way to expand on this program, but I have no idea why. Once again, this program is not what I need, what I need is somehow to sum the digits of a number using for or while loops. Thank you!
not much code has to be added for summing the digits :
First solution : using a substract with '0' character
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + (sdigit.charAt(i) - '0');
}
System.out.println("Sum is : "+sum);
Second solution : using Integer.parseInt which converts String to int :
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + Integer.parseInt(sdigit.subString(i,i+1));
}
System.out.println("Sum is : "+sum);
int digit;
System.out.println("Enter a positive integer: ");
number= Integer.parseInt(System.console().readLine());
int sum=0;
int currDigit = 0;
while( number / 10 > 0) {
currDigit = number % 10; //fetching last digit
System.out.println(currDigit);
sum = sum + currDigit;
number = number / 10;
}
EDIT: Lol I would've never thought you guys would be such savages. I thought this would be the right place for a college student to come and seek for answers. If I didn't care, why would I even be here.. Basically my question is different from the other ones because I do need the first loop to state my even numbers ie: 10 12 14 16 18 20. I sincerely hoped I would get some feedback on how to reinstate the original value of firstNum for the second loop, not criticism expecting to get selected as an answer for points in a matter of seconds.
I've implemented a code that I saw as an answer in a very similar question on the forum. Yet when I compile it, the output for my sum code doesn't return anything. It's just blank. Can I get some feedback on what I am missing or doing wrong? Thank you. BTW I can only use while loop.
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
int sum = 0;
if (mod != 0)
{
firstNum++;
}
System.out.print("Even numbers: ");
while (firstNum <= secondNum)
{
System.out.print(firstNum + " ");
firstNum += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
while (firstNum <= secondNum)
{
System.out.print(sum);
sum += firstNum;
firstNum += 2;
}
The first loop only prints the even numbers, it can not add because the firstNum reaches the secondNum.
If you want to keep the same code you have, you only need to add a new variable that prints even numbers. So the first loop will print the even numbers and the second loop will do the sum.
For example:
int evenNumber;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
int sum = 0;
if (mod != 0) {
firstNum++;
}
evenNumber = firstNum;
System.out.print("Even numbers: ");
while (evenNumber <= secondNum) {
System.out.print(evenNumber + " ");
evenNumber += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
while (firstNum <= secondNum) {
sum += firstNum;
firstNum += 2;
}
System.out.println(sum);
This code is not optimal, but it complies with what you need. But if you want to do better, you can do it like this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
int total = 0;
System.out.print("Even Numbers: ");
while (firstNum <= secondNum) {
if (firstNum % 2 == 0) {
System.out.print(firstNum + " ");
total += firstNum;
}
firstNum++;
}
System.out.println("\nSum: " + total);
During your first while, you already changed the value of firstNum. So basically, when you arrive to the second while, you don't even enter it.
I would simply change the first loop and delete the second one :
while (firstNum <= secondNum) {
System.out.print(firstNum + " ");
sum += firstNum;
firstNum += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
System.out.println(sum);
In your first while loop -
while (firstNum <= secondNum){
System.out.print(firstNum + " ");
firstNum += 2;
}
you keep incrementing variable firstNum until you reach secondNum, so the condition of the second while loop (firstNum <= secondNum) will never evaluates to true.
A very simple way to achieve your goal can be as follows.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
int total = 0;
while(firstNum <= secondNum){
if(firstNum%2 == 0)
total += firstNum;
firstNum++;
}
System.out.println("Sum: " + total);
I have encountered some problems with the calculating of largest and smallest number... If the first number I entered is a larger number than the 2nd number input, it will not record the 1st number into the largest...
Take a look at the output, it will help elaborate better..
Calculation Error.. &
1st input problem..
Codes below!
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
} else {
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
You could build an IntStream if you are using Java 8, and extract those numbers automatically using IntSummaryStatistics. You can find the official documentation from Oracle here.
Here is the code to achieve that:
List<Integer> input = new ArrayList<>();
while (true) { // LOOP till user enter "-1"
number = kb.nextInt();
// Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
input.add(number);
}
}
IntSummaryStatistics z = input.stream() // gives Stream<Integer>
.mapToInt(Integer::intValue) // gives IntStream
.summaryStatistics(); // gives you the IntSummaryStatistics
System.out.println(z);
If you input 8 3 7 the output will be:
IntSummaryStatistics{count=3, sum=18, min=3, average=6.000000, max=8}
I hope it helps!
Do it like this:
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
}
//REMOVED ELSE ADDED another IF
if (number > largest){
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
The problem is your if statement, as the logic is flawed. If the input number is smaller than smallest, then you update the smallest number. So far all is correct. The problem occurs, because you update largest in the else part. This means, if a number is not the smallest, largest is overwritten. But if the number is greater than the smallest, it is not automatically the largest. The right way to do this, is to check if the number is larger than the largest in a new if statement and update largest only in this case.