In the main method I am reading the input from system.in and passing it to while condition. But it is not working. Each time it takes default 53 cases. Could not figure out where is the mistake.
If I manually assign int num = 15 instead of int num = br.read() just above the while loop. It works fine.
public class Parenthesis
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int num = br.read();
while(num > 0)
{
System.out.println(num-- + "Chances Left");
String str = br.readLine();
if(isParenthesis(str))
System.out.println("Cool Rudra");
else
System.out.println("Poor Rudra");
}
}
public static boolean isParenthesis(String str)
{
if(str == "Rudra")
return true;
else
return false;
}
}
Use below
int num = Integer.parseInt(br.readLine());
instead of
int num = br.read();
Another way to get intfrom user
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
Related
In a part of my program, I put a while loop to repeatedly ask for inputs. There is an option to type in the letter "F" and break the loop.
This is my program:
public class Example {
public static void main(String[] args) {
int x = 0;
ArrayList Numbers = new ArrayList();
while (x==0) {
System.out.println("Type your number:");
Scanner s = new Scanner(System.in);
if (s.equals("f") || s.equals("F")) {
x = 1;
}
else if (!s.equals("f") && !s.equals("F")) {
int n = Integer.parseInt(s.next());
Numbers.add(n);
}
}
}
}
When I run the program, I type some numbers and then type "F". I see this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "F"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Example.main(Example.java:13)
I believe the String "F" can pass through my else if but I don't know why. How can I solve this?
You are comparing a string with a Scanner obj. Lets see how a scanner object works in java.
Scanner myObj = new Scanner(System.in);
String myInput = myObj.nextLine(); // Read user input
Then you can compare your myInput to the character 'f' or 'F'
You cannot directly compare a scanner object with a string. You will need to take some input using scanner and then you can compare that input with other types.
Try running this code.
public class Example {
public static void main(String[] args) {
int x = 0;
ArrayList Numbers = new ArrayList();
Scanner sc = new Scanner(System.in);
while (x==0) {
System.out.println("Type your number:");
String s = sc.nextLine();
if (s.equals("f") || s.equals("F")) {
x = 1;
}
else if (!s.equals("f") && !s.equals("F")) {
int n = Integer.parseInt(s.next());
Numbers.add(n);
}
}
}}
Program to count how many times a particular character, letter or number occur in a sentence.
However I keep getting message:
Resource leak: 'sc' is never closed
I am using Java and Eclipse. What should I do?
import java.util.Scanner;
class Number-count {
public static void number - count(String args[]) {
String s;
char ch;
int count = 0;
Scanner SC = new Scanner(System. in );
System.out.println("Enter a sentence");
String str = sc.nextLine();
System.out.println("Enter a character to be searched for occurence");
s = sc.nextLine();
char c = s.charAt(0);
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Character " + c + " occur " + count + " times");
}
}
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method
SC.close();
after your scanner work completed put: sc.close();
It is working 100%
Try this code
public static void number - count(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
try{
//your code
}
finally {
sc.close();
}
}
If you want to use the scanner globally in a class(which is the case sometimes)
try this:
static Scanner sc = new Scanner(System.in);
/* Making it easy for beginners, when we use Scanner sc it is required to be close once we have taken all inputs from user, to close use sc.close(); */
package basicjava;
import java.util.*;
public class sumbyuser {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your numbers for summation : ");
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a+b;
System.out.println("Summation is : "+sum);
}
}
Try sc.close();
After the using the scanner inputs :
import java.util.*;
public class Func1 {
public static void CalculateSum() {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a + b;
System.out.println("The sum is " + sum);
}
public static void main(String[] args) {
CalculateSum();
}
}
I have a program that is supposed to ask the user for a number and it will determine whether it is a palindrome or not. It's supposed to keep asking for numbers until EOF is input - So far it asks for the number twice and doesn't seem to be doing the while loop correctly.
Any insight is appreciated
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
String num = scanner.nextLine();
String reverse = "";
while (scanner.hasNextLine())
{
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
num = scanner.nextLine();
reverse = "";
}
System.out.println("\nProgram ended on request");
}
}
This worked for me; unless you need num or reverse outside the while loop it should work.
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
while (scanner.hasNextLine())
{
String num = scanner.nextLine();
String reverse = "";
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
}
System.out.println("\nProgram ended on request");
}
}
I would separate the palindrome test into its' own method. You could do that in a one line method like
public static boolean isPalindrome(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
but I would prefer to iterate the first half of the characters and compare them to the second half in reverse like
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i * 2 <= chars.length; i++) {
if (chars[i] != chars[chars.length - i - 1]) {
return false;
}
}
return true;
}
Then your main can invoke that in an infinite loop (terminating on the lack of input) like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number to check if it is a palindrome:");
if (!scanner.hasNextLine()) {
break;
}
String num = scanner.nextLine();
if (isPalindrome(num)) {
System.out.printf("%s is a palindrome%n", num);
} else {
System.out.printf("%s is NOT a palindrome%n", num);
}
}
System.out.println("Program ended on request");
}
i have a function to read user input. it takes a parameter to choose reading Ints or Strings. When i try to make sure that it reads only Ints with while(!sc.hasNextInt()) it works, but only when i step it in debug mode. whenever i try to use it while program is running it throws an exception regardless of input being a number or characters.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Databaz.ctecka(Databaz.java:14)
at Databaz.main(Databaz.java:38)
this points me to sc.next(); line in my function:
static String ctecka(int volba)
{
Scanner sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next(); //this is where exception points
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
sc.close();
return vystup;
}
function is being used from code:
int volba = Integer.parseInt(ctecka(1)); //it returns String so i parse it
That happens because you close your scanner sc.close(); which closes your inputStream then you try to access it again (have a look here), so to solve your problem, generalize your scanner variable, and then close it only when you finish all the ctecka() method calls, like the following:
Scanner sc;
private void some_method(){
int volba1 = Integer.parseInt(ctecka(1));
int volba2 = Integer.parseInt(ctecka(1));
int volba3 = Integer.parseInt(ctecka(2));
int volba4 = Integer.parseInt(ctecka(3));
sc.close();
}
String ctecka(int volba){
sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next();
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
return vystup;
}
This is what I have written so far but when exception is raised it does not again ask the user for input.
do {
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = br.readLine();
key = Integer.parseInt(temp);
} while (key < 0 && key > 9);
if (key < 0 || key > 10)
throw new InvalidStartingStonesException(key);
player1 = new KeyBoardPlayer();
player2 = new KeyBoardPlayer();
this.player1 = player1;
this.player2 = player2;
state = new KalaGameState(key);
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
} catch (IOException e) {
System.out.println(e);
}
As soon as that NumberFormatException is thrown, you jump out of the loop and down to the catch. If your try-catch block is inside your while loop, it'll have the effect you're looking for. You may need to adjust the condition on the loop.
An alternative way is to check if the string input matches a regular expression for an integer. If it doesn't match, you ask for the input again.
See Teleteype.readInt() from the Java Project Template. The basics of it is that you read input as a String, and then you convert it to an integer using Integer.parseInt(), which will throw NumberFormatException if the contents of the String is not an integer, which you can handle by catching the NumberFormatException.
What I would recommend is instead of using all these exceptions is to make separate methods that read specific data types. (Ex.)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args){
int n = getInteger("Enter integer: ");
System.out.println(n);
}
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
return Integer.parseInt(in);
}
}
while (true) {
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
key = Integer.parseInt(br.readLine());
if (key > -1 && key < 10)
break;
else
System.out.println("Invalid number of stones. Choose from 0 - 9");
}