for loop is printing twice in java and data conversion [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;
public class salary
{
public static void main(String[] args)
{
int n,sum=0,average=0,count1=0,count2=0;
System.out.println("How many people salary you want to enter" );
Scanner in = new Scanner(System.in);
n = in.nextInt();
String[] salary=new String[n];
int[] sal=new int[n];
for (int i=0;i<n;i++)
{
System.out.println("please enter salary with $ sign as prefix" );
salary[i]=in.nextLine();
}
for (int j=0;j<n;j++)
{
salary[j] = salary[j].replaceAll("[$]+", "0");
System.out.println(salary[j]);
sal[j]= Integer.parseInt(salary[j]);
//salary[j] = Integer.parseInt(salary[j].replaceAll("[$]+", " "));
sum=sum+sal[j];
}
average=sum/n;
for(int q=0;q<n;q++)
{
if (sal[q]>average)
{count1=count1+1;
}
else if (sal[q]<average)
{
count2=count2+1;
}}
System.out.println("The average is "+average);
System.out.println("The salary greater than average "+count1);
System.out.println("The salary less than average "+count2);
}
}
getting error and also for loop is not working properly
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at salary.main(salary.java:34)
read a list of salary amounts that start with a dollar sign “$” and followed by a nonnegative
number, save the valid salary inputs into an array and sort the salary in ascending
order, calculate the average of the salary inputs, and count the number of inputs less than
/greater than the average.

Change Line 16 to in.next:
for (int i = 0; i < n; i++) {
System.out.println("please enter salary with $ sign as prefix");
salary[i] = in.next();
}

Related

My code's output is not the array I input [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 1 year ago.
I am trying to run the following code in order to input an array of any size I desire:
import java.util.Scanner;
import java.util.Arrays;
public class testing2 {
public static void main(String[] args) {
double[] inputs = new double[5];
int currentSize = 0;
System.out.println("Please enter values, Q to quit:");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
inputs = Arrays.copyOf(inputs, currentSize);
System.out.print(inputs);
}
}
But when I input any array, my output is just a combination of symbols such as: [D#13fee20c, and this is not the output I am hoping for. Could anyone help me?
You're not printing correctly:
for (int i = 0; i < input.length; i++)
System.out.print(input[i] + " ");
}

Problems with Arrays and Methods [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
How to get the program to read a set of integers from an input file. The goal is to store them in an array and then display greater values than input. Also, Also, create a method called greater_than_n() that accepts an integer array and an integer n. The purpose of this method is to display numbers greater than n
import java.util.Scanner;
import java.io.*;
public class Lab5 // File Name{
public static void main(String[] args) throws IOException
{
Scanner userInput = new Scanner(System.in);
File Integers = new File("Integers.txt");
Scanner inputReader = new Scanner(Integers);
String line = inputReader.nextLine();
System.out.print(line);
inputReader.close();
System.out.print("Enter an Integer: ");
int userAction = userInput.nextInt();
System.out.println("The numbers in the input file that are greater than " + userAction + " are: ");
for (int index = 0; index < Integers.length; index++)
{
if(Integers[index] > userAction)
{
System.out.print(Integers + " ");
}
}
}
}
You are checking in a wrong way. Your loop should iterate up to the length of array. Then if you want to print the greater numbers in the array, check each element if greater than the input number. If yes, print the number in the index.
Scanner userInput = new Scanner(System.in);
int[] numbers = {2, -4, 6, 8, 19};
System.out.print("Enter an Integer: ");
int userAction = userInput.nextInt();
System.out.println("The numbers in the input file that are greater than " + userAction + " are: ");
for (int index = 0; index < numbers.length; index++) {
if(numbers[index] > userAction)
System.out.print(numbers[index] + " ");
}
You are printing out array on every step of loop, to print out a number you should change System.out.print(numbers); for System.out.print(numbers[index]);.
More of than if you want to print just number which greater then input (userAction=3, output should be 6, 8, 19 for your example), you have a error in your algorithm. What your algorithm does is just print out array userAction times. To fix it you can use this snippet:
for (int index = 0; index < numbers.length; index++)
{
if (numbers[index] > userAction) {
System.out.print(numbers[index]);
}
}
You print the Arrayobject, what you want is to print the index of the array, this can be accomplished by using:
System.out.print(numbers[index]).

Based on user input years, generate random numbers for a 2d array based on the user input

Before I state my question I have searched the questions that have already been posted and they were of some help to me, but not really what I am looking for.
For now, don't worry about the 2d array portion.
I am supposed to create a program that generates random float values based on the user input for a number of years. Let me explain.
First it asks for the user input for years; the user enters a value between 1-80 and the program checks if the entered value is between those two. (DONE)
Then, based on the user input, it will print out each year with a random value between [0.00 and 100.00] like so.
Example; if user enters 3, then the output will display;
year 1: random values
year 2: random values
year 3: random values
Let's just start with that for now. I already have it to where it it asks for user input and I did have it to where it generated random values, but they were not between what I wanted.
Here is my code so far.
package name;
import java.util.*;
public class name {
public static void main(String[] args) {
Random generator = new Random();
inputCheck();
}
public static void inputCheck(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the desired number of years: ");
int years = keyboard.nextInt();
System.out.println();
while (years < 1 || years >= 80){
System.out.print("Please enter a value for years that is greater than 1 and less than 80: ");
years = keyboard.nextInt();
System.out.println();
}
}
}
Here you are
public class Test {
public static void main(String[] args) {
Random generator = new Random();
int years = inputCheck();
for (int i = 1; i <= years; i++) {
System.out.println("Year " + i + ": " + generator.nextFloat() * 100);
}
}
public static int inputCheck() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the desired number of years: ");
int years = keyboard.nextInt();
System.out.println();
while (years < 1 || years >= 80) {
System.out.print("Please enter a value for years that is greater than 1 and less than 80: ");
years = keyboard.nextInt();
System.out.println();
}
return years;
}
}
I don't see that generator being used, but aside from that, when you do you will only get an integer between zero and the given value(without manipulation of course) wha you want is a float between 0 and 100 with two decimal places, so generate the random number:
Randint=(Generator.nextFloat(100.00));
At least that is what I remember 😁.
I only gave this since you say you have everything else down pat.

