Data entry problem with incorrect result? - java

Seeing the code.
When I start the program, it doesn't let me insert the scanner class input into the switch, how come?
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = in.nextInt();
switch (select) {
case 1:
System.out.println("first name:");
String n = in.nextLine();
System.out.println("surname:");
String s = in.nextLine();
System.out.println(n + s);
break;
}
Output:
select:
1
first name:
surname:

The nextLine method is ignored because there is a newline character left in the nextInt method. There are two ways to fix this problem.
Solution 1:
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = in.nextInt();
in.nextLine();
Solution 2:
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = Integer.parseInt(in.nextLine());

Replacing Scanner with BufferedReader and InputStreamReader could fix it, try:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("select:");
int select = Integer.parseInt(input.readLine());
switch (select) {
case 1:
System.out.println("first name:");
String n = Integer.parseInt(input.readLine());
System.out.println("surname:");
String s = Integer.parseInt(input.readLine());
System.out.println(n + s);
break;
}

Related

Java Try-Catch Exception Calculator

So I'm trying to make a user input calculator using try-catch and exception. The program keeps on repeating and couldn't get the actual input for the numbers and it also includes the statement Wrong input. Please try again.
Any idea on how to fix this?
import java.util.*;
public class Calculator
{
public static void main(String[] args) {
int x=1;
do {
try {
System.out.println("Menu");
System.out.println("1-Addition");
System.out.println("2-Subtraction");
System.out.println("3-Multiplication");
System.out.println("4-Divison");
System.out.println("5-Modulos");
System.out.println("6-Exit");
System.out.println("Choose option: ");
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.print("Input two numbers:");
String dimension = scan.nextLine();
String[] parts = dimension.split(" ");
int a = Integer.parseInt(parts[0]);
int b = Integer.parseInt(parts[1]);
int c=a+b;
System.out.println("Sum = " +c);
break;
case 2:
System.out.print("Input two numbers:");
String dif = scan.nextLine();
String[] difference = dif.split(" ");
int num1 = Integer.parseInt(difference[0]);
int num2 = Integer.parseInt(difference[1]);
int d=num1-num2;
System.out.println("Difference = " +d);
break;
case 3:
System.out.print("Input two numbers:");
String multi = scan.nextLine();
String[] product = multi.split(" ");
int num3 = Integer.parseInt(product[0]);
int num4 = Integer.parseInt(product[1]);
int p=num3*num4;
System.out.println("Product = " +p);
break;
case 4:
System.out.print("Input two numbers:");
String div = scan.nextLine();
String[] quotient = div.split(" ");
int num5 = Integer.parseInt(quotient[0]);
int num6 = Integer.parseInt(quotient[1]);
int q=num5/num6;
System.out.println("Quotient = " +q);
break;
case 5:
System.out.print("Input two numbers:");
String mod = scan.nextLine();
String[] modulo = mod.split(" ");
int num7 = Integer.parseInt(modulo[0]);
int num8 = Integer.parseInt(modulo[1]);
int m=num7%num8;
System.out.println("Modulos = " +m);
break;
case 6:
System.out.println("Now exiting program...");
break;
}
} catch (Exception e) {
System.out.println("Wrong input. Try again.");
}
} while (x==1);
}
}
You need to do this
int choice = Integer.parseInt(scan.nextLine());
because you are reading next input with readline()
String dimension = scan.nextLine();
and \n is already present it the stream when you enter your option with nextInt() because nextint() never reads the \n which you leave behind by pressing Enter button.
You should add:
scan.skip("\n");
right after
int choice = scan.nextInt();
Why? Because nextInt() reads next integer from input. And it leaves new line character at the end on the input. It's like:
1<enter>
After that you invoke scan.nextLine() which reads everything up to next new line character. In fact there is 1 new line character in the buffer. And here your nextLine() reads an empty string.
To solve that issue you have to skip buffered new line characters with scan.skip("\n").
EDIT:
in addition, your code doesn't allow you to exit, because you're not changing your x variable. Try to change it after System.out.println("Now exiting program...");. It will work ;)
This will help you to identify root cause:
} catch (Exception e) {
System.out.println("Wrong input. Try again.");
e.printStackTrace();
}

Suggestions with Strings from File

