The constructor Scanner(InputStream) is undefined - java

I have imported java.util.* but the IDE can't recognize Scanner. If I change it to import java.util.Scanner; it's fine. But I need it on java.util.* because the catch exception is part of java.util. This code is from a textbook by the way.
EDIT: I'm using Eclipse.
import java.util.*;
public class GetInteger {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
int i = GetAnInteger();
System.out.println("You entered " + i);
}
public static int GetAnInteger() {
while(true) {
try {
return sc.nextInt();
}
catch (InputMismatchException e) {
sc.next();
System.out.println("That's not an integer. Try again: ");
}
}
}
}

Related

Java: issue calculating average from txt file

Hello everybody first post on here!
i'm currently having some issues with my readfromfile() to calculate an average my issue is that its printing the ten numbers "stuck together"
like 12345678910 i dont understand how i can calculate an average like this i tried token/10 and it returns 0000000000
any suggestions getting an average from this mess?
i tried returning token with %n%s which looks better but still when i divide by 10 it doesnt give me a correct number what am i doing wrong
package average;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Formatter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class average {
private static Formatter output;
private static Scanner input;
public static void main(String[] args) {
openFileWrite();
writeToFile();
closeFile();
openFileRead();
readFromFile();
closeFileRead();
}
public static void openFileRead() { // gets file for "read"
try {
input = new Scanner(Paths.get("Numbers.txt"));
} catch (IOException e) {
System.out.println("Unable to read file");
}
}
public static void openFileWrite() { // gets file for "write"
try {
output = new Formatter("Numbers.txt");
} catch (FileNotFoundException e) {
System.out.println("Unable to open file");
}
}
public static void readFromFile() {
while (input.hasNextInt()) {
int token = input.nextInt();
System.out.print(token);
}
}
public static void writeToFile() {
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 numbers");
try {
for (int i = 0; i < 10; i++) {
System.out.println("Another Number Please");
int total = input.nextInt();
output.format("%s%n", total);
}
} catch (InputMismatchException e) {
System.out.println("Please do not enter any letters");
writeToFile();
}
}
//required to close file for write
public static void closeFile() {
output.close();
}
//required to close file for read
public static void closeFileRead() {
input.close();
}
}
Just change your readFromFile method as:-
public static void readFromFile() {
double average = 0;
while (input.hasNextInt()) {
int token = input.nextInt();
average+=token;
}
System.out.println("Average ="+average/10);
}

Java Exception Handling - Do while Loop

I'm writing a Java Exception Handling program and encountered following issue.
when I enter a invalid input an infinite loop started executing instead of execution start from the try block.
public class Exception_Handling {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
boolean bl=true;
do {
try {
int a = sc.nextInt();
int b = sc.nextInt();
bl=false;
}
catch(InputMismatchException ex) {
System.out.println("Enter Valid Number Format");
System.out.println(ex);
}
}while(bl);
}
}
You need to flush your buffer before re-entering in the loop. Otherwise java tries to read the same input again and again.
import java.util.Scanner;
public class Exception_Handling {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
boolean bl = true;
do {
try {
int a = sc.nextInt();
int b = sc.nextInt();
bl = false;
} catch (Exception ex) {
System.out.println("Enter Valid Number Format");
System.out.println(ex);
sc.next();
}
} while (bl);
}
}
You can also use sc.reset() instead of sc.next()in your case. But if you had configured scanner with useDelimiter, useLocale or useRadix it will reset these parameters too. (see reset() java doc)
You have a catch exception on Input Mismatch so it won't bother to execute this statement:
bl = false;
which would not terminate the loop.
public class Exception_Handling {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
boolean bl=true;
do {
try {
bl=false;
int a = sc.nextInt();
int b = sc.nextInt();
}
catch(InputMismatchException ex) {
System.out.println("Enter Valid Number Format");
System.out.println(ex);
}
}while(bl);
}
}

How to stop NoSuchElementException error from this part of the code? [duplicate]

