Something wrong with armstrong number java code - java

I wrote a code for school in java that verifies if a number is an armstrong number. I programmed it so that it runs as many times until the user inputs 0, at which the program will terminate. I am having 2 problems.
The code only works the first time through, if the user inputs 371 (an armstrong number) the first time, it works, but after that it returns that the number is not an armstrong number.
When the user inputs 0, it still shows the statement whether it is or is not an armstrong number, which I don't want it to.
This is the code:
import java.util.Scanner; //import Scanner for user input
public class Ch6Project {
public static void main(String[] args) {
int userNum, totalValue = 0, num, numLength; //declare variables that will be used
String suserNum; //declare user input variable
Scanner input = new Scanner(System.in); //declare a Scanner
System.out.println("Welcome to the Armstrong Number Program."); //description
System.out.println("\nTo calculate an Armstrong number: ");
System.out.println("\t 1. Cube each digit of the number.");
System.out.println("\t 2. Take the sum of these cubes.");
System.out.println("\t 3. If the sum equals the number, it is an Armstrong Number.");
System.out.println("\t e.g. 3^3 + 1^3 + 7^3 = 317");
do {
System.out.print("\nEnter a whole number (0 to quit): ");
suserNum = input.nextLine(); //collect user input
userNum = Integer.parseInt(suserNum); //parse user input
numLength = suserNum.length(); //calculate length of user input
for (int i = numLength; i > 0; i--) { //create loop to run for n times
num = Integer.parseInt(suserNum.substring(numLength - 1, numLength)); //get last digit of number
totalValue += Math.pow(num, 3); //cube a digit
numLength--; //subtract userNum by 1 to get the rest of the digits
}
if (totalValue == userNum) { //if total value equals user input, it is Armstrong #
System.out.println("Your number is an Armstrong number.");
} else { //if total value does not equal user input, it is not an Armstrong #
System.out.println("Your number is not an Armstrong number.");
}
} while (userNum != 0); //run loop until user input == 0
input.close(); //close user input
}
}

Change your code so that it breaks immediately after entry of the userNum
e.g.
userNum = Integer.parseInt(suserNum); //parse user input
if (userNum == 0) {
break;
}
then you can also change your loop to a endless loop
while (true) {
// your code
}

It works only the first time because you don't reset your sum variable: just after the do insert:
do {
totalValue =0;..
}while (userNum != 0);
plus, your code doesn't immediatly exit because the check of the condition is at the end, hence you insert the number, the code is executed and THEN you check. BTW: when you can, avoid using break statement.
Put an if controll after the reading of the number, like this:
do {
System.out.print("\nEnter a whole number (0 to quit): ");
suserNum = input.nextLine(); //collect user inputuserNum =
Integer.parseInt(suserNum); //parse user input
if(userNum !=0){...your code...}
}while (userNum != 0);
There are a ton of more elegant way to code it but this should do the work

public class E1 {
public static void main(String[] args) {
int c = 0, a, temp;
int m = 153;
int n = m;
temp = n;
while (n > 0) {
a = n % 10;
n = n / 10;
c = c + (a * a * a);
}
if (temp == c)
System.out.println(m + " is an armstrong number");
else
System.out.println(m + "is not an armstrong number");
}
}

Related

Java lottery Machine Task

