Can't get my Scanner to work with ArrayList - java

Hi sorry in advance about my bad code haha. I'm trying to get my code to read out what I type in the keyboard (only one phrase) forwards and then backwards however I keep getting errors with every different method I try.
import java.util.ArrayList;
import java.util.Scanner;
class hw
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
sal.add(kb.next());
sal.add(kb.next());
sal.add(kb.next());
display(sal);
displayb(sal);
}
public static void display(ArrayList<String> sal)
{
for (int i=0; i<sal.size(); i++)
System.out.print(sal.get(i)+ " ");
System.out.println();
}
public static void displayb(ArrayList<String> sal)
{
for (int z = sal.size(); z >= 1; z--)
System.out.print(sal.get(z-1) + " ");
System.out.println();
}
}
I know this has something to do with using a while loop and something like
String s;
s = kb.next();
but I keep getting infinite loops and other errors with everything I try. Any ideas?

I am quite sure code is ok, you need to make following change though.
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
sal.add(kb.next());
sal.add(kb.next());
**Sal.add(kb.next());**
here replace "Sal" with "sal"

For simple constant adding using a while loop, you need some type of termination condition:
int i = 0;
while (i < 5) {
sal.add(kb.next());
i++;
}
/* or */
String last = "";
while (!last.equals("end")) {
last = kb.next();
sal.add(last);
}

Related

Can I search for values in two different type of arrays with just one type of variable?

I'm quite new to Java and I've been asked to create a program in which the user is able to input two values and store them in separate arrays. The two values I'm asking the user are name and cell number, then I must allow the user to search by typing either a name or a cell number and return the corresponding name or cell number. I made it possible to input the values and search within them by number but when I try searching by name I get this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
This is my code:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
Thanks! :)
Looking at your problem statement it doesn't seem like you need to do any additional processing on numbers. Hence, even if you store the number as a string it should be fine in this case.
Hence after getting a user search criteria, you could do a simple string search within both arrays.
Hope this helps :)
First of all, the highest number that can be represented as an int in Java is 2147483647 (214-748-3647). This clearly will not be able to hold a high enough number to accommodate any phone number. To address this issue and also fix your main error, I would suggest storing the numbers as a string instead. Here's my solution:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
Please also note that I un-defined your variable i. As far as I can see there's no reason for you to be defining it. Hope this helps, good luck!

Insight with ending a loop by pressing the enter key in Java

I am in a low level java programming class, and I am having trouble figuring something my professor assigned to us. We originally made a program that added integers that were placed in an arraylist. She then asked us to make it as user friendly as possible, without having a specific amount of integers the user inputs. So I came up with this:
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
do
{
numbers.add((int) input.nextInt()); //inserting input into the arraylist
System.out.println("The sum is " + sum(numbers)); //test output
}while(input.hasNextInt()); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(ArrayList<Integer> list)
{
int total = 0;
for (int i = 0; i < list.size(); i++)
{
total += list.get(i);
}
return total;
}
}
Sorry for the clutter of comments, I'm trying to show any of you my mindset behind what I did. Thank you so much in advance for anyone that has any suggestions!
See if this helps where in you take an input from user to terminate the program.
public class CalculatorREDONE {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add or -1 to exit");
Scanner input = new Scanner(System.in);
// boolean nextAvailable = true;
while(true)
{
String nextVal = input.nextLine();
if(nextVal.isEmpty()) {
break;
}
numbers.add(Integer.parseInt(nextVal)); //inserting input into the arraylist
// System.out.println("The sum is " + sum(numbers)); //test output
} //while (!input.next().); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(List<Integer> list) {
int total = 0;
for (int i = 0; i < list.size(); i++) {
total += list.get(i);
}
return total;
}
}
Try this -- it takes the input as a string, checks the length. If the user just hits enter the length will not be greater than zero. This catches the number exception from the parseInt by confirming the user has ended their list.
Note that I didn't include your sum portion since it wasn't relevant to the question of breaking the loop. You'll need to re-add
import java.util.Scanner;
import java.util.ArrayList;
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
String userinput = "xx";
int nextnum = 0;
while (userinput.length() > 0) {
try {
userinput = input.nextLine();
nextnum = Integer.parseInt(userinput);
numbers.add(nextnum);
System.out.println("Taken");
} catch (NumberFormatException e) {
System.out.println("Inputs complete");
}
}
System.out.println(numbers);
input.close();
}
}

while there is input from user

