Simple Java program that squares and cubes a users input number - java

I am currently taking my first programming class in college and so far have been very good with understanding how to code basic things. This latest assignment has me confused and stumped.
My assignment is to:
Accept numeric input from the user (integer value)
Print out the square and cube of the number entered.
Make sure that the number is > 0.
Repeat the above three times.
If the number entered is <= 0 then end the program, telling the user why.
My issue is that I am unsure how the variables are to be set for this and how exactly to add the loop to repeat the process 3 times.
This is all I have so far and do not know where to go from here, any help would be appreciated. Thank you
import java.io.*;
public class Assignment3 //class name here, same as file name
{
public Assignment3() throws IOException{ //constructor, place class name here
// use BufferedReader class to input from the keyboard
// declare a variable of type BufferedReader
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//declare variable for input
String inputString;
// houseKeeping()
String yourNumber;
int number;
int totalSquare = 0;
int totalCube = 0;
int count;
int badNumber=0;
String squareCube = " Your number squared is" +square +"your number cubed is"+cube;
System.out.print("Enter a number: ");
inputString = input.readLine();
yourNumber = inputString;
}//end constructor
}
public static void main(String [] args) throws IOException
{
new Assignment3(); //class constructor name
}

I could just post the answer here, but then that wouldn't help you learn :)
Firstly, consider using a Scanner to get your inputs. Using BufferedReader will read input data as String. It is possible to convert String to int using Integer.parseInt() but it's more convenient to use Scanner.nextInt().
Secondly, about looping:
Since you want to loop 3 times, the following form of loop seems appropriate:
for (int i=0; i<3; i++) {
//read input, calculate square & cube
}
Inside the loop, you'll want to check for invalid entry (number <= 0), and if so, use break to jump out of the loop early and end the program.

Sorry for the bad format.. I tried too long to fix it on the site...
package com.ispecsoft.porkypig;
import java.io.*;
public class Assignment3 // class name here, same as file name
{
public Assignment3() throws Exception
{
}
public static void DoIt()
{
try
{
int xIn = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
for (int x = 0; x < 3; x++)
{
System.out.print("Enter a number: ");
xIn = Integer.parseInt(input.readLine());
int iSquare = xIn * xIn;
int iCube = iSquare * xIn;
System.out.println(x == 0 ? " Your number squared is ("+ iSquare + ") your number cubed is (" + iCube: ") Your number squared is (" + iSquare+ ") your number cubed is (" + iCube + ")");
}
}
catch (NumberFormatException e)
{
System.out.print("The character's you entered are not integers.. this application will now close. ");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
System.out.print("There was an IOException.. this application will now close. ");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
Assignment3.DoIt();
}
}

Related

Java, How to break a loop when input is empty? [duplicate]

This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 3 years ago.
The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.
Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....
I'm sure there is a quick and logical solution to this that I'm not thinking of.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
while(scan.hasNextInt()){
int n = scan.nextInt();
if (n > x){
x = n;
}
}
System.out.println("Largets number entered: " + x);
}
}
This should solve your problem:
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
try {
while(!scan.nextLine().isEmpty()){
int num = Integer.parseInt(scan.nextLine());
if(num > x) {
x = num;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Largest number entered: " + x);
scan.close();
}
}
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
String str = scanner.nextLine();
int x = 0;
try {
while(!str.isEmpty()){
int number = Integer.parseInt(str);
if (number > x){
x = number;
}
str = scanner.nextLine();
}
}
catch (NumberFormatException e) {
System.out.println("There was an exception. You entered a data type other than Integer");
}
System.out.println("Largets number entered: " + x);
}
}

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

How do I make my do while loop with user prompt work?

I'm creating an application that basically works as a guessing game. At the end of the game I want to ask the user if they want to play again. If they type "Y" or "y", the game will restart, if any other character is entered, then the loop ends.
public class NumberGame {
public static void main(String[] args) throws java.io.IOException {
int NumberGame;
int NumberUser;
char BonusResponse;
char charGen;
String Guess = " ";
String Bonus = " ";
do {
NumberGame = (int) (Math.random() * 10);
charGen = (char)(NumberGame + 48);
//for(NumberGame < 1; NumberGame++){
System.out.print("The computer generated number was " + NumberGame);
System.out.print("\nGuess a number between 1 and 9: ");
NumberUser = (char) System.in.read();
NumberUser = (int) (NumberUser - 48);
if (NumberGame > NumberUser)
Guess = " Too low! Try again";
else if (NumberGame == NumberUser)
Guess = " Congratulations, you win!";
else if (NumberGame < NumberUser)
Guess = " Too high! Try again";
System.out.println("You guessed " + NumberUser + "." + Guess);
if (NumberGame == NumberUser)
Bonus = "Now that you've won, wanna play again? Type Y to play again or any other key to exit:";
else
Bonus = " ";
System.out.println(Bonus);
BonusResponse = (char) System.in.read();
} while (BonusResponse == 'Y' || BonusResponse == 'y');
}
}
You could use the Scanner Class instead of plain System.in.read()
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
String response= sc.next();
You can use Scanner class as seen on this answer or BufferedReader as seen on this answer.
Example with BufferedReader class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Areas {
public static void main(String args[]){
float PI = 3.1416f;
int r=0;
String rad; //We're going to read all user's text into a String and we try to convert it later
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
System.out.println("Radius?");
try{
rad = br.readLine(); //We read from user's input
r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
}
catch(Exception e){
System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
Areas a = new Areas(); //We call this class again, so user can try it again
//You can also print exception in case you want to see it as follows:
// e.printStackTrace();
}
}
}
Example with Scanner class:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
}
You can try adding the reading code inside a do-while loop to validate user input. Then add this code after your while (BonusResponse == 'Y' || BonusResponse == 'y');
if (BonusResponse == 'y' || BonusResponse == 'Y') {
startApplication();
}
move all your main() code to startApplication() method. And change main to:
public static void main(String args[]) {
startApplication();
}
Also please follow Java naming conventions:
Except for variables, all instance, class, and class constants are in
mixed case with a lowercase first letter. Internal words start with
capital letters. Variable names should not start with underscore _ or
dollar sign $ characters, even though both are allowed.