I am trying to read from a external file. I have successfully read from the file but now I have a little problem. The file contains around 88 verbs. The verbs are written in the file like this:
be was been
beat beat beaten
become became become
and so on...
What I need help with now is that I want a quiz like programe where only two random strings from the verb will come up and the user have to fill inn the one which is missing. Instead of the one missing, I want this("------"). My english is not so good so I hope you understand what I mean.
System.out.println("Welcome to the programe which will test you in english verbs!");
System.out.println("You can choose to be tested in up to 88.");
System.out.println("In the end of the programe you will get a percentage of total right answers.");
Scanner in = new Scanner(System.in);
System.out.println("Do you want to try??yes/no");
String a = in.nextLine();
if (a.equals("yes")) {
System.out.println("Please enter the name of the file you want to choose: ");
} else {
System.out.println("Programe is ended!");
}
String b = in.nextLine();
while(!b.equals("verb.txt")){
System.out.println("You entered wrong name, please try again!");
b = in.nextLine();
}
System.out.println("How many verbs do you want to be tested in?: ");
int totalVerb = in.nextInt();
in.nextLine();
String filename = "verb.txt";
File textFile = new File(filename);
Scanner input = new Scanner(textFile);
for (int i = 1; i <= totalVerb; i++){
String line = input.nextLine();
System.out.println(line);
System.out.println("Please fill inn the missing verb: ");
in.next();
}
System.out.println("Please enter your name: ");
in.next();
You can do something like this
import java.util.Scanner;
import java.io.*;
public class GuessVerb {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = in.nextLine();
File file = new File(fileName);
Scanner input = new Scanner(file);
String guess = null;
int correctCount = 0;
while(input.hasNextLine()) {
String line = input.nextLine(); // get the line
String[] tokens = line.split("\\s+"); // split it into 3 word
int randNum = (int)(Math.random() * 3); // get a random number 0, 1, 2
String newLine = null; // new line
int wordIndex = 0;
switch(randNum){ // case for random number
case 0: newLine = "------ " + tokens[1] + " " + tokens[2];
wordIndex = 0; break;
case 1: newLine = tokens[0] + " ------ " + tokens[2];
wordIndex = 1; break;
case 2: newLine = tokens[0] + " " + tokens[1] + " -------";
wordIndex = 2; break;
}
System.out.println(newLine);
System.out.println("Please fill inn the missing verb: ");
guess = in.nextLine();
if (guess.equals(tokens[wordIndex])){
correctCount++;
}
}
System.out.println("You got " + correctCount + " right");
}
}
Above is complete running program.

Getting 'cannot find symbol' error

I am getting cannot find symbol error. I am making a program that could perform various mathematical operations. I am getting the error here:
a=Double.parseDouble(in.readLine());
The error is:
cannot find symbol- method readLine()
I am giving my whole program:
// I(Rachit Bhargava) am writing my first program that includes almost every feature of Mathematical Operations.
import java.io.*;
import java.lang.*;
import java.lang.Math;
public class All_In_One
{
public static void main(String args[])throws IOException
{
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(read);
double a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, r, s, t, u, v, w, x, y, z, i1, a1, i2, a2;
char ch1, ch2;
System.out.println("To which topic is your question based upon?");
System.out.println("Enter 'm' for Mathematics and 'g' for Geometry");
System.out.println("Please enter your choice.");
ch1= (char)(in.read());
switch (ch1)
{
case 'm':
System.out.println("What operation do you want to do?");
System.out.println("Enter 'a' for addtion, 's' for subtraction, 'm' for multiplication, 'd' for division, 't' for finding out simple interest(with amount), 'c' for finding out compound interest(with amount) and 'b' for finding out both(with amount) and their difference");
System.out.println("Please enter your choice.");
ch2= (char)(in.read());
switch (ch2)
{
case 'a':
System.out.println("Please enter first number.");
a=Double.parseDouble(in.readLine());
System.out.println("Please enter second number.");
b=Double.parseDouble(in.readLine());
c = a+b;
System.out.println("Sum = "+c);
break;
case 's':
System.out.println("Please enter first number.");
a=Double.parseDouble(in.readLine());
System.out.println("Please enter second number.");
b=Double.parseDouble(in.readLine());
c = a-b;
System.out.println("Difference = "+c);
break;
case 'm':
System.out.println("Please enter first number.");
a=Double.parseDouble(in.readLine());
System.out.println("Please enter second number.");
b=Double.parseDouble(in.readLine());
c = a*b;
System.out.println("Answer = "+c);
break;
case 'd':
System.out.println("Please enter first number.");
a=Double.parseDouble(in.readLine());
System.out.println("Please enter second number.");
b=Double.parseDouble(in.readLine());
c = (a>b)? (a/b):(b/a);
System.out.println("Answer = "+c);
break;
case 't':
System.out.println("Please enter principal");
p=Double.parseDouble(in.readLine());
System.out.println("Please enter rate of interest.");
r=Double.parseDouble(in.readLine());
System.out.println("Please enter time(in years)");
t=Double.parseDouble(in.readLine());
i = p*r*t/100;
a = p+i;
System.out.println("Simple interest = "+i);
System.out.println("Amount = "+a);
break;
case 'c':
System.out.println("Please enter principal");
p=Double.parseDouble(in.readLine());
System.out.println("Please enter rate of interest.");
r=Double.parseDouble(in.readLine());
System.out.println("Please enter time(in years)");
t=Double.parseDouble(in.readLine());
a = p*(Math.pow(((100+r)/100), t));
i = a-p;
System.out.println("Compound Interest = "+i);
System.out.println("Amount = "+a);
break;
case 'b':
System.out.println("Please enter principal");
p=Double.parseDouble(in.readLine());
System.out.println("Please enter rate of interest.");
r=Double.parseDouble(in.readLine());
System.out.println("Please enter time(in years)");
t=Double.parseDouble(in.readLine());
i1 = p*r*t/100;
a1 = p+i1;
a2 = p*(Math.pow(((100+r)/100), t));
i2 = a-p;
d = a2-a1;
System.out.println("Simple interest = "+i1);
System.out.println("Amount(as by simple interest) = "+a1);
System.out.println("Compound Interest = "+i2);
System.out.println("Amount(as by compound interest) = "+a2);
System.out.println("Difference in interests and amount = "+d);
break;
default:
System.out.println("Invalid input :(");
}
break;
case 'g':
System.out.println("Work In Progress!");
break;
default:
System.out.println("Invalid Input :(");
}
System.out.println("Thank you for using my program");
System.out.println("All credits goes to Rachit Bhargava");
}
}
Please help me solve this problem!
You need do the following 2 changes:
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(in);
Use read.readLine() rather than in.readLine();
such as,
a=Double.parseDouble(read.readLine());
InputStreamReader class does not have readLine method . Scanner is a better alternative to collect user inputs.
As you may see in InputStreamReader javadoc, there's no readLine method. Maybe you want to use the readLine method from your BufferedReader read variable since BufferedReader has this method:
b = Double.parseDouble(read.readLine());
By the way:
This line:
BufferedReader read = new BufferedReader(read);
should be:
BufferedReader read = new BufferedReader(in);
The fact that compiles doesn't mean it will work as expected.
I would recommend you changing the name of your variables for something more meaningful, for example buffReader instead of read, firstNumber instead of a, secondNumber instead of b, and so on...
Well that's because InputStreamReader doesn't have a readLine() method. You need to use BufferedReader
Change your code:
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(read);
to:
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(in);
Then you can do the following:
a = Double.parseDouble(read.readLine());
Alternatively you can use Scanner which will allow you to do Scanner.nextDouble():
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();