Asking the user what size the array should be

import java.util.Scanner;
/**
* Created by b00598439 on 30/09/2015.
*/
public class Assessment1 {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
for (int i = 1; i<=2; i=>3; i++){
answer[i] nextInt(); //Get integer entered, if different from 1 or 2, if any other number then quit
}
System.out.println("What size of array would you like?");
int SIZE = in.nextInt(); //What size should the array be?
int [] answer = new int[SIZE]; //Lets user read into the program
System.out.println("The total of the numbers in the program is: " + answer); //Gives total of numbers
System.out.println("The average of the numbers in the program is: " + avg);
int count = 0;
for (int i = 0) ; //Calculating the average
I have been trying to get the code sorted to write to screen and follow on through for the size of the array. I have to get the user to select an option 1, or option 2, if option 1 or 2 isn't chosen then I have to terminate the program. I cannot even get the first part printing or working and this is what I have to do:
1) If the array option is chosen, the program should:
• Ask the user what the size of the array should be
• Let the user read in the numbers into the array
• Output the total of the numbers stored in the array
• Output the average of the numbers stored in the array
I have been sitting here for 4 hours and still getting nowhere
Any help would be appreciated
This can be done in many ways,I have done it in a simple way so you can understand the whole code step by step.By the way,you haven't explained what you want the program to do if option 2 was chosen.You can remove the option 2 by deleting the "case 2:".See the code.
import java.util.Scanner;
public class Assessment1 {
public static void main (String args[]) {
int average,sum=0;
Scanner input = new Scanner(System.in);
Scanner length = new Scanner(System.in);
Scanner option = new Scanner(System.in);
System.out.println("Enter 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
int x=option.nextInt();
switch(x){
case 1:
System.out.println("Input array size: ");
int len=length.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
sum += numbers[i];
}
average=sum/len;
System.out.println("Total sum of all numbers: "+sum);
System.out.println("Average of all numbers: "+average);
case 2:
//insert your "ArrayList code here,you haven't explained what you want here
default:
System.out.println("Program terminated.");
}
}
}
Ok, I developed a little more the code. I put it inside a while loop... it goes back to the beginning and asks to again to enter the options... you enter any number other than 1 or 2 and you get out. I tested it and it works ok in the console. Just a comment.. you are getting the average in integer values... if you would like to get doubles then you have to use doubles and use nextDouble instead of nextInt. Hope that it helps.
import java.util.Scanner;
public class Assessment{
public static void main(String[] args){
// Scanner to get the initial number options
Scanner in = new Scanner(System.in);
// Scanner to get numbers to sum
Scanner numSc = new Scanner(System.in);
// Declaration of variables and array
int answer = 0; //You need int answer, don't need an array by now
int numAnswer;
int sum = 0;
int average;
// Loop the program
while (true){
System.out.println("Enter number 1 for arrays, 2 for arraylists, any other to quit");
// Using in Scanner to test for integer input
if(in.hasNextInt()){
// If there is an integer then give it to numAnswer
numAnswer = in.nextInt();
// What to do if the option is 1, 2 or other number
switch(numAnswer)
{
case 1:
case 2:
answer = numAnswer;
break;
default:
System.exit(0); // Out of the program
}
}
// If answer variable got number 1
if (answer == 1){
// New Scanner to get the size of the array
Scanner sizeSc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
// Getting the size of the array with sizeSc Scanner
int size = sizeSc.nextInt();
// Making a new array with the size of size variable
int[] inputNums = new int[size];
// Looping to get input numbers
for (int i = 0; i < inputNums.length; i++){
System.out.println("Enter a number in the array: ");
//Getting the numbers from console with numSc Scanner
inputNums[i] = numSc.nextInt();
sum += inputNums[i]; //Getting the sum of each number
}
average = (sum/size);
System.out.println("Sum of numbers: " + sum);
System.out.println("Average of numbers: " + average);
System.out.println(" ");
} else {
System.out.println("YOUR CODE TO THE LISTARRAY");
}
}
}
}