Using nextLine() and nextInt() together in my context always gets an error

I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.

How to properly use try-catch?

I'm trying to process how to use try-catch. I understand it'll 'try' the main code, and if it doesn't work it'll catch it and execute something different. I want to also keep prompting the user to enter a proper value.
I keep getting the inputmismatch exception error, even if I set my catch to have that in its block.
To clarify: The try-catch is going to be there for when I ask the user for ints on how long they plan to stay, and what floor they'd like to be on. Therefore, the errors I'd like to handle involve non-integers and if they are out of bounds of the 'hotel'.
Here is my code:
public class Hotel{
public static void main(String[] args) throws IOException {
int choice = 0;
String guestName = " ";
int stayTime = 0;
int floorPref = 0;
System.out.println("Welcome to the Hotel California.");
Scanner sc = new Scanner(System.in);
Room[][] hotel = new Room[8][20];
for(int i = 0; i< hotel.length; i++){
for(int j = 0; j<hotel[i].length;j++){
hotel[i][j] = new Room(0,false,"none",0.00,0);
int roomNum = ((i+1) * 100) + (j + 1);
hotel[i][j].setRoom(roomNum);
int roomCheck = hotel[i][j].getRoomNumber();
if(roomCheck > 500){
hotel[i][j].setPrice(350.00);
}
else if(roomCheck < 500){
hotel[i][j].setPrice(200.00);
}
}
}
// Guest check-in interface.
do{
System.out.println("What business have you today?");
System.out.println("1. Guest Registration");
System.out.println("2. Guest Checkout");
System.out.println("3. Show me occupied rooms");
System.out.println("4. Exit");
choice = sc.nextInt();
if(choice == 1){
System.out.println("Tell us about yourself.");
System.out.println("Please input your name:");
guestName = sc.next();
System.out.print("How long are you planning to stay?");
try{
stayTime = sc.nextInt();
}
catch(InputMismatchException e){
System.out.println("Please input a valid integer.");
stayTime = sc.nextInt();
}
System.out.println("Great. What floor would you like to be on? Enter a number 1-8, 0 for no preference.");
floorPref = sc.nextInt();
System.out.println("The following rooms are available based on your floor preference (floors 1-8, 0 for no preference: ");
}
if(floorPref > 0){
for(int i = 0; i < hotel[floorPref].length; i++){
if(hotel[floorPref][(i)].getOccupation() == false){
System.out.print("Rooms " + hotel[floorPref-1][i].getRoomNumber() + ", ");
}
}
System.out.println("Are available today.");
}
else if(floorPref == 0){
for(int i = 0; i < hotel.length; i++){
for(int j = 0; j < hotel[i].length; j++){
System.out.print("Room " + hotel[i][j].getRoomNumber() + ", ");
}
}
System.out.println("Is available.");
}
}while(choice != 4);
}
}
The try-catch block you have right now is flawed, because once you get inside the catch block, all the user has to do is enter something that's not an integer to crash your whole program.
Instead, to get stayTime and all the other ints you pull from the Scanner, create a separate function that blocks until the user enters an int:
private static int parseIntFromScanner(Scanner sc) {
while(true) {
try {
int toReturn = sc.nextInt();
return toReturn;
} catch(InputMismatchException ime) {
//Continue back to the top of the loop, ask again for the integer
}
}
}
try to put this at the top of your code
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
and in your public static void throws IOException main delete throws IOException so it only remains public static void main
hope it will works
the following is small piece of code to divide.If user enters zero then it will go to catch and you can also enter number.
Note
the code will go catch only once.I have used depracated methods.This is just an example as per your requirement.
import java.io.DataInputStream;
import java.io.IOException;
public class test1 {
public static void main(String args[]) throws NumberFormatException, IOException
{
DataInputStream d=new DataInputStream(System.in);int x;
try {
x=Integer.parseInt(d.readLine());
int z=8;
System.out.println(z/x);
} catch (Exception e)
{
System.out.println("can not divide by zero");
x=Integer.parseInt(d.readLine());
}
}
}
To answer your question as to why it's still failing: all of the calls to nextInt() can throw InputMistmatchException, not only the one put inside the try part of a try-catch block. And that's what's happening now.
Another issue is calling nextInt a second time inside the catch block. Exceptions thrown inside a catch block require their own handling, separate from the try-catch block to which they belong. So, if nextInt inside the catch block throws an InputMismatchException, it will leave the try-catch block and work its way out from there. In the case of the posted code, that means main will terminate on the exception.
A side point, as musical_coder pointed out, the code needs to loop with the validation. Otherwise, it would end up without setting values if the second attempt to read a value fails.
BTW, see this: Redoing a try after catch in Java, for a tip on scanner use that will lead to more headaches. In fact, it tells why the handling with the try-catch you have now will always end up terminating the program. (it's a matter of how Scanner functions)

Categories

Resources