So I have a working code that asks the user the height & width of a rectangle and then outputs the rectangle in asterics (*).
Now I want to implement a function public static int askPositiveInteger(String question, String messageIfError) {...} that uses scanner.hasNextInt() (checks for integer) and scanner.next() (throw away whatever nonsense the user wrote).
The function is supposed to ask the user for a positive integer using the message question. If the input is wrong it prints the error message messageIfError and asks again.
I wrote the function:
public static int askPositiveInteger(String question, String messageIfError) {
int num = -1;
do {
System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
num = scan.nextInt();
} else {
System.out.println("I need an int, please try again.");
scanner.next();
}
} while (num <= 0);
}
But I'm not sure how to implement it into my code:
public static void main(String[] args) {
int height, width, i, j;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the height of the rectangle: ");
height = scanner.nextInt();
System.out.print("Enter the width of the rectangle: ");
width = scanner.nextInt();
for(i = 1; i <= height; i++){
for(j = 1; j <= width;j++){
System.out.print("*");
}
System.out.print("\n");
}
scanner.close();
}
Your function dosen't really use the parameters String question and String messageIfError. You can integrate them in you function by just swap out the
System.out.print("Please enter a positive integer number: "); and
System.out.println("I need an int, please try again.");
with
System.out.print(question); and System.out.println(messageIfError);.
this would result in :
public static int askPositiveInteger(String question, String messageIfError, Scanner scan) {
int num = -1;
while(num <= 0){
System.out.print(question);
num = scan.nextInt();
if(num <= 0){
System.out.println(messageIfError);
}
scan.nextLine();
}
return num;
}
I changed the function also, that you take an existing Scanner and scan of the given one.
Implementing this new function in your Main-Programm would look like follows:
public static void main(String[] args) {
int height, width;
Scanner scan = new Scanner(System.in);
height = askPositiveInteger("Enter the height of the rectangle: ","I need an int, please try again.", scan);
System.out.println("h = " + height);
width = askPositiveInteger("Enter the width of the rectangle: ","I need an int, please try again.", scan);
scan.close();
for(int i = 1; i <= height; i++){
for(int j = 1; j <= width;j++){
System.out.print("*");
}
System.out.print("\n");
}
}
Is that roughly what you thought of?
Related
I'm attempting to write a loop, that when the user inputs Y, the loop continues, and when the user inputs N, the loop stops. However, when I try to assign the variable I get the error "Cannot convert from void to char" I'm obviously messing up somewhere along the line but I'm not sure where.
import java.util.Scanner;
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
char ans = System.out.print("Would you like to input another value? (Y or N)? ");
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
} ```
You're assigning ans to the result of System.out.print() which is a void method.
Instead, create the prompt beforehand and use the Scanner to take the input:
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
// New Prompt
System.out.print("Would you like to input another value? (Y or N)? ");
// Take input and set ans
char ans = input.next().charAt(0);
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
}
Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}
I am trying to write a Java program that:
In the main method, prompt the user for an integer number.
Store the number in a variable called inputNum.
Pass the inputNum to a method called computeAvg.
In computeAvg, prompt the user to input double values as many times as inputNum. computeAvg method should calculate and return the average of real numbers that user entered.
Print the result in your main method.
This is my code
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
computeAvg();
}
public static void computeAvg() {
System.out.println(inputnum);
System.out.println("Enter double values as inputnum ");
int y;
y=keyboard.nextInt();
}
}
There are several changes to be done in your code:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
System.out.println("The average is"+computeAvg(inputnum));
}
public static double computeAvg(int y)
{
double[] arr = new double[y];
System.out.println(y);
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
double sum = 0;
for(double a:arr){
sum +=a;
}
System.out.println(sum);
double average = sum/arr.length;
return average;
}
First one is that the value you first taken as the user input must be passed to the method. Here I done it in computeAvg(inputnum) And expect this method to return a double value.
Second one is You should declare the method to return a value void means no return. change it to double
public static double computeAvg(int y)
take the parameter from the main method (value you taken from the user.)
If you need to store multiple values better solutions is array.(There are many methods bust for a beginner stick to arrays) crate a double array to take multiple double values.
double[] arr = new double[y];
next loop your code for the number of times the user input and take the double values.
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
next create a double value sum and get the addition and the divide it to get the average (another double value).
for(double a:arr){
sum +=a;
}
Finally return the average to the main method where it prints.
I used static Scanner keyboard = new Scanner(System.in); because I used the same scanner in both methods.
Feel free to ask any question regarding the code.
I hope the comments in the code are self explanatory for what the problem is asking and how the code works:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer? ");
// here you are asking for the number of double numbers that will be
// entered
int inputnum = keyboard.nextInt(); // asking for the int input (varibale
// is stored in inputnum)
System.out.println("Average for all " + inputnum + " numbers is: "
+ computeAvg(inputnum));
}
public static double computeAvg(int inputnum) {
Scanner keyboard = new Scanner(System.in);
double eachInput = 0.0;
double sumInputs = 0.0;
for (int counter = 1; counter <= inputnum; counter++) {
System.out.println("Please enter a double as input #" + counter
+ ": ");
eachInput = keyboard.nextDouble(); // asking for double input
sumInputs += eachInput; // adding up each input
}
// calculating and returning average
return sumInputs / (double) inputnum;
}
The code below shows my progress, but I cannot print the numbers that were entered. I don't know where to put println("you entered the following numbers") in the loop so that it'll show up when the loop stops.
import java.util.Scanner;
public class aufgabe5 {
public static void main(String[] args) {
int x;
Scanner input = new Scanner(System.in);
System.out.println("How much numbers do you want to enter?");
x = input.nextInt();
int j = 1;
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[x];
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + j++ + ". number:");
numbers[i] = scanner.nextInt();
}
System.out.println("You entered following numbers");
System.out.println(x);
}
}
Change x like
System.out.println(x);
to Arrays.toString(int[]) like
System.out.println(Arrays.toString(numbers));
Edit
To print the array reversed,
String str = Arrays.toString(numbers).replace(", ", " ,");
str = str.substring(1, str.length() - 1);
System.out.println(new StringBuilder(str).reverse().insert(0, "[")
.append("]"));
Intialize the String before the loop, then keep adding the values to it.
After the loop finishes you can print the whole thing.
String someVar="You entered following numbers: ";
for(int 1=0;i<array.length;i++)
{
someVar=someVar+numbers[i]+",";
}
System.out.println(someVar);
Really having issues with this program I'm making. I've searched this site and a few others, although have yet to find a solution. It may look like I'm just soliciting help but I truly am stuck. I am to make a program that reads in 5 numbers from the user and average those numbers. My extent of knowledge of Java is the Scanner class and for loops, yet haven't used while loops yet. Here is the very poorly written code:
public class Average5
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
num = sc.nextInt();
}
I honestly have no clue what to do. More or less self taught.
public class Average5 {
public static void main(String args[]) {
int numlenngth = 5;
double total = 0;
Scanner sc = new Scanner(System.in);
for (int num1 = 0; num1 < numlenngth; num1++) {
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : " + (total / numlenngth));
}
}
output >>
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 2
Average : 1.2
For calculating exact average, you need to take double(sum) instead of int and add(sum) everytime with the user value.
public class Average5
{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to enter for calculating average: ");
int totalCount = sc.nextInt();
double sum=0;
for(int i= 0; i<totalCount; i++)
{
System.out.print("Please enter a number: ");
sum += sc.nextDouble();
}
System.out.println("Average of number is"+(sum/totalCount));
}
This is almost the same as the others posted, but it is limited to entering only 5 numbers and it takes care of possibly resulting floating number in the final division:
import java.util.Scanner;
public class Average5 {
private static final int TOTAL = 5;
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.format("You have to enter %d numbers now.\n", TOTAL);
for (int cnt = 1; cnt <= TOTAL; cnt++) {
System.out.format("Please enter number %d of %d: ", cnt, TOTAL);
sum += scanner.nextInt();
}
System.out.format("The average is %f.\n", sum / TOTAL);
scanner.close();
}
}
Here you can use the array to store the numbers:
public class Average5 {
private static final int MAX = 5;
public static void main(String[] args) {
int[] numbers = new int[MAX];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < MAX; i++) {
System.out.println("Please type the number");
numbers[i] = sc.nextInt();
}
float average = getAverage(numbers);
System.out.println("The average of the five numbers: " + average);
}
public static float getAverage(int[] arg0) {
int sum = 0;
float Ret = 0.0f;
if(arg0 != null) {
for(int i = 0; i < MAX; i++) {
sum += arg0[i];
Ret = sum / MAX;
}
return Ret;
}
}
This is not the only way to slove this problem.
int num = 0;
float total = 0f;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : "+(total/num));