Creating if statement for the small program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently struggling with my first java program.
The question's task was to create a program that prompts the user to enter 5 numbers and store them in an array. Then the array should be printed, after that's done the program prompts the user to enter a number to search. Depending on the number the program should print "(display number) is on the list" or "(display number) is not on the list"
I have been struggling with this for quite a while now not fully understanding the conditional task.
Here is what my code looks like:
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
System.out.println("The sorted numbers are "
+ number1 + ", " + number2 + ", " + number3 + ", " + number4 + ", " + number5);
System.out.println("Enter a number to search: ");
}
I added comments to document what the code was doing. This should hopefully help you grasp the concept.
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
//Create an array of integers to store user input
int[] userNumbers = new int[5];
System.out.print("Enter " userNumbers.length + " numbers: ");
//Goes into a loop, and sets each array index to the user inputted integer
for (int i = 0; i < userNumbers.length; i++) {
userNumbers[i] = input.nextInt();
}
System.out.println("Enter a number you would like to search for");
boolean exists = false;
int numToSearch = input.nextInt();
//for each number in the user numbers array, check to see if that number matches the number to search. If so, set exists = true and break out of the loop to check no further.
for (int num: userNumbers) {
if (numToSearch == num) {
exists = true;
break;
}
}
//if else to decide which output to show the user.
if (exists) {
System.out.println(numToSearch + " is in the list");
} else {
System.out.println(numToSearch + " is not in the list");
}
}
}
At first instead of storing your numbers in single variables, you store them in an array.
The next thing you'll do is use
boolean tmp = false;
int search = input.nextInt();
This will give you the number the user is searching for.
When you have it (the program will wait at the instruction until there's input), you loop over your array and in each iteration you compare it to the given number. You do this by using
if (array[i] == search) {
tmp = true}
With i being your iteration variable.
After the end of the for loop, you'll do another if where you, depending on the state of the tmp variable either print that the number exists or it doesn't.
Sorry for short explanation.
Try following....
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
List<Integer> integers = new ArrayList<Integer>();
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
integers.add(number1);
integers.add(number2);
integers.add(number3);
integers.add(number4);
integers.add(number5);
System.out.println("The sorted numbers are "
+integers);
System.out.println("Enter a number to search: ");
int searchNum = input.nextInt();
if(integers.contains(seacrchNum)){
System.out.println(searchNum+" is on the list");
}else{
System.out.println(searchNum+" is not on the list");
}
}
Explainations :
Placed all the entered numbers into an arrayLists and then prompt for the search Number to be entered. and Check wheather the search number is der in the ArrayLists or not. Based on the condition display the Message

Categories