SitePoint Enthusiast
java beginner script problem
Hello
I am a beginner with java and i have a little script problem. I want my program to end its calculations when you add a non integer.
Can someone please help. I got it to the stage where if you enter 0 it will end. It should actually be if you enter a non integer than the program should end.
Kind regards
---------------------
package oving1;
//import java.util;
import java.util.Scanner;
public class Sum {
//main methord
public static void main(String[] args) {
//create scanner
Scanner input = new Scanner(System.in);
//read an initial data
System.out.print("Enter an int value(the program exits if the input is not integer): ");
int data = input.nextInt();
//keepreading data until input 0
int sum = 0;
while (data != 0)
{
sum += data;
//read next data
System.out.print(
"Enter an int value(the program exits if the input is not integer): ");
data = input.nextInt();
}
System.out.println("The sum is " + sum);
}
}
SitePoint Zealot
A simple way of handling: -
use input.next() and try to typecast into a int and then if it throws NumberFormatException than just exit the programme.
Better way of identifying the characters: -
use regular expressions and find out if there is any character in the String.
SitePoint Enthusiast
Thanks for the reply.
I got the answer today in class. If anyone is interested here is the script.
----------------------
package oving1;
import java.util.Scanner;
public class Sum {
//main methord
public static void main(String[] args) {
//create scanner
Scanner input = new Scanner(System.in);
//read an initial data
System.out.print("Enter an int value(the program exits if the input is not integer): ");
//String string = input.next();
//keepreading data until input 0
int sum = 0;
while (input.hasNextInt())
{
int data = input.nextInt();
sum += data;
//read next data
System.out.print(
"Enter an int value(the program exits if the input is not integer): ");
}
System.out.println("The sum is " + sum);
}
}
I didn't know about the Scanner class. I guess you learn something new everyday.
Might've been a bit less cluttered if you used a do-while, but that'll do the trick.
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks