Having weird issue with array [duplicate] - java

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
Im currently in the process of creating a program and stores data and I'm running into an issue where its printing out a statement twice and counting it as two in an array(its hard to explain so ill show it)
So this is the code
public static void GetData()
{
Scanner input = new Scanner(System.in);
System.out.println("How many names do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
for (int i = 0 ; i < array.length ; i++ )
{
String[] names = new String[num];
System.out.println("enter employee's name: ");
names[i] = input.nextLine();
}
for(int j = 0; j < array.length;j++)
{
double[] payrate = new double[num];
System.out.println("enter employee's payrate: ");
payrate[j] = input.nextDouble();
}
}
}
the problems is its printing out :
How many names do you want to enter?
4
enter employee's name:
enter employee's name:
harry
enter employee's name:
larry
enter employee's name:
mary
enter employee's payrate:
twice right away so when the user declares let says the array size of 4 it'll print that twice and it'll count that as two spots already so now it only counts 3 of the data and switches to the next array, I'm honestly not sure whats causing this, I tried to debug it but it tells me nothing, any help would be loved!

The first names[i] = input.nextLine(); will read the \n from the line containing the number which you read with input.nextInt(), so you'll get an empty name there.
You could read the num as follows:
String strNum = input.nextLine();
int num = Integer.parseInt(strNum);

Related

How do you have the user set the variable?

I am trying to have the user set the name for how many numbers they set. for example if they set 3 the program asks for name 3 times and then sets those names to a different varible inside an array.
public static void main(String[] args) {
Scanner Num = new Scanner(System.in);
Scanner Name = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = Num.nextInt();
int[] numbs = new int[number];
for (int i = 0; i < numbs.length; i++) {
System.out.println("What is your name");
String [] nameArray = Name.nextLine();
Just a small improvement over Titan's answer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int numberOfTimes = sc.nextInt();
String[] names = new String[numberOfTimes];
sc.nextLine();
for (int i = 0; i < numberOfTimes; i++) {
System.out.println("What is your name");
names[i] = sc.nextLine();
}
System.out.println(Arrays.toString(names));
}
Starting point
Here are several things happening in your posted code:
You have two different Scanners, each reading from System.in
After prompting for user input (int number = Num.nextInt()), you're using that number to create an array of size "number"
When you call nextLine(), you are assigning the result to a string array (String []).
Working solution
Here's a variation which addresses those issues, with a few additions, too:
Use one Scanner, and give it a general name ("scanner", not "Num") since a scanner has nothing to do with one specific data type. Any scanner can read strings, integers, booleans, bytes, etc. Look in Javadoc for the full set of supported data types.
Check if user input is valid before trying to create an array – if user enters "-1" that's a valid integer value, but not valid for allocating an array – new int[-1]) would throw a java.lang.NegativeArraySizeException at runtime.
Use "next()" instead of "nextLine()" – with the rest of your example, using "nextLine()" results in skipping one line without direct interaction from the user (so the first "name" is always an empty string)
Assign the result of "next()" to a String (not String[]), matching the return type from the method
Use "System.out.print()" instead of "println()", a little tidier program output
Use lowercase names to follow Java naming conventions ("scanner", not "Scanner")
Scanner scanner = new Scanner(System.in);
System.out.print("How many names do you want to enter: ");
int times = scanner.nextInt();
if (times < 0) {
System.out.println("negative numbers not allowed");
} else {
String[] names = new String[times];
for (int i = 0; i < times; i++) {
System.out.print("What is your name: ");
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
}
And here's a sample run:
How many names do you want to enter: 3
What is your name: one
What is your name: two
What is your name: three
[one, two, three]
Create a String array of number length outside the loop and initialize each index with name as input.
By the way you only need to create one Scanner object for input(Not needed to create various objects for different input).
Edit - There was no use of numbs array.
Scanner sc=new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = sc.nextInt();
String []nameArray=new String[number];
/*Since nextInt() does not read the newline character in your input
created by hitting "Enter"*/.
sc.nextLine();
for (int i = 0; i < number; i++) {
System.out.println("What is your name");
nameArray[i]=sc.nextLine();
}
sc.close(); //To prevent memory leak

How to print the selected name in the array?

How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
here is my code:
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
//Getting the names using for loop.
for(int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
for(int i = 0; i <numOfLoop; i++) {
if(name[i] == name[num]) {
System.out.println(name[i]);
}
}
Input:
6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.
Expected output: cody
I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().
Just adding in.nextLine(); before the For-loop should fix the problem.
Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.
There are several typical flaws in the code snippet to be addressed:
InputMismatchException - because not all new lines are consumed properly after calling to nextInt
name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible
The fixed code would look as follows:
Scanner in = new Scanner(System.in);
System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine(); // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
System.out.println("Looking for name: " + name[num]);
for (int i = 0; i <numOfLoop; i++) {
if(name[i].equals(name[num])) {
System.out.println(name[i] + " at index=" + i);
}
}
} else {
System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}
Sample output:
Input the number of names:
5
Input the names, one per line:
john
jeff
joan
john
jake
Input the index of the name to print:
0
Looking for name: john
john at index=0
john at index=3
You do not need the second loop.
All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.
// Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
if (num >= 0 && num < numOfLoop) {
System.out.println(name[num]);
} else {
System.out.println("Invalid index.");
}
}
}
Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?
A sample run:
5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
for (int i=0; i<name.length; i++){
String names = in.next();
name[i] = names;
}
System.out.println("The names array: " + Arrays.toString(name));
for(int index=0;index<name.length;index++) {
System.out.print("Enter an index you want to print: ");
index = in.nextInt();
System.out.println("index " + index + " is: " + name[index-1]);
}

Code Help - Used scanner to initialize string array. When displaying, array values are all blank

I'm currently taking a beginning Computer Science course and for one of our assignments we basically have to create a magic eight ball using an array where the user inputs the amount of values in the array and also inputs the values themselves in the array using a loop. After writing the code, I tested it and found that for some reason it wasn't setting the input into the array like it was supposed to it and after hours tweaking and trying to figure out what's wrong with it I still have no clue. Any help would be much appreciated.
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
input.next(); //It kept skipping the input part the first time
//so I added this
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
out.println("What is your question?");
question = input.nextLine();
input.next();
currentResponse = (int)(Math.random()*numResponses);
out.println(currentResponse);
out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank
spaces
}
out.println("Thank you for using the Magic Eight Ball");
The output should be something like
How many responses would you like there to be?
4 //The input
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[s,d,f,g]
What is your question?
s
0 //The randomized array index number
s //The value of that index
What is your question?
d
2
f
What is your question?
g
1
g
instead it's currently
4
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[, , , ]
What is your question?
s
0 //the randomized array index number
What is your question?
d
2
What is your question?
g
1
input.nextInt(); only consumes the integer entered, it doesn't consume the newline character entered after it. To get around this you can use input.nextLine(); to consume the newline char after it. Then you should be able to remove the input.next(); from the end of the for loop when taking in the responses.
You can also remove the input.next(); within the question loop later on as that's not needed as well -- the input.nextLine(); consumes the whole line.
Here's the adjusted code:
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
System.out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
input.nextLine();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
System.out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
System.out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
System.out.println("What is your question?");
question = input.nextLine();
currentResponse = (int)(Math.random() * numResponses);
System.out.println(currentResponse);
System.out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank spaces
}
System.out.println("Thank you for using the Magic Eight Ball");
}
Some additional documentation: https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html

JAVA using assigned values from an array in a calculation

