I keep getting the error "cannot find symbol 'arr' " How do I accept both the array as a user input (being a float not a double) and 3 float variables as elements in the array?
import java.util.Scanner;
public class runtime_array
{
public static void main(String[] args){
System.out.println("Program creates array size at run-time");
System.out.println("Program rounds sum and average of numbers to two decimal places");
System.out.println("Note: numbers *must* be float data type");
System.out.println(); //blank line
// taking String array input from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter length of String array");
int length = input.nextInt();
arr[i] = input.nextInt();
// create an array to save user input
float[] input = new float[length];
float[] input = new float[arr];
// loop over array to save user input
System.out.println("Please enter array elements");
for (int i = 0; i < length; i++) {
}
float sum = 0;
System.out.println("The array input from user is : ");
for(int i = 0; i < arr.length; i++){
System.out.println(String.format("%.2f", Float.valueOf(arr[i])));
sum += Float.valueOf(arr[i]);
}
System.out.println("The sum is: " + String.format("%.2f",sum));
System.out.println("The average is: " + String.format("%.2f",(sum/length)));
}
}
You've got a couple issues here
First, you cannot declare float[] input because you've already given Scanner to the reference for input. You need to name your float[] something different. Let's go with userInput.
Scanner input = new Scanner(System.in);
System.out.println("Please enter length of String array");
int length = input.nextInt();
float[] userInput = new float[length];
Next, you are trying to do things with arr before you have declared it. However, I don't even think you need a reference to arr. You should remove this line.
arr[i] = input.nextInt();
Furthermore, you need to prompt your user during each loop iteration, as well as append the Scanner input to float[] userInput.
for (int i = 0; i < length; i++) {
System.out.println("Please enter array elements");
userInput[i] = input.nextInt();
}
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");
}
}
}
}
I need to write a program in Java that prompts the user to enter three integer. Among these integers entered, the largest of said integers will need to be found in addition to the square root. I'm just a beginner, and I appreciate any and all assistance.
import java.util.Scanner;
public class largest {
public static void main (String [] args) {
int Integer1;
int Integer2;
int Integer3;
Scanner input=new Scanner(System.in);
System.out.println("Enter 3 integers:");
Integer1 = input.nextInt();
Integer2 = input.nextInt();
Integer3 = input.nextInt();
if (Integer1 > Integer2);
System.out.println (Integer1);
if (Integer1 > Integer3);
System.out.println (Integer1)
This is all I have so far, and I'm dubious that I'm even on track. Please, help.
I would recommend using Math.max as aioobe suggested, but if you want to implement the logic yourself use this:
import java.util.Scanner;
import java.lang.Math;
class prog {
public static void main (String [] args) {
int Integer1;
int Integer2;
int Integer3;
Scanner input = new Scanner(System.in);
System.out.println("Enter 3 integers:");
Integer1 = input.nextInt();
Integer2 = input.nextInt();
Integer3 = input.nextInt();
if (Integer1 > Integer2) {
if (Integer1 > Integer3) {
System.out.println (Integer1);
System.out.println (Math.sqrt((float)Integer1));
}
else {
System.out.println (Integer3);
System.out.println (Math.sqrt((float)Integer3));
}
}
else if (Integer2 > Integer3) {
System.out.println (Integer2);
System.out.println (Math.sqrt((float)Integer2));
}
else {
System.out.println (Integer3);
System.out.println (Math.sqrt((float)Integer3));
}
}
}
For anything more than 3, your best off using Math.max. The (float) part is converting the integer to a float, otherwise the square root wouldn't be precise (as integers are whole numbers
There are a lot of ways to do this and you can use different libraries and data types , I'm not sure you are allowed to use for loop , array or Lists .
Mostly for these kind of jobs you need to use loops, that make it simple and easy to understand .
Here are few different ways that you can do it :
In this example if you need to get more than 3 entries simply modify the number 4 to number of integers that you need to receive from user.
int num, tmp = 0;
Scanner input = new Scanner(System.in);
for (int i = 1; i < 4; i++) {
System.out.printf("Enter integer number %d :", i);
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
}
System.out.printf("the largest number is :%d and the Square is: %s", tmp, Math.sqrt((float) tmp));
second Way without using the for loop:
int num, tmp = 0;
Scanner input = new Scanner(System.in);
System.out.printf("Enter integer number 1 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("Enter integer number 2 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("Enter integer number 3 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("the largest number is :%d and the Square is: %s", tmp, Math.sqrt((float) tmp));
Always try to use less variables, that's make your application more memory efficient.
I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Try this
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.
String input = scanner.nextLine(); // get the entire line after the prompt
String[] numbers = input.split(" "); // split by spaces
Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()
Scanner has a method called hasNext():
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
System.out.println(scanner.nextInt());
}
If you know how much integers you will get, then you can use nextInt() method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.
import java.util.Scanner; // imports class so we can use Scanner object
public class Test
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter numbers: ");
// This inputs the numbers and stores as one whole string value
// (e.g. if user entered 1 2 3, input = "1 2 3").
String input = keyboard.nextLine();
// This splits up the string every at every space and stores these
// values in an array called numbersStr. (e.g. if the input variable is
// "1 2 3", numbersStr would be {"1", "2", "3"} )
String[] numbersStr = input.split(" ");
// This makes an int[] array the same length as our string array
// called numbers. This is how we will store each number as an integer
// instead of a string when we have the values.
int[] numbers = new int[ numbersStr.length ];
// Starts a for loop which iterates through the whole array of the
// numbers as strings.
for ( int i = 0; i < numbersStr.length; i++ )
{
// Turns every value in the numbersStr array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt( numbersStr[i] );
// OPTIONAL: Prints out each value in the numbers array.
System.out.print( numbers[i] + ", " );
}
System.out.println();
}
}
There is more than one way to do that but simple one is using String.split(" ")
this is a method of String class that separate words by a spacial character(s) like " " (space)
All we need to do is save this word in an Array of Strings.
Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :
for (int i = 0; i < stringsArray.length; i++) {
int x = Integer.parseInt(stringsArray[i]);
// Do what you want to do with these int value here
}
Best way is converting the whole stringArray to an intArray :
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
now do any proses you want like print or sum or... on intArray
The whole code will be like this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
}
}
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
Using this on many coding sites:
CASE 1: WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8 , 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
It's working with this code:
Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();
A simple solution can be to consider the input as an array.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //declare number of integers you will take as input
int[] arr = new int[n]; //declare array
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt(); //take values
}
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
This method only requires users to enter the "return" key once after they have finished entering numbers:
It also skips special characters so that the final array will only contains integers
ArrayList<Integer> nums = new ArrayList<>();
// User input
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
if (!n.isEmpty()) {
String[] str = n.split(" ");
for (String s : str) {
try {
nums.add(Integer.valueOf(s));
} catch (NumberFormatException e) {
System.out.println(s + " cannot be converted to Integer, skipping...");
}
}
}
//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenSum = 0;
int oddSum = 0;
while (n > 0) {
int last = n % 10;
if (last % 2 == 0) {
evenSum += last;
} else {
oddSum += last;
}
n = n / 10;
}
System.out.println(evenSum + " " + oddSum);
}
}
if ur getting nzec error, try this:
try{
//your code
}
catch(Exception e){
return;
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`
I need to solve the following problem: Write a method named tokenStats that accepts as a parameter a Scanner containing a series of tokens. It should print out the sum of all the tokens that are legal integers, the sum of all the tokens that are legal real numbers but not integers, and the total number of tokens of any kind. For example, if a Scanner called data contains the following tokens:
3 3.14 10 squid 10.x 6.0
Then the call of tokenStats(data); should print the following output:
integers: 13
real numbers: 9.14
total tokens: 6
If the Scanner has no tokens, the method should print:
integers: 0
real numbers: 0.0
total tokens: 0
So, this is my question. I have tried to use
while (input.hasNext()) {
if (input.hasNextInt()) {
and this creates an infinite loop,
but if I use
while (input.hasNext()) {
input.next();
if (input.hasNextInt()) {
I lose my first token if it is an int...
what should I do?
I suggest you check this way .. which cover all your scenario
int totalint =0;
float totalfloat=0 ;
int count=0;
while(input.hasNext())
{
String next = input.next();
int n; float f;
try{
if(next.contains(".")
{
f= Float.parseFloat(next);
totalfloat += f;
}
else{
n= Integer.parseInt(next);
totalint +=n;
}
}
catch(Exception e){ /*not int nor a float so nothing*/ }
count++;
}
In order to determine the amount of Integers in your file I suggest doing something like this
Add the following variables to your code
ArrayList<Integer> list = new ArrayList<Integer>();
int EntryCount = 0;
int IntegerCount =0;
Then when looking through the file inputs try something like this were s is an instance of a scanner
while (s.hasNext()) {
if(s.hasNextInt() == true){
int add =s.nextInt();
System.out.println(add);
list.add(add);
IntegerCount++;
}
EntryCount++;
}
Then in order to figure out the sum of all integers you would loop through the array list.
public static void tokenStats(Scanner input) {
int integers = 0;
double real = 0.0;
int tokens = 0;
while (input.hasNext()) {
if (input.hasNextInt()) {
integers+= input.nextInt();
} else if (input.hasNextDouble()) {
real+= input.nextDouble();
} else {
input.next();
}
tokens++;
}
System.out.println("integers: " + integers);
System.out.println("real numbers: " + real);
System.out.println("total tokens: " + tokens);
}