So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
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 am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.
I´m totally new to Java and I´m stuck. I have to create the game "guess the Number". I´m able to do the most parts but I´m don´t now how to handle the User Input if its a String.
I want to be able to tell the User that the Input was not correct if he enters a String, and repeatedly ask for Input. It would be great if someone could help me here :)
Here is my Code:
import java.util.Scanner;
import java.util.Random;
public class SWENGB_HW_2 {
public static void main(String[] args) {
System.out.println("Welcome to the guess the number game!\n");
System.out.println("Please specify the configuration of the game:\n");
Scanner input = new Scanner(System.in);
System.out.println("Range start number (inclusively):");
int startRange;
startRange = input.nextInt();
System.out.println("Range end (inclusively):");
int endRange;
endRange = input.nextInt();
System.out.println("Maximum number of attemps:");
int maxAttemp;
maxAttemp = input.nextInt();
System.out.println("Your Task is to guess the random number between "
+ startRange + " and " + endRange);
Random randGenerator = new Random();
int randNumber = randGenerator.nextInt((endRange - startRange) + 1)
+ startRange;
int numberOfTries = 0;
System.out
.println("You may exit the game by typing; exit - you may now start to guess:");
String exit;
exit = input.nextLine();
for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) {
int guess;
guess = input.nextInt();
if (guess == randNumber) {
System.out.println("Congratz - you have made it!!");
System.out.println("Goodbye");
} else if (guess > randNumber) {
System.out.println("The number is smaller");
} else if (guess < randNumber) {
System.out.println("The number is higher");
}
}
if (numberOfTries >= maxAttemp) {
System.out.println("You reached the max Number of attempts :-/");
}
}
}
You can create a utility method that looks like this:
public static int nextValidInt(Scanner s) {
while (!s.hasNextInt())
System.out.println(s.next() + " is not a valid number. Try again:");
return s.nextInt();
}
and then, instead of
startRange = input.nextInt()
you do
startRange = nextValidInt(input);
If you want to deal with the "exit" alternative, I'd recommend something like this:
public static int getInt(Scanner s) throws EOFException {
while (true) {
if (s.hasNextInt())
return s.nextInt();
String next = s.next();
if (next.equals("exit"))
throw new EOFException();
System.out.println(next + " is not a valid number. Try again:");
}
}
and then wrap the whole program in
try {
...
...
...
} catch (EOFException e) {
// User typed "exit"
System.out.println("Bye!");
}
} // End of main.
Btw, the rest of your code looks great. I've tried it and it works like a charm :-)
You could check that the scanner has an int before you attempt to read it. You can do that by calling hasNextInt() with something like
while (input.hasNext() && !input.hasNextInt()) {
System.out.printf("Please enter an int, %s is not an int%n", input.next());
}
int startRange = input.nextInt();
I have to write a java program that computes the greatest common divisor of two positive integers. Program has to check for the positive integers only. My problem is that when I enter a negative integer and then a non-numeric string, my program stops running. Bellow is my code:
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
System.out.print("Enter a positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
a = sc.nextInt();
while (a <= 0){
System.out.print("Please enter a positive integer: ");
a = sc.nextInt();
}
System.out.print("Enter another positive integer: ");
while (!sc.hasNextInt()){
System.out.print("Please enter a positive integer: ");
sc.next();
}
b = sc.nextInt();
while (b <=0){
System.out.print("Please enter a positive integer: ");
b = sc.nextInt();
}
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
}
Try this:
import java.util.Scanner;
public class A {
public static void main (String[] args){
int a, b, m, n, remainder;
a = validInput();
b = validInput();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
static int validInput() {
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("Please enter a positive integer: ");
String tmp = sc.next();
if (tmp.matches("^\\d+$")) {
return Integer.parseInt(tmp);
}
}
}
}
I suggest you to make your programs more modular, as you can see it's benefits in a simple program like this.
/* prompt a */
String a = sc.next();
/* prompt b */
String b = sc.next();
if (isValid(a) && isValid(b)) {
int ia = Integer.parseInt(a);
int ia = Integer.parseInt(b);
/* calculations and such */
}
boolean isValid(String num) {
try {
int i = Integer.parseInt(num);
if (i < 0) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
return true;
}
It shound work, even if i don't try it. I have just 2 advise as you look new in coding :
-When you make code, try to use function. Normally, you should never copy/paste.
-Try to put full name to your variable, particulary if you share your code on a forum, it would be more simple to people to understand what you did, and help you :)
import java.util.regex.Pattern;
import java.util.Scanner;
class GCD {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int a, b, m, n, remainder;
a=askInt();
b=askInt();
m = a;
n = b;
while (n != 0){
remainder = m%n;
m = n;
n = remainder;
}
System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
}
private int askInt(){
System.out.print("Enter a positive integer: ");
String tampon = sc.nextLine();
while(!Pattern.matches("\p{Digit}",tampon)){
System.out.print("Please enter a positive integer: ");
String tampon = sc.nextLine();
}
return Integer.valueOf(tampon);
}
}
In your first while you call next(), but in your second you use nextInt(). If you enter at the first time a negative Integer, you ll step to the next while with the nextInt(). So you ll get an exception if the user is entering a String with something else than numbers, because the scanner cant get the value of keys or something else. A smarter way would be to catch the exception and use it for a endless while like this:
while(true)
System.out.print("Please enter a positive Number: ");
try{
a = sc.nextInt();
if(a>-1){
break;
}
}catch(Exception ignore){
}
}
This code will run until the user enters a positive number. If he enters something else than numbers, the exception will come and will be ignored and the while will go on, if the number was not positive (bigger than -1 in this case) the while will not break.
I've created this code to get unlimited values of integers, store them, and calculate the mean. It also does it in a squared format. My problem is, I created it so that the while loop only stops when the the number 0 is entered. However, I only put it there as a substitute, as it's the only way i could test the rest of the code to ensure it all works.
What I really want to do it have the while loop continue until the user provides input that is not an integer. Ive tried everything, using hasNextint() or nextint and so forth, what can I do?
import java.io.*;
import java.util.*;
public class InputStats {
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
int inputNumber; // One of the integers input by the user.
int sum; // The sum of all the integers.
int count; // The number of integers that have been entered.
double mean; // The mean value of the integers, rounded to 2 decimal places.
int squarein; // Value of squared number.
int sumsquare; // The sum of the squares of all the integers.
double meansquare; // The mean value of the squares of integers, rounded to 2 decimal places.
/* Initialize the summation and counting variables. */
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
/* Read and process the user's input. */
System.out.println("Enter your first positive integer: ");
inputNumber = TextIO.nextInt();
while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running sum.
squarein = inputNumber; //
sumsquare = squarein * squarein; //square inputs
count++; // Count the input by adding 1 to count.
System.out.println("Enter your next positive integer, or 0 to end: ");
inputNumber = TextIO.nextInt();
}
/* Display the result. */
if (count == 0) {
System.out.println("You didn't enter any data!");
} else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
You should read your values in as a string and then convert them to integers with Integer.parseInt(string);
That way you can use the following function to check if they're integers
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Your program would then look like this:
import java.io.*;
import java.util.*;
public class InputStats {
// *** I added this to help your while loop ***
public static boolean isInteger(String s) {
// check if a string is an integer, eg "10" is 10 but "w" is not an int
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
// *** I added this to store the input as a string first ***
String input; // The original string inputted by the user
int inputNumber;
int sum;
int count;
double mean;
int squarein;
int sumsquare;
double meansquare;
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
System.out.println("Enter your first positive integer: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
// *** I made this while it's an integer so it stops when it's a string ***
while (isInteger(input)) {
inputNumber = Integer.parseInt(input);
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein * squarein;
count++;
System.out.println("Enter your next positive integer, or a non integer to end: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
}
if (count == 0) {
System.out.println("You didn't enter any data!");
}
else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
// *** I removed this because it was no longer needed *** TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
hasNextInt() should work
while(TextIO.hasNextInt()) {
inputNumber = TextIO.nextInt();
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein*squarein;
count++;
System.out.println("Enter your next positive integer: ");
}
Another thing, why do you call TextIO.nextInt() before your System.outs? It doesn't seem necessary and could possibly throw an error.
Use a boolean flag. Set it to false initially and when user has inputted set it to true.
boolean userInputted = false;
while (!userInputted) {
.
.
.
// if user has inputted
userInputted = true;
}
You could have the user input one line of text with numbers separated by commas and use .split(",") to separate into an array of strings, then loop through that array by the .length and apply .trim() to each string to remove trailing space, then use Integer.parseInt(strarray[i]) to convert the strings to integers. And obviously put it all in a try...catch in case the user inputs badly formatted data.
What you need is a way to tell if what the user inputs is a number or something else.
Try something like this function.
//Function to parse the input from provided scanner, and return null
//if input is not a number
public static Integer parsedInputFrom(Scanner sc){
String input= sc.next();
Integer inputNumber=null;
try{
inputNumber = Integer.parseInt(input);
} catch (NumberFormatException n){
return null;
}
return inputNumber;
}