public class Solution {
public static void main(String args[])
Scanner sc=new Scanner(System.in);
for(int i=0;i<5;i++){
int input1=sc.nextInt();
sc.nextLine();
String str1=sc.nextLine();
Double input2=sc.nextDouble();
}
}
}
This is my code. I only got this exception in "int" and "double" input only in for loop. IF I write it out-side of for loop it working fine. Please any one can help me solve this problem, because I am getting this error in my TCS exam.
Unfortunately your question does no give me much information, however I will try to answer anyway (need that rep). Im assuming the issue you run into is a InputMismatchException ? This is probably something to do with you trying to pass a double (i.e. 12.0) into an int. Using something like System.out.println("Enter Int Input:") can help you highlight which input type you should be providing on the line. try/catch blocks can stop the error being thrown.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
for (int i = 0; i < 5; i++) {
System.out.println("i: " + i);
System.out.println("Enter Int Value:");
int input1 = sc.nextInt();
sc.nextLine();
System.out.println("Enter String Value:");
String str1 = sc.nextLine();
System.out.println("Enter Double Value:");
Double input2 = sc.nextDouble();
}
} catch (InputMismatchException e) {
System.out.println("Invalid input entered for variable type.");
}
}
Related
I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. I was encouraged to use a for loop, but I don't see how that would work. I can calculate the number of characters using length(), but I can't figure out how to make my method work. This is what I have so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
return;
}
public static int GetNumOfCharacters(int userCount) {
int i = 0;
String userInput = "";
userCount = userInput.length();
return userCount;
}
}
My method is not returning the length of the string, it just gives me 0 or an error.
Right now, you are never calling your "GetNumOfCharacters" method in your main. The way Java programs work, is by calling the main method and executing line per line what lies there. So you need to call you method from inside the main method. On the other hand, it should get the Stirng as a parameter, so you can get its length. It would look something like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
int lenInput = GetNumOfCharacters(userInput);
System.out.println("The length was: "+lenInput+" characters");
}
public static int GetNumOfCharacters(String userInput) {
int len = userInput.length();
return len;
}
A problem is that you are not actually calling the method
so try
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
System.out.println ("The length is " + GetNumOfCharacters (userInput))
}
// need to pass string into this method
public static int GetNumOfCharacters(String myString) {
int userCount = myString.length();
return userCount;
}
}
Your question included the line:
I was encouraged to use a for loop, but I don't see how that would
work.
There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string:
for (int len = 0; ; len++) {
try {
text.charAt(len);
} catch (StringIndexOutOfBoundsException ex) {
return len;
}
}
That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop.
Problems with your code:
No Function call
Add function call in main() as int count=GetNumOfCharacters(userInput);
Parameter datatype mismatch
change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) {
Unwanted return statement in main()
remove the return from main()
Not displaying the value returned from GetNumOfCharacters
Add System.out.print("Number of characters: "+ count); inside main()
Code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
int count=GetNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int GetNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
OR
Function is not really needed,you can remove the function and do it like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
System.out.print("Number of characters: "+ userInput.length());
}
If you don't want to use predefined methods, you can do like this..
public static void main(String args[]){
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.println("You entered: "+userInput);
char a[]=userInput.toCharArray();
int count=0;
for(char c : a){
count++;
}
System.out.println("length of the string is:"+count);
}
public class Main{
public static void main(String args[]){
int i = nextInt();
}
public int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()){
scanner.nextLine();
Printer.println(Printer.PLEASE_NUMBER);
}
i=scanner.nextInt();
scanner.close();
return i;
}
}
The code above is how I'm trying to force a user to input a int value, but I get the nosuchelement exception, as the scanner.nextLine() reads a NULL.
In c++ the software waits for the user to input something. Is there anything I can do to force the program to stop, wait for the user to input something and then make the check?
EDIT:
So I'm having problems regardless, if I use scanner outside of Main class, it gives that error...
If you want the user to input and the scanner to pick up solely an integer value Scanner provides the method:
int i = scanner.nextInt();
Where i will store the next value entered into the console. It will throw an exception if i is not an integer.
Here is an example: Let's say I want the user to input a number and then I want to spit it back out to the user. Here would be my main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please print your number: ");
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
}
Now to check whether i is a integer you can use an if statement. However if you want the program to repeat until the user inputs an integer you can use a while loop or a do while loop where the loop's arguments would check if i is an integer.
Hope this is what you were looking for! By the way avoid naming your method nextInt() as the import java.util.Scanner; already has that method name. Don't forget imports as well!
You can do this:
public static void main(String[] args) {
System.out.println("" + nextInt());
}
public static int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!scanner.hasNextInt()){
System.out.println("Please enter a number:");
scanner.nextLine();
}
i = scanner.nextInt();
scanner.close();
return i;
}
This will cause the program to stop and wait for input each time the loop is executed. It will keep looping until it has an int in the scanner.
This works. There surely is a better solution.
EDIT As predicted. Check this,
import java.util.Scanner;
public class NewMain{
static boolean badNumber;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please print your number: ");
try{
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
badNumber = false;
}
catch(Exception e){
System.out.println("Bad number");
sc.next();
badNumber = true;
}
}while(badNumber);
}
}
package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.
I need int num to only accept numbers. If I input letters I get an error. Is there a way to immediately flag letters, or do I have to take num in as a string and run loops?
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input a number.");
int num = input.nextInt();
}
}
You must use Scanner.hasNextInt():
It Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
public static void main(String[] args)
{
System.out.println("Input a number.");
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num = sc.nextInt();
System.out.println(num);
}
You probably want to do something like this:
import java.util.InputMismatchException
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input an integer.");
int num = 0; // or any other default value
try {
num = input.nextInt();
} catch (InputMismatchException e) {
System.out.println("You should've entered an integer like I told you. Fool.");
} finally {
input.close();
}
}
}
If the user enters something that is not an integer, the code within the catch block will be executed.
If I enter the wrong input(example , if I enter String instead of Integer) loop is not ending, it wont get input next time. Here(below) i attach the entire program. can you please help this?. Thanks in advance!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* #author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
On an InputMismatchException you are doing i--, so the loop condition is modified to prevent the loop from ending without the needed input. If you read the API documentation for Scanner.nextInt() you should notice the following:
If the translation is successful, the scanner advances past the input that matched.
This means that if the input cannot be translated to int, the scanner does not advance. So on the next invocation of nextInt() it will re-read the exact same, non-int, input and fail again. You will need to read past that non-integer token before attempting to get an int again.
Again, don't mess with the loop index inside of the loop as this can cause problems down the road. Instead use a while loop which is much cleaner and much easier to debug 3 months from now:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
what about the below?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}