Counting and resetting a Scanner - java

I'm an amateur with Java and am trying to put the contents of a scanner into an array. This is what I have currently:
`
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int l = scannerLength(sc);
sc.close(); sc = null; sc = new Scanner(System.in);
int[] input = new int[l];
for (int i = 0; i < l; i++) {
input[i] = sc.nextInt();
System.out.println(input[i]);
}
}
private static int scannerLength(Scanner sc) {
int output = 0;
while(sc.hasNextInt()) {
output++;
sc.nextInt();
}
return output;
}
`
I am trying to effectively 'reset' the Scanner after my helper function determines its length by voiding it and declaring it anew, so I can use nextInt to put the elements into an array. But I get a NoSuchElementException at line 8.
Can anyone tell me why this is? I would think, after resetting the Scanner, that sc.nextInt() at line 8 wouldn't pose a problem.

Related

Java program for splitting strings with line breaks and stops with no entry not working?

This is the problem I'm trying to solve:
My code is the following:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why. Any explanations?
You should arrange your code like:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true) part:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:
Scanner scanner = new Scanner(System.in);
outside of the while loop.
The reason:
You only need to create a single Scanner object. This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.
You can also think about it more mechanically than that:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right? Its quite a similar thing in this case.

Add 1st and Last digit of a number

I am trying to add the 1st and last digit of a no but after the programs gets to while loop it starts asking for more inputs,like an infinite loop .
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();//no of testcases
int n[]=new int[t];
int last=0,first = 0;
for(int i=0;i<t;i++){
n[i]=sc.nextInt();
sc.nextLine();
last=n[i]%10;
while(n[i]>=10){
first=n[i]/10;
}
System.out.println(first+last);
}
This is how I did it.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
String temp = t+"";
String[] arr = temp.split("");
int x = Integer.parseInt(arr[0]) + Integer.parseInt(arr[arr.length - 1]);
System.out.println(x);
}
That is because you are not updating the value of n[i] with every iteration.
This is my proposed solution for your while loop:
while(n[i]>=10){
n[i]=n[i]/10;
}
first = n[i]
In while loop you need to update the value of n[i] by using n[i]=n[i]/10; which is causing while loop to become infinite loop
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();//no of testcases
int n[]=new int[t];
int last=0,first = 0;
for(int i=0;i<t;i++){
n[i]=sc.nextInt();
sc.nextLine();
last=n[i]%10;
while(n[i]>=10){
n[i]=n[i]/10;
}
first=n[i]/10;
System.out.println(first+last);
}

Ending while loop in Java

I'm making a program for my assignment. This is not the whole program but it's just a part of it.
I want from the user to enter some integer values to be stored in "items" arrays. When the user input "stop" the loop should close and here is the problem.. when I write stop the program stops and give me some errors.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=0, lines=1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true){
i=i+1;
if ("stop".equals(scan.nextLine()))
break;
else
items[i] = scan.nextInt();
}
}
There are certain mistakes in your code. It's more better if you could just add the error.
Try this code.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0, lines = 1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true){
String InputTxt = scan.nextLine();
if (InputTxt.equals("stop"))
break;
else{
try{
items[i] = Integer.parseInt(InputTxt);
i++;
}catch(Exception e){
System.out.println("Please enter a number");
}
}
}
}
On top of other answers, I would like to advise you to change the looping from
while(true)
to
//first you need to remove the local variable i
for(int i = 0; i < items.length; ++i)
Using this approach will help you to avoid IndexOutOfBoundsException when users key in more than 100 integer values.
your problem is this line : items[i] = scan.nextInt(); because you are trying to get integer while the input is string stop
EDIT
one possible solution is that you get your data as string and check if it is stop or not and if not then try to parse it to integer like code bellow:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=0, lines=1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true)
{
i=i+1;
String str = scan.nextLine()
if ("stop".equals(str))
break;
else
{
items[i] = Integer.parseInt(str)
}
}
}

Arrays - static method to return sum, but nothing is returned

Create a Java program that reads 10 numbers from the console Scanner
input = new Scanner(System.in); .Store the numbers as Floats in the array. Create static methods to perform the following actions on the array and returns the result.Add all the items in the array and return the result. Name this method"add".
So this is my code, but when the user inputs the 10 numbers, nothing is returned. Any suggestions?
public static void main(String[] args) {
float[] myArray = new float[10];
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("please enter number");
myArray[(i)] = input.nextFloat();
}
}
public static float add(float[] array) {
float sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
You are not calling the method :
public static void main(String[] args) {
float[] myArray = new float[10];
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("please enter number");
myArray[(i)] = input.nextFloat();
}
System.out.println(add(myArray)); // need to make this call
}
At the end of for loop you need to call the add method.
System.out.println(add(myArray));

For looping to add variables for a Scanner input

So I'm new to Java and I figured I'd do something simple like a for loop to print out an array of strings or something,
My code ended up like this:
package package.four;
import java.util.Scanner;
public class arrayrecurse {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter 5 words");
String a = in.next();
String b = in.next();
String c = in.next();
String d = in.next();
String e = in.next();
String[] s = {a, b, c, d, e};
for(int i = 0; i< s.length;){
System.out.println(s[i]);
i++;
}
in.close();
}
}
It works fine but my question is if it's possible to make a for loop cycle through variables.
For examples if I wanted something like:
for(words = 5; words > 0;){
String a = in.next();
a++}
Where would it change the variables each time I enter a new word.
Would it be possible to do something like that or do I need to type out the String variable = in.next(); every time I want to enter a new word input from the console?
You can call next() inside the loop, but you need to declare the variable outside the loop if you want to use it afterwards, also, there is no ++ operator for String or array in Java:
String[] inputs = new String[5];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
Use an ArrayList to store the input variables.
That is:
import java.util.*;
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (String s: inputVars)
{
System.out.println(s);
}
}
Or alternatively, if you want to change the contents of the ArrayList:
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (int i = 0; i < inputVars.size(); i++)
{
System.out.println(inputVars.get(i));
//Change the variable
inputVars.set(i, "Hello, " + inputVars.get(i));
}
}

Categories

Resources