My task is to allow a user to input their lottery numbers and check if
they have won the jackpot.
The user should be given the chance to enter 4 numbers. Each number should be in the range 1-99. If
the user enters a number that is less than 1, or greater than 99, then the programme should prompt
them to enter a number in the correct range. You should use a while loop to ensure that the user inputs
the correct number. What should the exit condition of the while loop be?
I have tried making a while loop as the task asks me to do. this did not work. I am completely and utterly stuck.
String password = "MyNameJeff";
Scanner dave = new Scanner(System.in);
System.out.println("lottery numbers");
int UserInput = dave.nextLine();
while (!password.equals(UserInput)) {
System.out.println random math command <----
UserInput = dave.nextLine();
}
System.out.println("Lottery numbers here?");
This while loop will take the first userInput and check its range between 1 and 99 inclusive.
while(userInput < 1 || userInput > 99){
System.out.println("Please re-enter another lottery number: ");
userInput=dave.nextInt();
}
If it is not in the range 1 to 99, it will request the user to re-enter another lottery number.
the condition is when you want to stop the while loop. for example
you may want to stop when you have 4 numbers
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Scratch {
public static void main(String[] args) {
List<Integer> choices = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
boolean done = false;
//we set done to false, and the condition is "while !(not) done"
while (!done) {
try {
System.out.println("write lottery numbers:");
String userInput = scanner.nextLine();
Integer result = Integer.parseInt(userInput);
// compareTo is a bit tricky, read the javadoc for information
if (result.compareTo(0) < 0) {
System.out.println("dont add number less then 0");
continue;
}
if (result.compareTo(99) > 0) {
System.out.println("dont add number more then 99");
continue;
}
//adding more result is the only way done will be eventually true
choices.add(result);
//set to done when the size of the list is 4
done = choices.size() == 4;
} catch (NumberFormatException e) {
System.out.println("Only add number");
}
}
System.out.println("Lottery numbers here?");
choices.forEach(System.out::println);
}
}
Check this code
public static void main (String[]args) throws IOException, ParseException {
int [] winNumbers = new int[4];
int [] numbers = new int[4];
int indx=0;
System.out.println("Enter Lottery Numbers");
while (indx<4) {
System.out.println("Enter number: ");
Scanner dave = new Scanner(System.in);
try {
String in = dave.nextLine().trim();
int inNum = Integer.parseInt(in);
if (inNum>0 && inNum<100) {
numbers[indx] = inNum;
indx++;
continue;
}
}
catch (NumberFormatException | NullPointerException nfe) {
}
System.out.println("Please enter a number in the range 1-99");
}
Random rand = new Random();
for (int i=0; i<winNumbers.length; i++){
int r = rand.nextInt(98);//will get a random number between 0-98
r +=1; // for the number to be on the space 1-99
winNumbers[i]=r;
}
System.out.println("User entered: " + Arrays.toString(numbers));
System.out.println("Lottery numbers here: " + Arrays.toString(winNumbers));
}
Two int arrays are used with size 4.
One is filled using Scanner. There are some checks:
trim(): will remove any whitespace that the user might enter
catch: will catch a numberFormatException or null. It will print nothing.
If the code does not enter the if(inNum>0 && inNum<100) then the indx counter will not increment and the code will print the error message: Please enter a number...
The second part of the code generates 4 random numbers and stores them in the second array.
Finally, it prints the two arrays.

Product of Number input by user, program stops when user inputs 0

i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"

I am trying to get user input until user enter 0 and then show maximum value among them in JAVA

I am a beginner to java and don't know to write a program using loops that prompt the user to enter a number till user does does not enter 0.
When user enter 0 then system should display MAX number among user input
QUE 2
Write a program to ask the user to enter a sequence of numbers (double type). The numbers are separated by the return key (and give a prompt for each enter). The user ends the sequence by entering a 0. Then output the maximum number of all the entered numbers. Here is an example (the part in italic is the user’s input): Please enter a sequence of numbers, separated by return, and then end this sequence with a 0 at last: 25
Next number: 35.6
Next number: 112.112
Next number: 0
The maximum among your enters is 112.112
import java.util.Scanner;
public class Q3
{
public static void main(String[] args[])
{
double n;
// double i;
double MAX=0;
System.out.println("Please Enter the number: ");
Scanner Kb = new Scanner(System.in);
n = Kb.nextDouble();
if(n>0){
System.out.println("Please Enter the number: ");
n = Kb.nextDouble();
return;
}
else if(n==0) {
if (MAX>0){
MAX=n;
return ;
}
}
return;
}
}
Keep track of the max and each time a user inputs a number check if it is greater than that max
import java.util.Scanner;
public class Q3 {
public static void main(String... args) {
double max = 0;
System.out.println("Please enter the number: ");
Scanner kb = new Scanner(System.in);
double number = kb.nextDouble();
while (number != 0) {
if (max < number) {
max = number;
}
number = kb.nextDouble();
}
System.out.print("The max is " + max);
}
}
Since zero is the terminal character then negative input can be essentially ignored and the initial value of max as zero is acceptable.
Note that nextDouble can throw an InputMismatchException if the user decides to give you input that can not be parsed to a double.
using Collections.max ,
List<Double> doubleList = new ArrayList<>();
System.out.println("enter a number :");
Scanner kb = new Scanner(System.in);
while (kb.hasNext() ) {
double input = kb.nextDouble();
if(input == 0){
break;
}
doubleList.add(input);
}
System.out.println("Max Value Entered : " + Collections.max(doubleList));
Scanner sc = new Scanner(System.in);
double max = 0;
while(true){
double number = sc.nextDouble();
if(max<number){
max = number;
}
else if(number==0){
break;
}
}
System.out.print(max);

