How to Use Scanner close in this Prorgram? - java

import java.util.Scanner; //Scanner is imported here
public class Reverse {
public static void main(String[] args) {
int rev=0, rem;
Scanner s = new Scanner(System.in); //Scanner is used here and error is shown in this line
System.out.println("Enter a number ");
int a=s.nextInt();
int b=a;
while(b!=0)
{
rem=b%10;
rev=rev*10+rem;
b=b/10;
}
System.out.println("The reverse of the number is " +rev);
if(a==rev)
{
System.out.println("The number is Palindrome.");
}
else
{
System.out.println("The number is not Palindrome");
}
}
}

use s.close(); at the end within main function.
Your program will look like this:-
public static void main(String[] args) {
int rev=0, rem;
Scanner s = new Scanner(System.in); //Scanner is used here and error is shown in this line
System.out.println("Enter a number ");
int a=s.nextInt();
int b=a;
while(b!=0)
{
rem=b%10;
rev=rev*10+rem;
b=b/10;
}
System.out.println("The reverse of the number is " +rev);
if(a==rev)
{
System.out.println("The number is Palindrome.");
}
else
{
System.out.println("The number is not Palindrome");
}
s.close(); //SCANNER ENDS HERE.

Related

How to accept any number of more than two digits in Java?

I have to write a program that will accept any number of more than two digits and then display the reverse of that number. How should i write the code for the “accept any number of more than two digits” part?
This is my code:
import java.util.Scanner;
public class Reversenum
{
public static void main(String args [])
{
int num, reversenum=0;
System.out.println(“Input a number and press enter”);
Scanner in= new Scanner(System.in);
num= in.nextInt();
for (;num!=0;)
{
reversenum= reversenum*10;
reversenum= reversenum+num%10;
num=num/10;
}
System.out.println(“Reverse number =“+reversenum);
}
}
Do this:
public static void main(String args []) {
int num=0, reversenum=0;
boolean flag = true;
while(flag) {
try {
System.out.println("Input a number and press enter");
Scanner in= new Scanner(System.in);
num= in.nextInt();
if(num>99) {
break;
}else {
continue;
}
}catch (Exception e) {
continue;
}
}
for (;num!=0;)
{
reversenum= reversenum*10;
reversenum= reversenum+num%10;
num=num/10;
}
System.out.println("Reverse number ="+reversenum);
}
this will ask the user to enter a number with more than 2 digits until it has received the number
do {
System.out.println(“Input a number and press enter”);
num= in.nextInt();
} while(num < 100);
add this where you get your input number

Java while loop not breaking after "break" statement

import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
while(true){
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}
The user should be able to put in multiple numbers until -1 is reached. Once its reached it should break the loop and print the last line.
You need to put
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
into your loop, else it will never get new user input
You need call scanner inside loop
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
while(true){
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}

How can I check if a file contains a certain number that the user has input? (java)

Hi I'm trying to write a program that will check a designated file for a number that a user has input, however if the number is not present in the file I want the program to loop back to the beginning, how could I do this?
Here is the mess I've made so far:
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
String keyWord = number, word;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(myScanner.nextLine().trim())) {
System.out.println("The number "+number+ " is there");
break;
} else {
// not found
}
} // main
} // class
all you need to do is take input from user and then check is it exist in file .you shouldn't use myScanner.nextLine().trim() inside while loop because then it waits to get user input every loop time .ones you get a number from user ,you should check it in the file .what you did is get user input and then again wait for user to input value again and again
fixed code
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(number.trim())) { //here was the problem
System.out.println("The number "+number+ " is there");
return;
} else {
}
}
System.out.println("not found"); // not found
}
the best approach
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine();
if(isFound(number)){
System.out.println("The number "+number+ " is there");
}else{
System.out.println("The number "+number+ " doesn't exist");
}
}
public static boolean isFound(String number) {
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
String word="";
while (sc.hasNextLine()) {
word = sc.next();
if (word.equals(number.trim())) {
return true;
}
}
return false;
}
}
This works for me, hope is useful for you:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) throws IOException {
File f = new File("trombones.txt");
f.createNewFile();
Scanner myScanner = new Scanner(System.in);
boolean numExiste = menu(new Scanner(f), myScanner);
while (!(numExiste)){
numExiste = menu(new Scanner(f), myScanner);
}
myScanner.close();
}
private static boolean menu(Scanner fileScanner, Scanner myScanner) throws FileNotFoundException{
String word = "";
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine().trim();
while(fileScanner.hasNextLine()){
word = fileScanner.nextLine();
if(word.trim().equals(number)){
System.out.println("The number "+number+ " is there");
return true;
}else{
//Not the number
}
}
System.out.println("The number "+ number+ " is not in the file\n\n");
return false;
}
} // main } // class

