Facing problem in java code while running in terminal - java

** I am Trying to print this pattern in JAVA
a/2 + a/3 + a/4 ....+ a/n
**
Here is my java code
import java.util.*;
public class ser
{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of a and n");
int a,i,n;
double s=0;
a=in.nextInt();
n=in.nextInt();
for(i=1;i<n;i++)
s=s+(double)a/(i+1);
System.out.println("ssss = "+s);
}
}
I'm using Kali linux and today I'm facing this error while running my java code in terminal
Enter the value of a and n
a 12
Error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ser.main(one.java:9)```

There is no problem1 with your code.
The problem is with the input that you are giving to the program.
Assuming that you are running from the command line, the way to compile and run the program is like this.
steve#greybeast:/tmp$ javac ser.java
steve#greybeast:/tmp$ java ser
Enter the value of a and n
2 12
ssss = 4.206421356421357
steve#greybeast:/tmp$
See?
When it asks me to "enter a and n", I type 2 12 <ENTER>.
And it works (as far as I can tell).
What you have been doing is entering letters, numbers in quotation marks and other things. But the program as you have written it2 expects only 2 integers with whitespace between them. And when it gets something that it doesn't expect, the nextInt() call throws an InputMismatchException.
1 - Actually, there is a problem. Your code ignores a number of important Java style conventions. For example, class names should NOT start with a lowercase letter, and code should be correctly indented. But these things only matter to humans who have to read your code.
2 - I hope that >you< wrote it. 'Cos if you copied it rather than writing it yourself, you are cheating yourself of the opportunity to learn to program.

Issue is with your input. Code is expecting integer value as input and you are providing 'a'. You need to provide integer.

You don't need to provide a and then 12, just provide 12, press enter and then provide the next Integer. Right now I think it's trying to decode a as an integer. Just provide the integers in order of their input and it should work.

brother!! just hardcore "a" to the print statement instead for taking it as an input.
may be this code will help u
import java.util.*;
public class ser
{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of n");
int i,n;
n=in.nextInt();
for(i=2;i<=n;i++)
{
System.out.print("a/"+i);
if(i==n)
break;
else
System.out.print(" + ");
}
}
}

To clear confusion, I modified your code as below.
Provide your input in two separate lines.
import java.util.*;
public class ser
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of a and n");
int a, i, n;
String a1, n1;
double s = 0;
a1 = in.nextLine(); // Reading as string value the complete line
n1 = in.nextLine();
// checking whether the value acquired is number or not
if (!isNumeric(a1.toString())) {
System.out.println("Please provide a valid number without alphbets or symbol, you have typed:" + a1);
System.exit(0);
}
if (!isNumeric(n1.toString())) {
System.out.println("Please provide a valid number without alphbets or symbol, you have typed:" + n1);
System.exit(0);
}
a = Integer.parseInt(a1);
n = Integer.parseInt(n1);
for (i = 1; i < n; i++)
s = s + (double) a / (i + 1);
System.out.println("ssss = " + s);
}
// will check whether the string passed is number or not
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
}

Related

no output after infinite while loop with hasNext() java [duplicate]

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
}
} finally {
scan.close();
}
}
Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:
if (scan.nextLine() == null) System.exit(0);
and
if (scan.nextLine() == "") System.exit(0);
They did not work.... The program continues and messes with the original intention,
The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.
There are two ways that the user could do this:
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.
Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.
(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)
The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods. (See How do I compare strings in Java?)
Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").
String comparison is done using .equals() and not ==.
So, try scan.nextLine().equals("").
You will have to look for specific pattern which indicates end of your input say for example "##"
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
if (line.equals("##")) {
System.exit(0);
scan.close();
}
}
} finally {
if (scan != null)
scan.close();
}
In this case, I recommend you to use do, while loop instead of while.
Scanner sc = new Scanner(System.in);
String input = "";
do{
input = sc.nextLine();
System.out.println(input);
} while(!input.equals("exit"));
sc.close();
In order to exit program, you simply need to assign a string header e.g. exit. If input is equals to exit then program is going to exit. Furthermore, users can press control + c to exit program.
You can check the next line of input from console, and checks for your terminate entry(if any).
Suppose your terminate entry is "quit" then you should try this code :-
Scanner scanner = new Scanner(System.in);
try {
while (scanner.hasNextLine()){
// do your task here
if (scanner.nextLine().equals("quit")) {
scanner.close();
}
}
}catch(Exception e){
System.out.println("Error ::"+e.getMessage());
e.printStackTrace();
}finally {
if (scanner!= null)
scanner.close();
}
Try this code.Your terminate line should be entered by you, when you want to close/terminate the scanner.
With this approach, you have to explicitly create an exit command or an exit condition. For instance:
String str = "";
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) {
//Handle string
}
Additionally, you must handle string equals cases with .equals() not ==. == compares the addresses of two strings, which, unless they're actually the same object, will never be true.
Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int is a double produces a double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args){
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("Hi temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}
You can check if the user entered an empty by checking if the length is 0, additionally you can close the scanner implicitly by using it in a try-with-resources statement:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter input:");
String line = "";
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNextLine()
&& (line = scan.nextLine().toLowerCase()).length() != 0) {
System.out.println(line);
}
}
System.out.println("Goodbye!");
}
}
Example Usage:
Enter input:
A
a
B
b
C
c
Goodbye!

Repeatedly check whether integer input has leading zeroes

I need the user to enter an integer input, check whether it starts by 0 and tell the user to enter another integer if that is the case
I tried parsing the integer input to a string, that works but only once. The string cannot be edited when program loops
I think the solution should not at all involve strings because i need the program to loop and check over and over until the input is valid (ie has no leading zeroes)
Splitting each digit of the int into an array does not work also because the ways i found pass by string.
public static void main(String[] args){
Scanner key = new Scanner(System.in);
int in= 0;
boolean looper=true;
while (looper == true) {
System.out.println("Enter an integer");
in = key.nextInt();
/* check whether in has any leading zeroes, example of
wrong input: 09999, 0099*/
if (/*in has no leading zeroes*/)
looper = false;
}
key.close();
}
Maybe another answer would be to have a method that creates a brand new string every time the program loops, so maybe like a recursion that automatically creates strings, not sure if that's even a thing though.
You can make it cleaner by using a do-while loop instead of while(true). Note that an integer starting with 0 is an octal number e.g.
public class Main {
public static void main(String[] args) {
int x = 06;
System.out.println(x);
// x = 09; // Compilation error - out of range
}
}
Thus, 06 is a valid integer. For your requirement, you can input to a String variable and prompt the user to again if it starts with a zero. If the input does not start with a zero, try parsing it to an int and process it if it succeeds; otherwise, loopback e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String input = "";
int in = 0;
boolean valid = true;
do {
System.out.print("Enter an integer: ");
input = key.nextLine();
if (input.startsWith("0")) {
System.out.println("Invalid input");
valid = false;
} else {
try {
in = Integer.parseInt(input);
System.out.println("You entered " + in);
// ... process it
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
valid = false;
}
}
} while (!valid);
}
}
A sample run:
Enter an integer: 09999
Invalid input
Enter an integer: xyz
Invalid input
Enter an integer: 123
You entered 123
As an aside, never close a Scanner(System.in) because it also closes System.in and there is no way to open it without rebooting the JVM.

Writing a WHILE loop in Java to compute the largest value in a sequence that prevents no user input

I'm trying to learn (self-taught) Java by reading Big Java, Late Objects from by Cay Horstmann. I'm using repl.it to write my code (if you may want to look it up, it's public)
A selfcheck question of Chapter 4 Loops is:
How can you overcome the problem of when the user doesn't provide any input in the algorithm of section 4.7.5 (titled Maximum and Minimum) and the WHILE loop just terminates the program for this reason ?
They basically ask to rewrite the code so it solves this problem.
The information of section 4.7.5 you need to solve this problem: To compute the largest value in a sequence, keep a variable that stores the largest element that you have encountered, and update it when you find a larger one.
(This algorithm requires that there is at least one input.)
double largest = in.nextDouble();
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > largest)
{
largest = input;
}
}
This is what the book suggests as the answer to this problem (but I disagree):
One solution is to do all input in the loop and introduce a Boolean variable that checks whether the loop is entered for the first time.
double input = 0;
boolean first = true;
while (in.hasNextDouble())
{
double previous = input;
input = in.nextDouble();
if (first) { first = false; }
else if (input == previous) { System.out.println("Duplicate input"); }
}
I don't fully understand the first sentence. And I disagree this as a solution for the problem because (as far as I can tell) it tests whether the input has been entered before, instead of testing if any sort of user input has been provided..
I tried to merge those two sections of code together but I can't seem to make it work. Or more specific: figure out how to build it. What variables / loops do I need? In which order do I write this?
I've made a flowchart in Visio of the first section of code but have no clue how to continue.
This is what I've written so far:
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number: ");
double largest = 0;
while (input.hasNextDouble())
{
double value = input.nextDouble();
if (value > largest)
{
largest = value;
System.out.println("The largest input till now is: " + largest);
}
}
Can someone:
Ask me questions which help me to solve this question? I.e. Tell me what tools I need (WHILE, FOR etc.)
Provide a solution in text which I can hopefully transform in code
Or write the code for me (I haven't learned arrays yet, so please solve it without)
Thanks in advance,
So I worked on this for a bit and I think I have something close to what you're looking for using a do while loop.
This code accepts user input first, then checks it's value in comparison to the last input and return either "Input a higher value", "Duplicate number found", or it sets the last number entered to the current number.
I hope this helps you get your code to where you'd like it to be! I'm still new, so I apologize if this is not entirely optimized.
Also, I have not added a way to exit the loop, so you may want to add a check on each iteration to see if the user would like to continue.
public static void main(String[] args) {
double userInput = 0;
double prevNum = 0;
boolean hasValue = false;
boolean exitCode = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
userInput = sc.nextDouble();
do {
if (userInput<prevNum) {
System.out.println("Please enter a number higher than " + prevNum);
hasValue=true;
}
else if (userInput==prevNum) {
System.out.println("Duplicate input detected.");
hasValue=true;
}
else {
prevNum = userInput;
hasValue = true;
}
}
while(hasValue==false);
System.out.println(prevNum);
System.out.println(userInput);
}
while(exitCode==false);
}
If you want compute if the number entered is the largest entered from the beginning but declare it at the largest if it's the first iteration then do this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean flag = true;
double largest = 0;
System.out.println("Enter the number: ");
while (input.hasNextDouble()){
double value = input.nextDouble();
if (flag) {
flag = false;
largest = value;
}
else if (value > largest) largest = value;
System.out.println("The largest input till now is: " + largest);
System.out.println("Enter a new number: ");
}
}

How do I read and print numbers in Java? [duplicate]

What class can I use for reading an integer variable in Java?
You can use java.util.Scanner (API):
import java.util.Scanner;
//...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).
If you are using Java 6, you can use the following oneliner to read an integer from console:
int n = Integer.parseInt(System.console().readLine());
Here I am providing 2 examples to read integer value from the standard input
Example 1
import java.util.Scanner;
public class Maxof2
{
public static void main(String args[])
{
//taking value as command line argument.
Scanner in = new Scanner(System.in);
System.out.printf("Enter i Value: ");
int i = in.nextInt();
System.out.printf("Enter j Value: ");
int j = in.nextInt();
if(i > j)
System.out.println(i+"i is greater than "+j);
else
System.out.println(j+" is greater than "+i);
}
}
Example 2
public class ReadandWritewhateveryoutype
{
public static void main(String args[]) throws java.lang.Exception
{
System.out.printf("This Program is used to Read and Write what ever you type \nType quit to Exit at any Moment\n\n");
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String hi;
while (!(hi=r.readLine()).startsWith("quit"))System.out.printf("\nYou have typed: %s \n",hi);
}
}
I prefer the First Example, it's easy and quite understandable.
You can compile and run the JAVA programs online at this website: http://ideone.com
Check this one:
public static void main(String[] args) {
String input = null;
int number = 0;
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
input = bufferedReader.readLine();
number = Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.out.println("Not a number !");
} catch (IOException e) {
e.printStackTrace();
}
}
Second answer above is the most simple one.
int n = Integer.parseInt(System.console().readLine());
The question is "How to read from standard input".
A console is a device typically associated to the keyboard and display from which a program is launched.
You may wish to test if no Java console device is available, e.g. Java VM not started from a command line or the standard input and output streams are redirected.
Console cons;
if ((cons = System.console()) == null) {
System.err.println("Unable to obtain console");
...
}
Using console is a simple way to input numbers. Combined with parseInt()/Double() etc.
s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);
s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);
check this one:
import java.io.*;
public class UserInputInteger
{
public static void main(String args[])throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int number;
System.out.println("Enter the number");
number = Integer.parseInt(in.readLine());
}
}
This causes headaches so I updated a solution that will run using the most common hardware and software tools available to users in December 2014. Please note that the JDK/SDK/JRE/Netbeans and their subsequent classes, template libraries compilers, editors and debuggerz are free.
This program was tested with Java v8 u25. It was written and built using
Netbeans IDE 8.0.2, JDK 1.8, OS is win8.1 (apologies) and browser is Chrome (double-apologies)
- meant to assist UNIX-cmd-line OG's deal with modern GUI-Web-based IDEs
at ZERO COST - because information (and IDEs) should always be free.
By Tapper7. For Everyone.
code block:
package modchk; //Netbeans requirement.
import java.util.Scanner;
//import java.io.*; is not needed Netbeans automatically includes it.
public class Modchk {
public static void main(String[] args){
int input1;
int input2;
//Explicity define the purpose of the .exe to user:
System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n"
+ "Commented and coded for C/C++ programmers new to Java\n");
//create an object that reads integers:
Scanner Cin = new Scanner(System.in);
//the following will throw() if you don't do you what it tells you or if
//int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9
System.out.println("Enter an integer wiseguy: ");
input1 = Cin.nextInt(); //this command emulates "cin >> input1;"
//I test like Ernie Banks played hardball: "Let's play two!"
System.out.println("Enter another integer...anyday now: ");
input2 = Cin.nextInt();
//debug the scanner and istream:
System.out.println("the 1st N entered by the user was " + input1);
System.out.println("the 2nd N entered by the user was " + input2);
//"do maths" on vars to make sure they are of use to me:
System.out.println("modchk for " + input1);
if(2 % input1 == 0){
System.out.print(input1 + " is even\n"); //<---same output effect as *.println
}else{
System.out.println(input1 + " is odd");
}//endif input1
//one mo' 'gain (as in istream dbg chk above)
System.out.println("modchk for " + input2);
if(2 % input2 == 0){
System.out.print(input2 + " is even\n");
}else{
System.out.println(input2 + " is odd");
}//endif input2
}//end main
}//end Modchk

How to read integer value from the standard input in Java

What class can I use for reading an integer variable in Java?
You can use java.util.Scanner (API):
import java.util.Scanner;
//...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).
If you are using Java 6, you can use the following oneliner to read an integer from console:
int n = Integer.parseInt(System.console().readLine());
Here I am providing 2 examples to read integer value from the standard input
Example 1
import java.util.Scanner;
public class Maxof2
{
public static void main(String args[])
{
//taking value as command line argument.
Scanner in = new Scanner(System.in);
System.out.printf("Enter i Value: ");
int i = in.nextInt();
System.out.printf("Enter j Value: ");
int j = in.nextInt();
if(i > j)
System.out.println(i+"i is greater than "+j);
else
System.out.println(j+" is greater than "+i);
}
}
Example 2
public class ReadandWritewhateveryoutype
{
public static void main(String args[]) throws java.lang.Exception
{
System.out.printf("This Program is used to Read and Write what ever you type \nType quit to Exit at any Moment\n\n");
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String hi;
while (!(hi=r.readLine()).startsWith("quit"))System.out.printf("\nYou have typed: %s \n",hi);
}
}
I prefer the First Example, it's easy and quite understandable.
You can compile and run the JAVA programs online at this website: http://ideone.com
Check this one:
public static void main(String[] args) {
String input = null;
int number = 0;
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
input = bufferedReader.readLine();
number = Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.out.println("Not a number !");
} catch (IOException e) {
e.printStackTrace();
}
}
Second answer above is the most simple one.
int n = Integer.parseInt(System.console().readLine());
The question is "How to read from standard input".
A console is a device typically associated to the keyboard and display from which a program is launched.
You may wish to test if no Java console device is available, e.g. Java VM not started from a command line or the standard input and output streams are redirected.
Console cons;
if ((cons = System.console()) == null) {
System.err.println("Unable to obtain console");
...
}
Using console is a simple way to input numbers. Combined with parseInt()/Double() etc.
s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);
s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);
check this one:
import java.io.*;
public class UserInputInteger
{
public static void main(String args[])throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int number;
System.out.println("Enter the number");
number = Integer.parseInt(in.readLine());
}
}
This causes headaches so I updated a solution that will run using the most common hardware and software tools available to users in December 2014. Please note that the JDK/SDK/JRE/Netbeans and their subsequent classes, template libraries compilers, editors and debuggerz are free.
This program was tested with Java v8 u25. It was written and built using
Netbeans IDE 8.0.2, JDK 1.8, OS is win8.1 (apologies) and browser is Chrome (double-apologies)
- meant to assist UNIX-cmd-line OG's deal with modern GUI-Web-based IDEs
at ZERO COST - because information (and IDEs) should always be free.
By Tapper7. For Everyone.
code block:
package modchk; //Netbeans requirement.
import java.util.Scanner;
//import java.io.*; is not needed Netbeans automatically includes it.
public class Modchk {
public static void main(String[] args){
int input1;
int input2;
//Explicity define the purpose of the .exe to user:
System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n"
+ "Commented and coded for C/C++ programmers new to Java\n");
//create an object that reads integers:
Scanner Cin = new Scanner(System.in);
//the following will throw() if you don't do you what it tells you or if
//int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9
System.out.println("Enter an integer wiseguy: ");
input1 = Cin.nextInt(); //this command emulates "cin >> input1;"
//I test like Ernie Banks played hardball: "Let's play two!"
System.out.println("Enter another integer...anyday now: ");
input2 = Cin.nextInt();
//debug the scanner and istream:
System.out.println("the 1st N entered by the user was " + input1);
System.out.println("the 2nd N entered by the user was " + input2);
//"do maths" on vars to make sure they are of use to me:
System.out.println("modchk for " + input1);
if(2 % input1 == 0){
System.out.print(input1 + " is even\n"); //<---same output effect as *.println
}else{
System.out.println(input1 + " is odd");
}//endif input1
//one mo' 'gain (as in istream dbg chk above)
System.out.println("modchk for " + input2);
if(2 % input2 == 0){
System.out.print(input2 + " is even\n");
}else{
System.out.println(input2 + " is odd");
}//endif input2
}//end main
}//end Modchk

Categories