Output sum of even numbers between two integers

I am working on a simple JAVA question in one of my college courses. I am stumped on this one program. I will display what I have so far and give the question I have to answer. I also looked at a similar question on StackOverflow, BUT it isn't the same problem so it DIDN'T help. The program I need to write is:
Write a program that uses 'while' loops to perform the following steps:
a.) Prompt the user to input two integers: 'firstNum' and 'secondNum' (firstNum must be less than secondNum)
b.) Output all the odd numbers between 'firstNum' and 'secondNum' inclusive.
c.) Output the sum of all the even numbers between 'firstNum' and 'secondNum' inclusive.
This is what I have so far... (I still need to calculate the even numbers and sum them up)
//import classes
import java.util.*;
public class chapter5no9
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
//Part A
int firstNum;
int secondNum;
int sumEven;
System.out.println("Please enter an integer: ");
firstNum = console.nextInt();
System.out.println("Please enter another integer less than the first integer: ");
secondNum = console.nextInt();
//Part B
if (firstNum < secondNum)
{
System.out.print("Your second number is greater than the first. So Please re-enter: ");
secondNum = console.nextInt();
}
else
{
System.out.print("Odd Numbers: ");
firstNum++;
while (firstNum > secondNum)
{
if (secondNum % 2 != 0)
{
System.out.print(" " + secondNum);
}
secondNum++;
}
System.out.println();
System.out.print("Sum of Even Numbers: ");
firstNum++;
while (firstNum > secondNum)
{
if (secondNum % 2 != 0)
{
System.out.print(" " + secondNum);
}
secondNum++;
}
}
}
}
I created the loopCounter variable to handle the required iterations without changing the values inputted by the user. The following changes have been made to your code.
Part A: added a while loop to validate user input. Also changed logic in if statement.
Part B: used one loop to print odd numbers and total even numbers
//Part A
int firstNum;
int secondNum;
int sumEven=0;
System.out.println("Please enter an integer: ");
firstNum = input.nextInt();
System.out.println("Please enter another integer less than the first integer: ");
secondNum = input.nextInt();
//Part B
//validate input in a loop
while(true)
{
if (firstNum > secondNum)
{
System.out.print("Your second number is larger than the first. So Please re-enter: ");
secondNum = input.nextInt();
}
else
{
break;
}
}
System.out.print("Odd Numbers: ");
int loopCounter=firstNum;
while(loopCounter<secondNum)
{
if (loopCounter%2!=0)
{
System.out.print(" " + loopCounter);
}//end if
else
{
sumEven+=loopCounter;
}//end else
loopCounter++;
}
System.out.println();
System.out.print("Sum of Even Numbers: ");
System.out.print(sumEven);
}
I would separate the two concerns of checking input and calculating the result. Here's how I would calculate it:
int sum = IntStream.rangeClosed(firstNum, secondNum).filter(i -> i % 2 == 0).sum();
The issue is in your logic. You have this if statement:
if (firstNum < secondNum)
{
System.out.print("Your second number is greater than the first. So Please re-enter: ");
secondNum = console.nextInt();
}
Which checks if the second number is greater than the first (which you want it to be) and then asks them to re-enter. You want to check if (secondNum < firstNum). You will need to reverse all your while and if statements that compare secondNum to firstNum.
Then you have this if (secondNum % 2 != 0) to check for odd numbers, which is correct, but you copy-pasted it to check for even numbers, which won't work, you will need to change that as well.
Then, you are outputting all the even integers inside your loop, when really you want to be adding it to an evenSum variable, and outputting that at the end of the loop:
System.out.println("The sum of all even integers is: " + evenSum);
That should be enough to help you, I'm not going to write your homework for you, that's not what we do here.
package hello.world;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number ;
int X = 0;
System.out.print("enter a number plz : ");
number = sc.nextInt();
while (X <= number){
System.out.println(X);
X ++;
}
}
}

Java DigitExtractor

