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.
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
I'm writing a number guessing game in java.
Number guessing game is a numeric version of famous hangman, where computer picks a
number between a prespecified range and user has to guess that number.
Requirements:
User must guess a number between 0-1000 and tells the user the range of guessed
number.
User has max 10 guesses.
Every time user makes a guess, total guesses reduce by one.
Computer keeps track of all the numbers user has guessed so far and shows this
information before next guess.
If the guess is correct, game ends in a win. In case of incorrect guess, computer gives a
hint to the user. If the user guess is greater than the picked number, then client tell the
user that ‘your guess is bigger’ and in case of being smaller appropriate message is
shown.
In case of invalid guess (alphabets, symbols and repeated guesses) one warning is given
and on next warning user loses a guess
The following code is running fine but it always shows the same number after guesses number. I think its not adding the new input in the arrraylist rather the first one everytime.
import java.util.*;
import java.lang.*;
public class NumberGuess {
public static void main(String[] args) {
int tries = 10;
ArrayList<Integer> guessed = new ArrayList();
int warnings = 2;
int i = 0;
Random rand = new Random();
int random = rand.nextInt(1000);
private void StartMenu () {
System.out.println("\" Welcome to the Number guessing game!\n I am thinking of a number between 0-1000\n You have 1 warning.\n You have 1 warning.\n ------------ ");
}
public char[] ToCharacterArray (String input){
char arr[] = new char[input.length()];
arr = input.toCharArray();
return arr;
}
public boolean CheckInput ( char arr[]){
if (Character.isDigit(arr[0])) {
return true;
} else {
return false;
}
}
String input;
while (tries > 0 && warnings > 0) {
System.out.println("You have " + tries + " guesses left.");
if (tries == 10) {
System.out.println("guessed number: ");
} else {
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(guessed.get(i));
}
}
System.out.println("Please guess a number:");
Scanner sc = new Scanner(System.in);
input = sc.next();
char InputString[] = ToCharacterArray(input);
if (CheckInput(InputString)) {
int intInput = Integer.parseInt(input);
guessed.add(intInput);
if (intInput > random) {
System.out.println("Your guess is greater");
}
if (intInput < random) {
System.out.println("Your guess is smaller");
}
if (intInput == random) {
System.out.println("Congrats! You win.");
System.out.println("The guessed number is: " + intInput);
tries = -1;
}
}
tries--;
}
}
}
The problem is because you iterate over the guessed numbers, and then print out the item of index i from that list. The number i at that point will always be zero, so it will always print just the first element from that list. Instead, you can just print the a, that is the element itself, after the iteration on guessed. Here is how it will look like:
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(a);
}
first off, the secret word is printed out as dashes, then the user puts in what letter they want to guess. if they guess the letter correctly then it will update the dashes. so if the word is java, it will show as ---- and if the user types a, then it will update and show -a-a . my program does that but it also adds extra dashes at the end and i don't know how to make it not print those extra dashes. and that brings me to another problem i am having, the user is asked at what indexes they want to guess the letter. so if the user types the letter a and at index 1, then the updated word will show -a--, but my program updates all instances of where the a is at, so it shows -a-a. here is my code:
import java.util.Scanner;
public class HangMan2 {
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int guessRemaining = 20;
int rounds = 1;
int roundScore;
String wordString = "";
String word = RandomWord.newWord();
int length = word.length();
for(int i = 0; i < length; i++)
{
wordString += "-";
}
System.out.println("The word is: " +wordString);
System.out.println("The secret word is: " +word);
System.out.println("Enter the number of spaces allowed");
int spacesAllowed = keyboard.nextInt();
keyboard.nextLine();
if(spacesAllowed > length)
{
System.out.println("Invalid input. Try again.");
System.out.println("Enter the number of spaces allowed");
spacesAllowed = keyboard.nextInt();
}
while(guessRemaining > 0) {
System.out.println("Please enter the letter you want to guess: ");
String letterGuess = keyboard.next();
char letterCharacter = letterGuess.charAt(0);
System.out.println("Please enter the number of spaces you want to check (seperated by spaces): ");
String spacesChecked = keyboard.next();
boolean guessCheck;
// check if the letter is in the string
guessCheck = (word.indexOf(letterCharacter)) != -1;
if(guessCheck == true)
{
for (int i = 0; i < word.length(); i++) {
if (letterCharacter == word.charAt(i)) {
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
System.out.println("Your guess is in the word!");
System.out.println("The updated word is: " +wordString);
} //end of if statement
} //end of for loop
}
else
{
System.out.println("Your letter was not found in the spaces you provided");
guessRemaining--;
System.out.println("You have " +guessRemaining+ " guesses remaining.");
}
}
if(guessRemaining != 0)
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
roundScore = (guessRemaining * 10) / spacesAllowed;
} //end of if
else{
System.out.println("Guesses Remaining: 0");
System.out.println("You have failed to guess the word... :(");
}
System.out.println("Would you like to play again? Yes (y) or No (n)");
String playAgain = keyboard.next();
if(!playAgain.equals("y") && !playAgain.equals("n"))
{
System.out.println("Invalid response, please try again... ");
}
if(playAgain.equals("y"))
{
rounds++;
}
else
{
System.exit(0);
}
}
}
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
if ((wordString.substring(0,i) + wordString.substring(i)).equals(wordString))
System.out.println("These are completely identical");
else
System.out.println("You solved it yourself ;)");
hint: it's 58 in your posted code.
Second part: Completely different program structure.
You'll need to track user's two guessed values, one as a character, the other as an int.
You will compare wordString.toCharArray()[indexUserGuessed] to characterUserGuessed and update the result or game state as needed, using similar code from the way you solved the if statement paradox I provided.
Finally, Welcome to Stack Exchange. MOST of us won't do your homework for you.
Oh and I would look up examples of "StringBuilder Java" as you might find it easier to manipulate your String with this class than with String.
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");
}
}
I'm a beginner and don't know what is wrong with my program.
What I would like the program to do is to allow the user to enter an Integer that is under MAX (1 000 000 000) but above 0. I also have put an exception block using the try and catch methods so that the user cannot enter a String.
The exception block works but it also prints the statements inside the if block, which I don't want.
This is what the console prints:
Number of marbles to divide:
*three*
Please enter a number not a word
Try again:
Please enter a number under 1 000 000 000 and above 0
Try again:
I only want it to print... Please enter a number not a word Try again: after the user enters a String. What I mean is that I want the method's while-loop to break if the user has entered a string.
Another problem that I can't seem to solve is that if the user enters an Integer that's value is over MAX (1 000 000 000), the program continues. This is what the console prints.
Number of marbles to divide:
1000000001
Number of people:
As you can see the program continues even though the user has entered an Integer over MAX (1 000 000 000)
This is my code:
import java.util.*;
public class MarblesApp
{
final static int MAX = 1000000000;
static int numberOfMarbles;
static int numberOfPeople, marblesPerPerson, marblesLeftOver;
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Welcome to the marble divvy-upper.");
System.out.println("This program will tell you how many marbles to give to each person.\n"
+ "The maximum amount of marbles is 1 000 000 000. The maximum amount of people is the same.\n");
System.out.println("Number of marbles to divide: ");
numberOfMarbles = GetMarbles();
System.out.println("Number of people: ");
numberOfPeople = GetPeople();
marblesPerPerson = (int)numberOfMarbles / numberOfPeople;
marblesLeftOver = (int)numberOfMarbles % numberOfPeople;
System.out.println("Give each child " + marblesPerPerson + " marbles.");
System.out.println("You will have " + marblesLeftOver + " marbles left over.");
}
private static int GetPeople()
{
while (true)
{
try
{
return input.nextInt();
}
catch(InputMismatchException f)
{
input.next();
System.out.println("Please enter a number not a word\nTry again: ");
}
if(numberOfPeople > MAX || numberOfPeople == 0);
{
System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
}
}
}
public static int GetMarbles()
{
while (true)
{
try
{
return input.nextInt();
}
catch (InputMismatchException e)
{
input.next();
System.out.println("Please enter a number not a word\nTry again: ");
}
if(numberOfMarbles > MAX || numberOfMarbles == 0);
{
System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
}
}
}
}
I know how difficult Java can be if you're absolutely new to it. And as I'm not one of those who expect your questions to be perfectly written and brought to the point, I assembled a solution to your problem.
I had to reorganize and squeeze your code a little bit. And I have to make some remarks referring to cleaner code:
method-names in Java always start with a lower-case letter, _ or $
avoid global variables if you don't need them
avoid duplicate methodes that only differ in their names
I hope this code gives you a good start into JAVA. Have fun!
import java.util.*;
public class MarblesApp
{
private final static int MAX = 1000000000;
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
int numberOfMarbles, numberOfPeople, marblesPerPerson, marblesLeftOver;
System.out.println("Welcome to the marble divvy-upper.");
System.out.println("This program will tell you how many marbles to give to each person.\n"
+ "The maximum amount of marbles is 1 000 000 000. The maximum amount of people is the same.\n");
System.out.println("Number of marbles to divide: ");
numberOfMarbles = getNumberFromConsole();
System.out.println("Number of people: ");
numberOfPeople = getNumberFromConsole();
marblesPerPerson = (int)numberOfMarbles / numberOfPeople;
marblesLeftOver = (int)numberOfMarbles % numberOfPeople;
System.out.println("Give each child " + marblesPerPerson + " marbles.");
System.out.println("You will have " + marblesLeftOver + " marbles left over.");
}
public static int getNumberFromConsole()
{
int number;
while (true)
{
try
{
// get the number from console
number = input.nextInt();
// validate whether it's greater zero and lower MAX
if(validateNumber(number) == true)
{
// if true, return the number
return number;
}
else
{
// if not, input again
input.next();
}
}
catch (InputMismatchException e)
{
System.out.println("Please enter a number not a word\nTry again: ");
input.next();
}
}
}
private static boolean validateNumber(int number) {
if(number > MAX || number == 0)
{
System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
return false;
}
return true;
}
}