I'm trying to ask the user for two two-digit numbers and then perform a length check and a type check on both of the numbers, then I want to output the sum of the numbers. Here's what I have so far:
package codething;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();
if(number.hasNextInt()) {
} else {
System.out.println("Error");
}
int m;
int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();
if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}
int sum = n + m;
System.out.println(sum);
}
}
At the moment my program won't even ask me for my second input. Not sure what to do :/
So several things:
-Don't construct more than one Scanner objects to read from System.in. It just causes problems.
-You're using String.valueOf() to convert an int to a String. It is better to simply check to make sure it is between 10 and 99.
-You check to make sure that the Scanner has a next int after you call nextInt which won't help. You need to make sure that there is a next int.
-A lot of your if statements have an empty if block and then you do something in the else. You can just do the opposite in the if and omit the else (Instead of if(length ==2) {} you can do if(length != 2) {//code}
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}
int m = 0;
if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}
if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);
Related
How to check in this code that the entered input is integer or not if not then ignore the non-integer values and display the rest numbers.
I have done the full coding but for checking the input is integer or not and then printing the value. How should I do it?
import java.util.Scanner;
class ques2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.print("how many number you want to enter= ");
i=sc.nextInt();
int input[]=new int[i];
System.out.println("Numbers should be great then 3");
for(j=0;j<i;j++)
{
input[j]=sc.nextInt();
}
System.out.println("Number entered are:");
for(j=0;j < i;j++)
{
System.out.println(input[j]);
}
System.out.println("Odd numbers are:");
for(j=0;j < i;j++)
{
if(input[j] % 2 != 0)
{
System.out.println(input[j]);
}
}
System.out.println("Palindrome numbers are:");
for(j=0;j < i;j++)
{
int rev=0,n,num;
n=input[j];
while(input[j] > 0)
{
num=input[j] % 10;
rev=num+(rev*10);
input[j]=input[j]/10;
}
if(n == rev)
{
System.out.println(n);
}
}
}
}
You could take a helper function:
public static boolean checkMe(String s) {
boolean amIValid = false;
try {
Integer.parseInt(s);
// s is a valid integer!
amIValid = true;
} catch (NumberFormatException e) {
//not an integer but you could continue with the rest numbers
}
return invalid;
}
You can check it by comparing the ASCII value whether it lies between 91 to 100.
If yes then it will be an Integer.
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String num;
String regex = "[0-9]+"; // to check the string only is made up of digits
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
num = input.next();
} while (!num.matches(regex));
int validNumber = Integer.parseInt(num);
/* .
.
. *\
You're already using sc.nextIn() which internally perform a regex-check as in #snr's post and a Integer.parseInt as in charly1212's post.
The only thing you should add is wrap it in a
try {
int i = sc.nextInt();
} catch(InputMismatchException e) {
//skip or repeat?
}
To deal with all cases, where the input is not an int (which includes values > Integer.MAX_VALUE and < Integer.MIN_VALUE)
The solution could look like this method, encapsulating all the input reading
private static int[] readNumbers() {
Scanner sc = new Scanner(System.in);
int i = -1;
while(i < 0){
try {
System.out.print("how many number you want to enter? ");
i=sc.nextInt();
} catch (InputMismatchException e){
System.out.println(sc.next() + " is not a number, try again");
}
}
List<Integer> numbers = new ArrayList<>();
System.out.println("Numbers should be greater then 3");
for(int j = 0; j < i; j++){
try {
numbers.add(sc.nextInt());
} catch (InputMismatchException e){
System.out.println("Skipping input " + sc.next());
}
}
return numbers.stream().mapToInt(Integer::intValue).toArray();
}
...
int input[] = readNumbers();
Please not, that the exception blocks invoke sc.next() to read the current line (which is not integer) and proceed with the next line (the new input), otherwise the scanner would not proceed its position.
I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>
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 am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.
I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.
System.out.println("Enter a ten digit binary number. Press 'Enter' after each digit. Only use one or zero. :");
binary[0] = keyboard.nextInt();
for (index = 1; index < 10; index++)
binary[index] = keyboard.nextInt();// fill array with 10 binary
// digits from user. User
// must press 'Enter' after
// each digit.
Try this:
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext())
{
final String input = scanner.next();
try
{
int num = Integer.parseInt(input, 2);
}
catch (NumberFormatException error)
{
System.out.println(input + " is not a binary number.");
//OR You may exit here, if you don't want to continue
}
}
Try this code part :
import java.util.Scanner;
public class InputTest
{
public static void main(String... args) throws Exception
{
Scanner scan = new Scanner(System.in);
int[] binary = new int[10];
for (int index = 0; index < 10; index++)
{
int number = scan.nextInt();
if (number == 0 || number == 1)
{
binary[index] = number;
System.out.println("Index : " + index);
}
else
System.exit(0);
}
}
}