Java Beginning - Scanner Class Error - java

I'm doing some homework where we have to use the Scanner class. I was able to use it to read in a String, an int, and a float. When I moved to the next phase (the class below) I suddenly am not able to use scanner the way I had before. I did indeed close any other scanner object I created and opened. Thank you for any help.
Why does this code: (nextLine() also does not work)
import java.io.*;
import java.util.Scanner;
public class Grades {
private int len;
private String [] gradeNames;
private int [] gradeArray;
private int enterGradeNames(){
Scanner input = null;
input = new Scanner(System.in);
for (int i = 0; i < len; ++i){
System.out.println("Enter the type of grades you will be reporting: (" +
(i + 1) + " of " + gradeArray.length + ")" );
gradeNames[i] = new String(input.next() );
}
input.close();
return 0;
}
protected int displayGradeNames(){
System.out.println("Type of Grades tracking");
for (int i = 0; i < len; ++i)
System.out.println(gradeNames[i]);
return 0;
};
public Grades(){
len = 0;
Scanner input = null;
input = new Scanner(System.in);
System.out.println("Enter the size of the grade array to be created");
len = 4;
gradeArray = new int[len];
gradeNames = new String[len];
input.close();
enterGradeNames();
}
}
give me this errror:
Enter the type of grades you will be reporting: (1 of 4)
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Grades.enterGradeNames(Grades.java:14)
at Grades.(Grades.java:34)
at Demo1.main(Demo1.java:32)
** Oh.. i should mention that it doesn't even give the option to input data before throwing the error

The problem is in your enterGradeNames() method with:
input.next()
You have to first call input.hasNext();
From documentation:
Throws:
NoSuchElementException - if no more tokens are available.
EDIT: as per comments
I am unable to reproduce the problem, but there are many unnecessary lines in your code, so try running this edited code and see whether it changes anything.
public class Grades {
private int len;
private String [] gradeNames;
private int [] gradeArray;
private int enterGradeNames(){
Scanner input = new Scanner(System.in);
for (int i = 0; i < len; i++){
System.out.println("Enter the type of grades you will be reporting: (" +
(i + 1) + " of " + gradeArray.length + ")" );
gradeNames[i] = new String(input.next());
}
return 0;
}
public Grades(int length){
this.len = length;
gradeArray = new int[len];
gradeNames = new String[len];
}
It's not generally good choice to call non-static methods inside constructor as the object isn't finished yet. You could do this in a (factory) method instead:
public static Grades buildGrades(){
Scanner s = new Scanner(System.in);
System.out.println("Enter size:");
int size = s.nextInt();
Grades grades = new Grades(size);
grades.enterGradeNames();
return grades;
}
EDIT2:
I searched a bit and the problem might be with your closing of the Scanner. Because if you call close on the Scanner, it will look whether its stream implements Closeable and if so it will close it as well. I never thought System.in would be closeable, but it is.
So the best option? Possibly use one Scanner for the whole program OR just don't close it if you dont want its stream to be closed. More can be read here.

try it with this:
public Grades(){
len = 0;
Scanner input = null;
input = new Scanner(System.in);
System.out.println("Enter the size of the grade array to be created");
len = 4;
gradeArray = new int[len];
gradeNames = new String[len];
enterGradeNames();
input.close();
}

I removed from your "Grades" Constructor the input reference because it is useless to do it twice (at enterGradeNames you initilize it again).
The problem was you closed the resource at the constructor and then tried to recreate it again.
public Grades(){
len = 0;
System.out.println("Enter the size of the grade array to be created");
len = 4;
gradeArray = new int[len];
gradeNames = new String[len];
enterGradeNames();
}

Related

Java: Declaring array with do... while

My school homework is to declare array with 100 variables.
The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.
So far I got:
public static void runTask1() {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
for (int i = 0; i < tab.length; i++);
System.out.println("Enter number for array ");
tab [] = read.nextInt();
Please help. I'm a total newbie in programming.
You should do your homework yourself ;)
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int idx=0;
do{
System.out.println("Number for array idx "+idx);
try{
tab[idx] = read.nextInt();
}catch(Exception e){
System.out.println("Wrong input");
}
if(tab[idx]<0) break;
idx++;
}while(idx<100)
Not compiled, just wrote it here.
Try that
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int index = 0;
while(index < tab.length){
System.out.println("Enter number for array ");
tab[index]= read.nextInt();
if(tab[index]<1) break;
index++;
}
System.out.println(Arrays.toString(tab));
}

Java exception error for input string

I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}

Passing an array to another method and copying it

I am trying to pass an array from one method to another method and then copy the contents of that array into a new array. I am having trouble with the syntax to accomplish that task.
Does anyone have some reference material that I could read about this topic or maybe a helpful tip that I could apply?
I apologize if this is a noob question, but I have only been messing with Java for 3-4 weeks part time.
I know that Java uses pass by value, but what where I'm getting lost is...should I invoke the sourceArray before copying it to the targetArray?
My goal here is not to be just handed an answer, I need to understand WHY.
Thanks...in advance.
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the total number of dealers: ");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.printf("%nPlease enter the required data for each of your dealers:");
dataCalculation(numDealers);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: ");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
int[] dealerSales = new int[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
int sales = input.nextInt();
dealerSales[i] = sales;
}
for(int i = 0; i < data; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
}
//gather the required input data.
//Perform the appropriate data validation here.
}//data calculations
//METHOD 3
public static int commission(int data)
{
//Create array
int[] commissionRate = new int[dealerSales];
//Copy dealerSales array into commissionRate
System.arraycopy(dealerSales, 0, commissionRate, 0, dealerSales.length);
//calculate the commission array.
//$1 - $5,000...8%
//$5,001 to $15,000...15%
//$15,001...20%
//
}//commission method
}//class
If you want to copy an array, you can use the Arrays.copyOf(origin, length) method. It takes 2 arguments, first one is the array from which the data is supposed to be copied and second is the length of the new array, and import java.util.Arrays.
-See the link for more info https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)

How to get consecutive numbers form user in a java program?

import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
Scanner sv=new Scanner(System.in);
b=sv.nextInt();
Scanner st=new Scanner(System.in);
n=st.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
}
I tried using scanner class but it is not executed by eclipse as it only shows sc,sv and st objects of scanner class is resource leaked and never closed.
Well, it appears you have some configs that keep your program from compiling and running based on the resource leaking (not an Eclipse user). Your code compiles and runs with Intellij on my machine so you have a few choices.
Change your configuration to ignore the warning/error. (not recommended)
Close the one Scanner you need. (scanner.close()) You can get more than one value from the single scanner. So, ditch the other ones.
To accomplish (2) another way you could use try-with-resources block and it will be closed automatically at the end of the try.
try (Scanner sc = new Scanner(System.in)) {
// put your code to get input here
} catch (IOException ioe) { ... }
In addition to the scanner issues you're asking about, you have a significant error in your code that will make it impossible to get any meaningful/accurate output. Consider...
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
int result = a + c;
System.out.print(result + " ");
}
c is made anew on each loop and assigned a value of 0 and so c = 2 * c * b; will equal 0 always; and a + c will then always just equal a.
Dont need to create a new Scanner Object...
just do:
int a, b, n;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
n = sc.nextInt();
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
final int result = a + c;
System.out.print(result + " ");
}
I was typing this out when #Xoce was posting his answer, so it's exactly the same as his :)
The only other thing that I'd like to add is that if you're using IntelliJ, try pressing control-alt-i to auto-indent your code.
public static void main(String[] args) {
//Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
n=sc.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}

how to take user input in Array using java?

how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
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;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
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();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();

Categories

Resources