Filling an array of integers by one prompting [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to fill an array of integers in Java by asking the user to enter the number once ?
for example :
Enter 3 integers >: 123
then I want to get the array filled like that :
arr[0]=1
arr[1]=2
arr[2]=3
I hope the question is clear :)
rgds

One way of going about this would be to take the integer in as a String. You can then use toCharArray() in order to grab an array of the characters - these characters can then be individually parsed into Integer by utilizing Character.getNumericValue().
See the String and Character APIs for more details on those methods.
Small example of what I mean:
String numbers = "123";
char[] numArray = numbers.toCharArray();
for (char c : numArray) {
int num = Character.getNumericValue(c);
// Do what you will with the number.
}
As noted, this particular implementation would only work in this format if you are assuming that each integer is single digit.

How about this:-
Scanner input = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}

Related

Print the index of an array next to the array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to print an array's element with it's index next to it. If the array element is even, it must display the element and its correlating index number, if the element is odd, it must display the element and "1".
For example:
Input: int[] array = new int [25]
Output: 0:0, 1:1, 2:2, 3:1, 4:4, 5:1, 6:6, 7:1 and so on
How would I do this?
You could do something like, You can check if a number is even then print the number and index separated by a colon else print number and 1 separated by a colon, This can be achieved by using for loop construct.Would recommend you to follow proper guide/tutorial as you look like a beginner in java.
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
int counter = 0;
for(int i : array) {
if(i % 2 == 0)
System.out.print(i+":"+counter);
else
System.out.print(i+":1");
if(counter<array.length-1)
System.out.print(", ");
counter++;
}

How to clarify whether the user's input was a binary number? [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 6 years ago.
Improve this question
I was required to make a code that accepted a binary number (1's and 0's) and then counted how many ones were in that binary number. My code fulfills this purpose.
The second part of the exercise is this: if the user enters a number that is NOT binary, I must output that there is an error and keep prompting the user until they give a binary number.
Can someone show me how to incorporate this? I have tried several times but cannot make it click. Thanks! Here is my code.
import java.util.Scanner;
public class NewClass
{
public static void main( String [] args )
{
Scanner scan = new Scanner( System.in);
int i = 0, count = 0;
String number;
System.out.println("Please enter a binary number.");
number = scan.next();
String number1 = "1";
while ((i = number.indexOf(number1, i++)) != -1) {
count++;
i += number1.length();
}
System.out.println("There are "+ count + " ones in the binary number.");
}
}
You already know how to find all of the 1's; you should be able to do something similar to find all of the 0's.
If the sum of those two counts is not the length of the string, there must be at least one illegal character in it.
If you use the parseInt method you can do
Integer.parseInt("1100110", 2) returns 102
or in your case
int intVal = Integer.parseInt(number, 2);
as per the javadocs
Throws:
NumberFormatException - if the String does not contain a parsable int.

Why can't I read indefinately doubles using this loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to read some data from a user and do some very simple calculations with them, but for some reason I can't explain, the program stops after first 2-3 inputs (given they are doubles). Can someone explain this behaviour?
My code:
Scanner in = new Scanner(System.in);
System.out.println("Enter your values, 'q' to quit: ");
double average, input, smallest, largest, range;
average = smallest = largest = range = Double.parseDouble(in.nextLine());
int counter = 1;
while (in.hasNextDouble()) {
input = Double.parseDouble(in.nextLine());
smallest = input < smallest ? input: 0;
largest = input > largest ? input: 0;
average += input;
counter++;
}
Consider this input:
1.23
4.56 7.89
To Scanner this looks like a valid sequence of three doubles on two separate lines. When you call nextLine to obtain the first double, it works fine, because the number occupies the entire string.
When you do the same for the next double, the string that you try to parse looks like this:
"4.56 7.89"
This string is not a valid double, so you cannot parse it.
One approach to deal with this problem is to call nextDouble, and avoid parsing altogether. Pairing up hasNextDouble() with nextDouble() has an advantage of not requiring users to put their data on different lines.
Note: The first call to Double.parseDouble(in.nextLine()) happens without checking that Scanner has next double, so your program could crash on initial bad input.