I'm having trouble with an assignment that I'm working on. Here is the prompt:
Create a DigitExtractor application that prompts the user for an integer (in the range: 0-999) and then displays either the ones, tens, or hundreds digit of the number. The user will select from a menu which digit they wish to display.
This program needs to be written as a class. The menu will be your driver program that you submit with the class so your instructor can use it to test the class.
Here is my code for it:
import java.io.*;
import java.util.*;
public class TestingMenu
{
public int number;
public int units;
public int tens;
public int hundreds;
public TestingMenu(int input)
{
number = input;
units = number%10;
tens = number%10;
hundreds = number%10;
}
public int return_units()
{
return units;
}
public int return_tens()
{
return tens;
}
public int return_hundreds()
{
return hundreds;
}
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
TestingMenu num;
int choice;
int input;
do
{
System.out.print("Enter a number(0-999): ");
input = kbReader.nextInt();
System.out.println("");
System.out.println("Options");
System.out.println("1) Units");
System.out.println("2) Tens");
System.out.println("3) Hundreds");
System.out.println("4) Quit");
num = new TestingMenu(input);
System.out.print("Enter your choice: ");
choice = kbReader.nextInt();
switch(choice)
{
case 1:
System.out.println("The units digit is: " + num.return_units());
break;
case 2:
System.out.println("The tens digit is: " + num.return_tens());
break;
case 3: System.out.println("The hundreds digit is: " + num.return_hundreds());
break;
case 4:
System.exit(4);
break;
default:
System.out.print("Invalid. Select a number from the given options.");
choice = kbReader.nextInt();
}
}
while(choice != 4);
}
}
I think I've almost got it, but I'm having issues whenever I test it. When I input a number such as 987 and I run all the options from 1-3, I keep getting 7 for the ones, tens, and hundreds. 4 exits the program and works okay, but I've tested this numerous times. Overall, it seems to only print the last digit.
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 1
The units digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 2
The tens digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 3
The hundreds digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 4
Could someone help me identify the error? I don't really know what went wrong with this program despite working on it for a few hours. Thanks in advance. All the help and feedback is greatly appreciated.
You had a few issues, I would suggest you review this very carefully -
// Why make them public?
private int units = 0;
private int tens = 0;
private int hundreds = 0;
public TestingMenu(int input) {
// Convert it to a String.
String str = String.valueOf(input);
if (str.length() == 1) {
// ones and only ones.
units = Integer.parseInt(str);
} else if (str.length() == 2) {
// tens and ones.
tens = Integer.parseInt(str.substring(0, 1));
units = Integer.parseInt(str.substring(1, 2));
} else if (str.length() == 3) {
// hundreds, tens and ones.
hundreds = Integer.parseInt(str.substring(0, 1));
tens = Integer.parseInt(str.substring(1, 2));
units = Integer.parseInt(str.substring(2, 3));
}
}
// Just use get, PLEASE!
public int getUnits() {
return units;
}
public int getTens() {
return tens;
}
public int getHundreds() {
return hundreds;
}
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
try {
TestingMenu num;
int choice;
do {
System.out.print("Enter a number(0-999): ");
num = new TestingMenu(kbReader.nextInt());
System.out.println("");
System.out.println("Options");
System.out.println("1) Units");
System.out.println("2) Tens");
System.out.println("3) Hundreds");
System.out.println("4) Quit");
System.out.print("Enter your choice: ");
choice = kbReader.nextInt();
if (choice == 1) {
System.out.println("The units digit is: "
+ num.getUnits());
} else if (choice == 2) {
System.out.println("The tens digit is: "
+ num.getTens());
} else if (choice == 3) {
System.out.println("The hundreds digit is: "
+ num.getHundreds());
} else if (choice != 4) {
// We want 4 to fall through and terminate the loop.
System.out.print("Invalid. Select a number "
+ "from the given options.");
choice = kbReader.nextInt();
}
} while (choice != 4);
} finally {
// close the Scanner.
kbReader.close();
}
}
What I would do is I would is I would use your Scanner to take input as a string so you can use .length() to get the length and .charAt() to display them...remember that charAt is like arrays in that the indexes start from 0, length does not. If you need them to be ints you can use Integer.parseInt() (be sure to check it is a number before trying this cause it will throw an exception but with a boolean and a try catch you can continue to ask users for input until they get it right like this
boolean notComplete = true;
while(notComplete = true){
try{ userinput = //get input somehow
Integer.parseInt(userinput);
//do whatever
boolean complete = true;
}catch(NumberFormatException e){
//get input and repeat it will keep trying until the boolean is updated
}})
But for this I don't think it matters how you keep it as long as you display it. You could also add an array of Strings that have indexs that correspond to what they are...meaning something like this:
String[] s = {"ones", "tens", "hundreds"};
so that when the user says 1, 2 or 3 to pick what should be displayed you can subtract one call .charAt on the string to display the number and print the index of the array s at the same index to tell the user what it is.

Categories

Resources