Java - Storing userinput using Arrays and Methods - java

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();
}

Related

How to access array from constructor

I just started with Java a few weeks ago and today I've tried to write a program which is able to calculate the average IQ of numbers the user can input. I've written two classes, IQ and IQTester (IQTester = Main only). Now my problem is, whenever I want to calculate something in method compute() (e.g. the average of the array) the whole array is empty. Does anybody know how I can "pass" the array from the constructor to the method compute()?
package IQProgramm;
public class IQ {
private int values[] = new int[10];
private double average;
public IQ(String numbers) {
this.values = values;
String[] values = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < values.length; ++i) {
System.out.print(values[i] + " ");
}
System.out.println("\n");
}
public void compute() {
for (int i = 0; i < values.length; ++i) {
System.out.println(values[i]);
}
}
}
package IQProgramm;
import java.util.Scanner;
public class IQTester {
public static void main(String[] args) {
Scanner readIQ = new Scanner(System.in);
System.out.println("Please enter your numbers: ");
String numbers = readIQ.nextLine();
IQ iq = new IQ(numbers);
iq.compute();
}
}
You have 2 different arrays named values, that's why it doesn't work well.
The first defined here String[] values = numbers.split(";"); is visible only in the constructor. If you want to set the value of the one that is available in the rest of the IQ class (private int values[] = new int[10];), you need to edit this one by using
this.values[i] = Integer.parseInt(values[i])
this refers to the variable values of the class IQ.
It is a good practice not to have 2 values with same name. You can change String[] values name to valuesStr for example.
Constructor with the fix:
public IQ(String numbers) {
String[] valuesStr = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < valuesStr.length; ++i) {
this.values[i] = Integer.parseInt(valueStr[i])
System.println(this.values[i]+" ");
}
System.out.println("\n");
}

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!

Java String function help needed

I have a homework question from college that I am having trouble with and I was wondering if anyone could give me some advice on where to go with it. We are using Arrays, for loops, if else and Strings.
I have to create a programme to take in a number of peoples names then put them in an Array ( which I had no problem with) I then need to separate the names in the array according to the first letters of each name : A-G in one array, letters H-P in another and the rest in a final array.
I have been told to use a String Function for this but not to use lists or Char.
This is the code I have so far :
import java.util.Scanner;
public class Party {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); // declaring scanner
int numGuests; // declaring the variable for number of guests
System.out.println("please enter the number of guests you are hosting : ");
numGuests = sc.nextInt(); // scanner for user inout num of guests
String[] names = new String[numGuests]; // string for number of guests
System.out.println("Please enter names ");
for(int i = 0; i < names.length; i++) // for loop for inputing the names.
{
names[i] = sc.next();
}
}
}
Please Use below logic and get result according to your requirement..
package com.test;
public class Namessplite {
public static void main(String args[]){
String[] names={"ABC","CAD","JKL","MNO"}; // these are names for example
String[] atog_group = new String[10];
String[] gtopgroup= new String[10];
int j=0,k=0;
for(int i=0;i<names.length;i++){
if((int)names[i].charAt(0)<72 && (int)names[i].charAt(0)>64){
atog_group[j]=names[i];
j++;
}else{
gtopgroup[k]=names[i];
k++;
}
}
System.out.println("A TO G Names Are :: ");
for(int m=0;m<j;m++){
System.out.println(atog_group[m]);
}
System.out.println("G TO P Names Are :: ");
for(int m=0;m<k;m++){
System.out.println(gtopgroup[m]);
}
}
}
Java 8 Style:
private static void splitNamesToArray(String[] names) {
String[] aToG = Arrays.stream(names).filter(n -> n.toUpperCase().charAt(0) >= 65 && n.toUpperCase().charAt(0) <= 71).toArray(String[]::new);
String[] hToP = Arrays.stream(names).filter(n -> n.toUpperCase().charAt(0) >= 72 && n.toUpperCase().charAt(0) <= 80).toArray(String[]::new);
String[] rest = Arrays.stream(names).filter(n -> n.toUpperCase().charAt(0) >= 81 && n.toUpperCase().charAt(0) <= 90).toArray(String[]::new);
System.out.println("A to G: " + Arrays.toString(aToG));
System.out.println("H to P: " + Arrays.toString(hToP));
System.out.println("Rest: " + Arrays.toString(rest));
}

Trying to make a random array that I can call 5 times, and that i can test against a user input

Need some help trying to set up this assignment. I am not to good with arrays, nor setting up methods to be used in the main. I need to make an array of 10 random numbers 1-100, that can be compared to the user input. I only need the comparison true/false to display. Here is what I have.
I get several errors in trying to print, so i haven't even tried to compare it to the user input yet.
Thanks,
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print(shots);
}
public int [] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++)
shots[i] = r.nextInt(100);
return shots;
}
public static void print(int shots[]) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}
As commentors said, please provide error messages.
However, I can pick out several issues just for starters. Let's look at your main method...
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print int [](shots);
}
In this call to the print method, why do you have int [] in there? Are you trying to cast something to an int array? Anyways, that has to come out.
Also, you are passing the print method some shots variable that doesn't exist.
Your print method takes an int array as its only argument, so you have to pass it a valid int array. Perhaps you meant to call getRandomNumbers() and pass the int array that it returns to the print method?
Also, what's with the nested classes you're showing. You have this class Final with another class ShotClass defined inside of it. And your closing brackets are all out of whack.
In short, you need to do as the comments ask and format your code and then work through each individual error message, because you've got a whole lot to fix.
EDIT
I'm not sure if I'm doing you more harm than good by giving you the answer to your homework assignment, but I feel for you so here it is. Please just look very carefully at the exact differences between what you posted in your question and what I show below. There's several mistakes you made, including bad syntax and a misunderstanding of how scope works, and I can't properly explain all the problems without typing several pages, so I hope you can learn from this example instead...
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
int[] shots = getRandomNumbers();
print(shots);
}
public static int[] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++) {
shots[i] = r.nextInt(100);
}
return shots;
}
public static void print(int[] shots) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}//END class

Can't get my Scanner to work with ArrayList

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);
}

Categories