Exception in main thread java.util.NoSuchElementException

I'm working on this project to improve my skill in Java. My goal is to write a program that reads the line from a specified doc or text file (depending on which the user wants to open; int 2 or 1 respectively.) and then asks the user to input their document name (without the file extension), and then reads the first line in the document or text file. I want it to do this as many times as the user wants. But I keep getting NoSuchElementException while executing the code.
public class switches {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("How many files would you like to scan?");
System.out.println("Enter # of files to scan: ");
int countInput = input.nextInt();
input.close();
for (int count = 0; count < countInput;) {
System.out.println("Please enter a file name to scan. ");
System.out.println("1 for .txt, 2 for .doc");
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
switch (choice) {
default: {
do {
System.out.println("Please pick "
+ "either 1: txt or 2: doc");
choice = keyboard.nextInt();
} while (choice != 1 && choice != 2);
}
case 1: {
System.out.println("Txt file name:");
keyboard.nextLine();
String txtName = keyboard.nextLine();
File openTxtFile = new File("C:/Users/Hp/Documents/" + txtName
+ ".txt");
Scanner firstTxtLine = new Scanner(openTxtFile);
String printedTxtLine = firstTxtLine.nextLine();
firstTxtLine.close();
System.out.println("The first line " + "of your text file is: "
+ printedTxtLine);
keyboard.close();
count++;
break;
}
case 2: {
System.out.println("Doc file name:");
keyboard.nextLine();
String docName = keyboard.nextLine();
File openDocFile = new File("C:/Users/Hp/Documents/" + docName
+ ".doc");
Scanner firstLine = new Scanner(openDocFile);
String printedDocLine = firstLine.nextLine();
firstLine.close();
System.out.println("The first line"
+ " of your word document is: " + printedDocLine);
keyboard.close();
count++;
break;
}
}
}
}
}
If you remove the line input.close(); on line 14. This should solve your problem. According to the documentation, it will throw a NoSuchElementException - "if input is exhausted".

Java - read String and int: java.util.NoSuchElementException

I try to read an int and after it a string, in this way:
String wantA = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter A");
wantA = in.nextLine();
in.close();
// some code
int want = 0;
Scanner in = new Scanner(System.in);
System.out.println("Save? Press 1 for yes, or 0 for no");
want = in.nextInt();
in.close();
after it prints
Save? Press 1 for yes, or 0 for no
then I get
java.util.NoSuchElementException
How can I fix it?
Remove in.close(); - it is killing the input stream (which never gets reopened).
Instead just keep using the same Scanner.
Change your code to this:
Scanner in = new Scanner(System.in);
System.out.println("Enter A");
String wantA = in.nextLine();
System.out.println("Save? Press 1 for yes, or 0 for no");
int want = in.nextInt();

Categories