repeating a program with arrays

I'm trying to get my program to repeat, but it's not working out too well. This is what I have so far:
import java.util.*;//to use scanner class
public class ArrayDemo
{
public static void main(String args[])
{
int a[]=new int[5];
Scanner sc=new Scanner(System.in);//use to take input
int i;
for(i=0;i<a.length;i++)//arrayname.length gives the length of array
{
System.out.println("Enter number:");
a[i]=sc.nextInt();
}
int sum=0;
long pro=1;
int max=a[0];
int min=a[0];
for(i=0;i<a.length;i++)
{
sum=sum+a[i];
pro=pro*a[i];
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
float avg=sum/a.length;
System.out.print("You entered");
for(i=0;i<a.length;i++)
{
System.out.print(", 1"+a[i]);
}
System.out.println("\nThe sum of those numbers is "+sum);
System.out.println("The product of those numbers is "+pro);
System.out.println("The largest number entered is "+max);
System.out.println("The smallest number entered is "+min);
System.out.println("The average of the numbers entered is "+avg);
}
}
I have another program that I'm trying to work into repeating, but it says no main applets or methods to be found, so it doesn't return anything:
import java.util.*;//to use scanner class
public class ArrayDemo
{
public static void myMethod(Scanner scanner)
{
int a[]=new int[5];
int i;
for(i=0;i<a.length;i++)//arrayname.length gives the length of array
{
System.out.println("Enter number:");
a[i]=scanner.nextInt();
}
int sum=0;
long pro=1;
int max=a[0];
int min=a[0];
for(i=0;i<a.length;i++)
{
sum=sum+a[i];
pro=pro*a[i];
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
float avg=sum/a.length;
System.out.print("You entered");
for(i=0;i<a.length;i++)
{
System.out.print(","+a[i]);
}
System.out.println("\nThe sum of those numbers is "+sum);
System.out.println("The product of those numbers is "+pro);
System.out.println("The largest number entered is "+max);
System.out.println("The smallest number entered is "+min);
System.out.println("The average of the numbers entered is "+avg);
System.out.println();
do {
myMethod (scanner);
System.out.println("You want to continue : (Y/N) ");
} while("Y".equalsIgnoreCase(scanner.next().trim()));
scanner.close ();
}
}
You need a main method like
public static void main(String args[])
Scanner scanner = new Scanner(System.in);
do {
myMethod (scanner);
System.out.println("You want to continue : (Y/N) ");
} while("Y".equalsIgnoreCase(scanner.next().trim()));
scanner.close ();
}
so move this code to a main method from your (my) `myMethod
Your first code has main method:
public static void main(String[] args) {// some code }
but second code has not this method. In the java language a program must start from main method with above signature.
In your 2nd approach you don't have the main method. So you can't run the file.
Another thing is don't put all the logic in main method. Try your best to separate them as much as possible. Then it is more clear.
Put your calculation logic to a method and call it from a while or do while loop
e.g.
class A{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int[] a= new int[5];
boolean bRepeat = true;
while(bRepeat){
for(i=0;i<a.length;i++){
System.out.println("Enter number:");
a[i]=sc.nextInt();
}
System.out.println("Sum is " + getSum(a));
System.out.println("Average is " + getAvergae(a));
.....
System.out.println("Do you wanna repeat? T/F");
String response = scanner.nextLine();
if(response.equalsIgnoreCase("T"))
bRepeat = true;
else
bRepeat = false; // or break
}
}
public static int getSum(int[] number){
//logic
}
public static double getAverage(int[] number){
//logic
}
public static int getProduct(int[] number){
//logic
}
public static int getMax(int[] number){
//logic
}
................
}

Prevent input error

import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
How do I loop a piece of code like the one above until an int is entered instead of giving an error when a non-int is entered?
The Scanner class has a lot of stuff built in so that you don't need to do try-catches unless you are explicitly looking to catch the errors.
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}
This tries to run the scanner, if a input is one that is not expected it will simply restart. You can add a message to it, my code was for brevity.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}

Categories

Resources