I've just begun to learn how to program with Java and I had a question with regard to the scanner input. I'm building a little program that simply asks the user for input to create a numerical array. I was wondering if there was a way to check for the numerical input encompassing the for loop, instead of putting a while check on each of my cases in the for loop.
As well, any other comments or suggestions on my code to help me improve and understand what I am doing would be greatly appreciated!
Thank you!
Edit: I'm calling this class from a 'Main' class where I run the program.
import java.util.Scanner; //Import the use of the Java Scanner
public class ArrayBuild { // Open Application
private static Scanner input;
public Double[] anArray;
public static int arrayCount = 0;
public ArrayBuild() { // Constructor for ArrayBuild object
input = new Scanner(System.in);
arrayCount++;
System.out.println("This will be Array: " + arrayCount);
// Array Size Declaration
System.out.println("Enter Array Size: ");
while (!input.hasNextInt()) {
System.out.println("Please enter an integer for Array size!");
input.next();
}
int n = input.nextInt();
anArray = new Double[n]; // Create 'anArray' of size n
//
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0) {
System.out.println("Enter First Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i > 0 && i < (n - 1)) {
System.out.println("Enter Next Number: \n");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i == (n - 1)) {
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
} // End For Loop
}
} // Close Class
One thing you can do to simplify and write clean code is to always separate the repeating code. In your case, inside the for loop, you are only changing the print statement inside the if condition. Take the other code outside like this--
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0)
System.out.println("Enter First Number: ");
else if (i > 0 && i < (n - 1))
System.out.println("Enter Next Number: \n");
else if (i == (n - 1))
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
} // End For Loop
Related
Scanner scanner = new Scanner(System.in);
int grade[] = new int[3];
for (int i = 0; i < grade.length; i++) {
System.out.println("Enter your test score:");
grade[i] = scanner.nextInt();
}
I've been trying to figure out how to make it so if the user input is below 0 or above 100 it will ask again. I'm very new to Java and this is the first language I'm learning. I would appreciate any pointers. Do I need to use a do-while loop instead of a for loop for this? Or do I implement an if statement into the for loop?
You can validate the input by putting an if block inside the for loop.
However, since your loop will only execute three times, you should change your increment condition only when user enters correct input or else not.
You also can use while loop here.
Here is some example code:
for (int i = 0; i < grade.length; i++)
{
System.out.println("Enter your test score:");
if(grade[i] < 0 || grade > 100)
{
i--;
continue;
}
grade[i] = scanner.nextInt();
}
The if block will check that if the input is outside boundaries, decrement i and restart the loop.
What I suggest is, instead of incrementing i in loop, you can increase the value in if condition. Like below,
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int grade[] = new int[3];
for (int i = 0; i < grade.length;) {
System.out.println("Enter your test score:");
int temp = scanner.nextInt();
if (temp >= 0 && temp <= 100) {
grade[i] = temp;
i++;
}else {
System.out.println("Please enter valid score");
}
}
scanner.close();
}
This basically gets a input value from user, if the value is greater or equal to 0 && lesser or equal to 100,then adds it to the Array and increments the loop count(array index value we can call it), else, prints message asking for valid input.
Instead of shoving the validation logic somewhere within the loop, you could also write a small utility method which neatly asks for valid input, and continues to do so until the user finally inputs something valid:
int promptInt(Scanner scanner, int min, int max, String errorMessage) {
while (true) {
int input = scanner.nextInt();
if (min <= input && input <= max) {
return input;
}
else {
System.out.println(errorMessage);
}
}
}
You could then simplify the loop:
int grade[] = new int[3];
for (int i = 0; i < grade.length; i++) {
System.out.println("Enter your test score:");
grade[i] = promptInt(0, 100, "Please enter a valid number");
}
I have a user enter a string of integers and I add them to an ArrayList, however I need to validate each entry is a positive integer. I have tried do/while loops, nested while loops, while with nested if and each runs into its own set of problems.
As an example of my current setup:
User enters for example: 1 2 3 4
pageVar is my Scanner and pageRef is my ArrayList
System.out.println("Please enter the page reference string: ");
while(pageVar.hasNext()) {
if (pageVar.hasNextInt() && pageVar.nextInt() > 0) {
pageRef.add(pageVar.nextInt());
}
else if (pageVar.nextInt() < 0) {
System.out.println("Please enter valid page reference string: ");
}
else if (!pageVar.hasNext()) {
pageVar.close();
}
}
running this my while gets stuck waiting for more input and I cannot determine how to break it.
Every time you call nextInt() you consume a value. Store the value before you compare.
while (pageVar.hasNextInt()) {
int v = pageVar.nextInt();
if (v > 0) {
pageRef.add(v);
} else {
System.out.printf("%d: is not a valid reference value.%n", v);
}
}
//you could try validating the int as it is being entered with a for loop??
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int[] numbers = new int[4];
for(int i = 0; i < numbers.length;i++)
{
System.out.println("Enter numbers: ");
numbers[i] = kbd.nextInt();
while(numbers[i] < 0)
{
System.out.println("Please enter a positive integer");
numbers[i] = kbd.nextInt();
}
}
}
}
I am attempting to validate multiple scanner inputs with paired If-Else blocks in a single while loop. The behavior that I am interested in achieving is to the current validation If-Statement request the user to re-enter input or move on to the subsequent input / selection blocks.
Right now, I am using the continue keyword which returns to the beginning of the While loop. Would using a do...while loop be better suited for this? Thank you.
while (count < numCars) {
System.out.println("Enter car type");
String name = scanner.next();
if (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers");
continue;
} else {
// re-enter name
}
System.out.println("Enter max speed");
int maxSpeed = scanner.nextInt();
if (maxSpeed == 100 || maxSpeed > 100) {
System.out.println("Max speed is not valid. Please re-enter");
continue;
} else {
// re-enter age
count++;
}
}
The functionality you want for every block can be achieved using while instead of if-else statements. I also structured your code in a nicer/more organized way:
int count = 0, numCars = 3; // Example value
String name;
int maxSpeed;
while (count < numCars) {
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
while (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers.");
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
}
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
while (maxSpeed >= 100) {
System.out.println("Max speed is not valid. Please re-enter.");
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
}
count++;
}
I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...
I need to write a program in Java that prompts the user to enter three integer. Among these integers entered, the largest of said integers will need to be found in addition to the square root. I'm just a beginner, and I appreciate any and all assistance.
import java.util.Scanner;
public class largest {
public static void main (String [] args) {
int Integer1;
int Integer2;
int Integer3;
Scanner input=new Scanner(System.in);
System.out.println("Enter 3 integers:");
Integer1 = input.nextInt();
Integer2 = input.nextInt();
Integer3 = input.nextInt();
if (Integer1 > Integer2);
System.out.println (Integer1);
if (Integer1 > Integer3);
System.out.println (Integer1)
This is all I have so far, and I'm dubious that I'm even on track. Please, help.
I would recommend using Math.max as aioobe suggested, but if you want to implement the logic yourself use this:
import java.util.Scanner;
import java.lang.Math;
class prog {
public static void main (String [] args) {
int Integer1;
int Integer2;
int Integer3;
Scanner input = new Scanner(System.in);
System.out.println("Enter 3 integers:");
Integer1 = input.nextInt();
Integer2 = input.nextInt();
Integer3 = input.nextInt();
if (Integer1 > Integer2) {
if (Integer1 > Integer3) {
System.out.println (Integer1);
System.out.println (Math.sqrt((float)Integer1));
}
else {
System.out.println (Integer3);
System.out.println (Math.sqrt((float)Integer3));
}
}
else if (Integer2 > Integer3) {
System.out.println (Integer2);
System.out.println (Math.sqrt((float)Integer2));
}
else {
System.out.println (Integer3);
System.out.println (Math.sqrt((float)Integer3));
}
}
}
For anything more than 3, your best off using Math.max. The (float) part is converting the integer to a float, otherwise the square root wouldn't be precise (as integers are whole numbers
There are a lot of ways to do this and you can use different libraries and data types , I'm not sure you are allowed to use for loop , array or Lists .
Mostly for these kind of jobs you need to use loops, that make it simple and easy to understand .
Here are few different ways that you can do it :
In this example if you need to get more than 3 entries simply modify the number 4 to number of integers that you need to receive from user.
int num, tmp = 0;
Scanner input = new Scanner(System.in);
for (int i = 1; i < 4; i++) {
System.out.printf("Enter integer number %d :", i);
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
}
System.out.printf("the largest number is :%d and the Square is: %s", tmp, Math.sqrt((float) tmp));
second Way without using the for loop:
int num, tmp = 0;
Scanner input = new Scanner(System.in);
System.out.printf("Enter integer number 1 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("Enter integer number 2 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("Enter integer number 3 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("the largest number is :%d and the Square is: %s", tmp, Math.sqrt((float) tmp));
Always try to use less variables, that's make your application more memory efficient.