This is a very basic question but I have just started out with JAVA and have hit a bit of a bump with regards to arrays.
What I am trying to do is populate an array with 6 pieces of information from the user:
Number of employees to be input,
An alphanumeric employee number,
A first name,
A last Name,
the number of hours they have worked,
a number input corresponding to Pay Scale.
So far I have gotten these inputs into an array in JAVA however what I wanted to do was use corresponding number input to select a constant within the Pay Scale array and then use that constant to calculate the wages of each employee.
for instance employee 1 worked 10 hours at scale 0 so that would be 10*4.50
and employee worked 10 hours at scale 1 which would be 10*4.62
import java.util.Arrays; //imports Array utility
import java.util.Scanner; //imports Scanner utility
public class test1 {
static Scanner keyb = new Scanner(System.in); //Adds a keyboard input
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
for (int i = 0; i < Employee.length; i++) {
System.out.print("Enter Employee Number: ");
Employee[i] = scanner.next();
System.out.print("Enter Employee's First name: ");
FirstName[i] = scanner.next();
System.out.print("Enter Employee's Last name: ");
LastName[i] = scanner.next();
System.out.print("Enter Employee's Hours worked: ");
HoursWorked[i] = scanner.nextDouble();
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
}
for (int i = 0; i < HoursWorked.length; i++) {
System.out.println("Employee " + Employee[i] + " " + FirstName[i] + " " + LastName[i] + " has "
+ HoursWorked[i] * PayScale[0]);
}
}
}
}
Am I even close to a solution on this?
Is what I'm asking possible in JAVA?
Maybe I'm just looking at this the wrong way, but any help regarding this would be greatly appreciated.
edit
OK I added the extras array into the code
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
int[]PayScale2 = {0,1,2,3,4};
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
I'm just unsure as to where I'd index the original PayScale array with the
PayScale[PayScale2[i]]
would it go into the for statement codeblock? (I have tried putting it in there however I get an error that it's not a statement :/
change
+ HoursWorked[i] * PayScale[0]);
to
+ HoursWorked[i] * PayScale[i]);
apart from that seems to me like you're doing what you're saying you should be doing..
you already have the payscales from here: double[] PayScale = {4.50,4.62,4.90,5.45,6.20}; so the following doesn't make a lot of sense:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
First of all, if you want to keep this number (Number 0 to 4) separately, you should use another Array, not the one where you keep the Payscales, then you could index to the first array which keeps the different rates.. or else you could directly use the first array if you know the pay scale for every employee.. in the end it has to do with what you want to do and how you want to do it, but the logic and the tools are there. If you call the 2nd array PayScale2 for example:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale2[i] = scanner.nextDouble();
then you can index to the first array for example:
PayScale[PayScale2[i]]
in which case if the user inputs 0 then PayScale2[i] would be 0 then PayScale[PayScale2[i]] would be PayScale[0] or 4.5 or whatever you set the value equal to at the first array

I cant take full names in my array [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[]repName = new String[5];
double[]salesAmount = new double[5];
System.out.println("Please Enter Sales Reps Name Followed By Monthly Sales: \n");
for (int i = 0 ; i < repName.length; i++ )
{
System.out.print("Sales Rep (Full Name): " );
repName[i] = input.nextLine();
System.out.print("Monthly Sales: € " );
salesAmount[i] = input.nextDouble();
System.out.println();
}
The code will only allow me to input a full name once, ie John Doe. It will not let me enter it with other doubles in the array. Why is this?
I got your error. When you enter double, you press enter. That is a new line which was taken instead of another name. Then it is expecting double but you are entering another name. So you get an input Mismatch.
After input.nextDouble() write input.nextLine();
The code should look like this.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[]repName = new String[5];
double[]salesAmount = new double[5];
System.out.println("Please Enter Sales Reps Name Followed By Monthly Sales: \n");
for (int i = 0 ; i < repName.length; i++ )
{
System.out.print("Sales Rep (Full Name): " );
repName[i] = input.nextLine();
System.out.print("Monthly Sales: € " );
salesAmount[i] = input.nextDouble();
input.nextLine();
System.out.println();
}
}
I have run your code, It's running well I think while entering salary you have not hit Enter key of your keybord.
I found that you are using loop over the length of person name. I think it is something wrong.
An easy way to solve this is to just use the next method instead of nextLine.
repName[i] = input.next();

Categories

Resources