This question already has answers here:
NoSuchElementException after closing system.in
(1 answer)
Scanner throwing NoSuchElementException
(2 answers)
NoSuchElementException Issue
(1 answer)
Closed 5 years ago.
This is a section of my code from a project that is giving an error. I am practicing encapsulation, but, cannot figure out why I am getting this error when I am setting values inside the Array-list.
There are two classes
1) Create_accountant
2) Adminstoreroom
Both of them are under same package: com.admin
package com.admin;
import java.util.InputMismatchException;
import java.util.Scanner;
class Create_accountant {
Adminstoreroom admin = new Adminstoreroom();
void Creating() {
System.out.println();
System.out.println("\t\t\t\t Create New Accoutant");
System.out.println();
name();
pass();
}
void name() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her name: \t");
String name = null;
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the name again.");
name();
}
catch(Exception e) {
System.out.println("Here is the main problem " + e);
}
admin.setAccName(name);
input.close();
}
private void pass() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her password: \t");
try {
admin.setAccPassword(input.nextLine());
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the password again.");
pass();
}
catch(Exception e) {
System.out.println("Here is the main problem");
}
input.close();
}
The problem is inside the 2 try blocks.
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
Both of the name() and pass() go for the catch(exception e) block. When I run this code, the output from the above try is
Here is the main problem java.util.NoSuchElementException: No line found
The second class
package com.admin;
import java.util.ArrayList;
class Adminstoreroom {
//These arrays are used for Storing accountant info in the admin sections
private static ArrayList<String> accName = new ArrayList<String>(30);
private static ArrayList<String> accPassword = new ArrayList<String>(30);
//Accountant Names
public void setAccName(String an) {
accName.add(an);
}
public String getAccName(int i) {
return accName.get(i);
}
//Accountant Password
public void setAccPassword(String ap) {
accPassword.add(ap);
}
public String getAccPassword(int i) {
return accPassword.get(i);
}

Syntax error on token(s), misplaced construct(s) Code Help Needed

I use eclipse to help me code & I have been having issues with the error message "Syntax error on token(s), misplaced construct(s)" coming up, I'm not entirely sure what is wrong with my code.
The goal of this code is to write a program where a user enters their name and age and the program checks to see the age is between 0 and 125. If not, the program shows an error code (use Exception Class)
Here is my current code: Errors are showing up in lines 1 and 4
public class ThreadsUnitProject1 {
import java.lang.String;
import java.io.*;
public static void main(String args[]);
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
try {
name = br.readLine();
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
catch(InvalidAgeException e) {
System.out.println("Error: " + e);
System.exit(1);
}
finally {
System.out.println("No errors found.");
}
}
}
}
Thank you thank you thank you for all of your help, I have been coding for awhile, but I'm new to Java.
Thanks again!
-Kristen
public static void main(String args[]) is a method it needs to create a block with curly braces. It doesn't contain the block in the ThreadsUnitProject1 class.
public static void main(String args[]){}
Also the import statements should be outside the class declaration.
Full Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ThreadsUnitProject1 {
public static void main(String args[]) {
}
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String name = "";
try {
name = br.readLine();
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
} finally {
System.out.println("No errors found.");
}
}
}
}
Use {} after public static void main(String args[]), not ;.

How to make it so that theres a wait time between dialog

how would i make it so that in between the System.out.println theres a pause, so it doesnt all spill out at once,
import java.io.*;
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
System.out.println("Stranger: Good morning");
System.out.println("Stranger: you had a terrible Dream..");
System.out.println("Stranger: what is your name?");
System.out.print("Name:");
Scanner kbReader = new Scanner (System.in);
String s = kbReader.next();
System.out.println("Nice to meet you " + s);
System.out.println("my name is Master Wizard.");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
}
}
You could try something like...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Stranger: Good morning");
delay(500);
System.out.println("Stranger: you had a terrible Dream..");
delay(500);
System.out.println("Stranger: what is your name?");
System.out.print("Name:");
Scanner kbReader = new Scanner(System.in);
String s = kbReader.next();
System.out.println("Nice to meet you " + s);
System.out.println("my name is Master Wizard.");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
For example

Categories

Resources