Java Array Index Out of Bounds Exception [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am getting the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at sorting.main(sorting.java:53). I am just trying to pass string integer values to an integer array but it is not working as intended. I have variables above such as count which is determined by how many integers the user wants to enter. In and another variable int[] list = new int[count]; which is the integer array I am trying to pass them to. If I enter the value of 5 for count I am trying to only accept 5 values of integers. Passing them to the int[] list array is where I am messing up.
// Prompts user to enter the integer values here
while(true){
System.out.print("\nEnter integer values here seperated by a space: ");
intValues = input.readLine();
String[] intCheck = intValues.split("\\s+");
try {
for(int j = 0; j < intCheck.length; j++){
list[j] = Integer.parseInt(intCheck[j]); // LINE 53 IS HERE
}
}
catch (NumberFormatException ex) {
System.err.println("You need to enter valid integer numbers. Try again.");
}
}
you probably have an extra space at the end so your split is returning an overlarge array. Use j < count.
I have gotten my error. I declared int count = 0 early on. Then just below that I declared int[] list = new int[count] which was taking 0 values. I should have declared the range after I prompted the user to enter the information.

Identifing the single largest number occurring in a file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's assume a text file is a Math text book. How should I code to find out the largest number in that file? I'm aware of using StringTokens, parseLong, split, etc. But I can't figure out a proper way to combine them.
To be precise, let's say that text has something like:
Chapter 3.5
Million has 6 zeros. Ex. 6,000,000
Billion has 9 zeros. Ex. 9,000,000,000
Trillion has 12 zeros. Ex. 8,000,000,000,000
The largest number is 8000000000000. How do I extract that?
Thanks in advance.
Use the Scanner interface. This code assumes you pass in the file path as the first argument. The Scanner interface handles commas in numbers. I use BigInteger to handle any size number.
public static void main (String[] args) throws java.lang.Exception
{
BigInteger biggestNumber = null;
Scanner s = new Scanner(new FileReader(args[0]));
while( s.hasNext() ){
if( s.hasNextBigInteger() ){
BigInteger number = s.nextBigInteger();
if( biggestNumber == null || number.compareTo(biggestNumber) == 1 ){
biggestNumber = number;
}
}
else {
s.next();
}
}
System.out.println("Biggest Number: " + biggestNumber.toString());
}
You can play with an online example at: http://ideone.com/zKI5rM . It doesn't read from a file but uses a string in the code instead.
One place this would fail is if the book splits large numbers across lines. I'm not sure what your source material is, but that is something to keep in mind.
Store the largest number seen so far (initially, negative infinity), then go through the entire file extracting each number and if it's greater than the largest number you've stored, store it. At the end, the number stored is the largest number. Use double rather than long to account for very large numbers and noninteger numbers. The simple way to find all integers is to use a Scanner, feeding next() into parseDouble(...) and comparing anything that doesn't throw a NumberFormatException.
The easiest way would be to parse the text file line by line.
You can do this using regular expressions to see if you have any number formats located in the current line. If you do then you can check to see if it's larger than the previously found number.
Here is an excellent tutorial on regular expressions if you haven't came across them yet.
http://www.vogella.com/articles/JavaRegularExpressions/article.html
You can use BigInteger
public class Test {
public static void main(String[] arg) {
String line = "215,485,454,648,464";
String line1 = "5,454,546,545,645";
List<BigInteger> list = new ArrayList<BigInteger>();
list.add(new BigInteger(line.replaceAll(",", "")));
list.add(new BigInteger(line1.replaceAll(",", "")));
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}
}
Output: largest: 215485454648464
For your situation
public static void main(String[] args){
Scanner input = new Scanner(new File("yourFile.txt");
List<BigInteger> list = new ArrayList<BigInteger>();
while (input.hasNextLine()){
String line = input.nextLine();
String[] tokens = line.split("\\s+");
String number = token[5].trim(); // gets only the last part of String
list.add(new BigInteger(line.replaceAll(",", "")));
}
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}

Categories