I'm new to java. In my program, I have the user enter the integers that are being added to an array list. I need to set up a while loop that will be something like this:
arrayList = new ArrayList<int>;
int i = scanner.nextInt();
while(there is input from user)
{
arrayList.add(i);
}
I expect the user to enter 5 values. What do I put as the condition statement of the while loop. In other words, how do I say "while there is input?" Thanks
Try something along the lines of
while(scanner.hasNextInt())
{
arrayList.add(i);
}
import java.util.Scanner;
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList arrayList = new ArrayList<Integer>();
int input;
for (int i = 0; i < 5; i++)
{
input = scan.nextInt();
arrayList.add(input);
}
}
}
I tried below code and tested its working fine. let me know if u want another requirements.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>();
System.out.print("enter 5 numbers");
int counter=1;
while(scan.hasNextInt()){
int i=scan.nextInt();
arr.add(i);
counter++;
if(counter==5){
scan.close();
break;
}
}
}
}
I believe, you're currently accepted answer has a very fatal (it never updates i). What you need is something more like this -
// arrayList = new ArrayList<int>; // And arrayList isn't a great name. But I have
// no idea what they actually are. So
// just use a short name.
List<Integer> al = new ArrayList<Inteeger>(); // <-- Use the interface type?
// And, you have to use the wrapper type.
// int i = scanner.nextInt();
while (scanner.hasNextInt())
{
al.add(scanner.nextInt()); // You don't need `i`.
}

Java - Storing userinput using Arrays and Methods

I am trying to ask the user to enter 10 names using arrays, and then return the method. Any help would be appreciated. Thanks in advance.
import java.util.Scanner;
public class methodbankinput
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
String[] names = {};
printarray(names);
}
public static void printarray(String[] names)
{
for (int i = 1; i < 11; i++)
{
System.out.println("Please enter 10 names" + i);
names = kb.nextLine();
}
}
}
This code won't compile. You've defined Scanner kb in your main and you can't see it inside printarray.
You've also declared a 0-length array. I don't think that's what you want.
And to store something in an array, you need to specify what index you want to store the value in. Arrays are also zero-indexed so i should start at 0, as so.
for (int i = 0; i < names.length; i++) // You could use i < 10 as well
{
System.out.println("Please enter 10 names" + i);
names[i] = kb.nextLine();
}

(noob) java values use (Scanner + For)

I wanted to program a java app that can print as many stars as the user want.
The programm will ask the user how many starts he want to print.
Here is my code :
import java.util.Scanner;
public class lab {
public static void main(String[] args){
int StarsN;
Scanner input;
input = new Scanner(System.in);
System.out.println("How many stars do you need?");
StarsN= input.nextInt();
}
public static void loopz(String[] args) {
int loopEnd = StarsN;
int loopStart;
for (loopStart = 0;loopStart==loopEnd;loopStart++) {
System.out.print("*");
}
}
}
First thing to note.. I don't know why you are sending your loopz method a String[].. Here is what i would do differently in the loopz method:
public static void loopz(int numOfStars)
{
for(int i = 0; i < numOfStars; i++)
System.out.print("*");
}
Also call loopz in main and send it the parameter.
your for loop : loopStart = 0 then it says is loopStart == loopEnd , and it won't enter in the loop because loopStart don't equals loopEnd so you should change "==" in your loop to "<" .
Here is the answer:
import java.util.Scanner;
public class lab {
public static void main(String[] args){
int StarsN;
Scanner input;
input=new Scanner(System.in);
System.out.println("How many starts do you need ?");
StarsN= input.nextInt();
int loopEnd = StarsN;
int loopStart;
for (loopStart = 0;loopStart<loopEnd;loopStart++) {
System.out.print("*") ;
}
}
}
I really would like to teach you how to fish, instead of just giving you the fish, but I think that you need too much theory before this. Try to find some book or a good and complete tutorial to follow, I'm sorry but I don't know neither of both to say to you.
Change for (loopStart = 0;loopStart==loopEnd;loopStart++) to for (loopStart = 0;loopStart < loopEnd;loopStart++).
And don't forget to call loopz() from main():
public static void main(String[] args){
Scanner input = null;
try {
input=new Scanner(System.in);
System.out.println("How many starts do you need ?");
int StarsN= input.nextInt();
loopz(StarsN); //Add this
} finally {
if( input != null )
input.close();
}
}
public static void loopz(int numStars) { //You don't need the String[] args here since you never use it
for (int loopStart = 0; loopStart < numStars;loopStart++) {
System.out.print("*") ;
}
}

Categories