My code is just printing out the last number from the list I create in a different program.
I need help storing the data into an array so I can sort it after.
edit: I need to take data from a file which is 'numbers.txt' and store it into an array.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[0] = numberArray;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}
Correction in the code.
1.) Inside while loop, list[0] = numberArray;, will keep adding elements on the same index 0, so lat value will override. SO something like list[i] = numberArray; will work, and increement i inside while loop. Take care of ArrayIndexOutOfBound Exception here.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
int i =0;
// Check for arrayIndexOutofBound Exception. SInce size is defined as 16
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[i] = numberArray;
i++;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}
Related
import java.util.Scanner;
import java.io.*;
public class practice3
{
public static void main(String[] args) throws IOException
{
int[] array = new int [99];
array = inputData();
for(int i=0; i<array.length; i++)
System.out.printf("%d",array[i]);
}
public static int[] inputData() throws IOException
{
final int MAX= 100;
int[] nums = new int[MAX];
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.print("Enter input file name: ");
String input = kb.nextLine();
File file = new File(input);
if(!file.exists())
{
System.out.println("The file entered is not found");
System.exit(0);
}
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && count < nums.length)
{
nums[count] = inputFile.nextInt();
count++;
}
inputFile.close();
return nums;
}
public static void printArray(int[] array, int counter)
{
System.out.println("Original array: ");
System.out.printf("%,12\n", array);
}
}
I don't know why these zeroes are printed after the array values I test from opening a file. I want to print the array itself and not the rest of the numbers. I tried messing with the MAX variable, but I dont know what to do.
The for loop in you main() iterates over the length of the array, which is 100 elements. The elements that you did not overwrite default to 0.
To solve this, pass the array as an argument to your inputData() and have it return how many elements it put into the array like:
public static int inputData(int[] input) {
// ...
input[count] = whatever;
// ...
return count;
}
Refactor arrays from int to Integer (0 -> null)
Add this before printing, it'll remove nulls from Integer (not int) array. (if int there will be zeroProblem)
int count = 0;
for (Integer i : array) {
if (i != null) {
count++;
}
}
Integer[] newArray = new Integer[count];
int index = 0;
for (Integer i : array) {
if (i != null) {
newArray[index++] = i;
}
}
Assume that i have 4 grades in testgrades.txt I don't know why this wont work.
public static void main(String[] args) throws FileNotFoundException {
File file1= new File("testgrades.txt");
int cnt = 4;
int[] grades = new int[cnt];
String line1;
for (int i=0; i<cnt; i++) {
Scanner inputFile2 = new Scanner(file1);
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
System.out.print(grades);
First of all, you should note that arrays in java hold fixed-size elements of the same type.
You can initialize them in one of two ways (not very sure if there are other ways).
//First method
int[] anArray = new int[10];
// Second method
int[] anArray = {1,2,3,4,5,6,7,8,9,10};
In either case, the array is of size 10 elements. Since you are fetching the data from the text file, I'll suggest you count number of lines into a variable and use that value to initialize the array. Then you can use a loop to fill the values this way:
// Assuming you have cnt as your total count of grades.
int[] grades = new int[cnt];
String line1;
for (int 1=0; i<cnt; i++) {
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
This is coming off my head so let me know if you face any problem.
You can do like this
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
File file= new File("testgrades.txt");
Scanner scan = new Scanner(file);
int arr[] = new int[100];
int i = 0;
do{
String line1 = scan.nextLine();
int grades2 = Integer.parseInt(line1);
arr[i++] = grades2;
}while(scan.hasNextLine());
for(int j = 0; j < i; j++){
System.out.println(arr[j]);
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
Write a method that returns a new array by eliminating the duplicate values in the array using this header:
public static int[] eliminateDuplicates (int[] list)
all I have so far is my main, but what I wanted to do for the other method was use a for loop to check values at each space in my array and print them if they did not equal any of the other entries. Working on it as we speak!
My output is this: The distinct numbers are: [I#4554617c
first of all this is 11 characters and at max I should be printing 10.
import java.util.Scanner;
public class EliminateDuplicates
{
public static void main(String [] Args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter ten whole numbers: ");
int[] tenNumbers = new int[10];
for (int i=0; i<10; i++)
{
tenNumbers[i] = input.nextInt();
}
System.out.println("The distinct numbers are: " + eliminateDuplicates(tenNumbers));
}
public static int[] eliminateDuplicates (int[] list)
{
int count = 0;
for (int i = 0; i > list.length; i++)
{
for (int j = i + 1; j < list.length; j++)
{
if(list[i] == list[j])
{
list[j] = -1;
}
}
}
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
count++;
}
}
int[] array2 = new int[count];
int newCount = 0;
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
array2[newCount] = list[i];
}
}
return array2;
}
}
import java.util.ArrayList;
public class EliminateDuplicates {
//This is called Generics, It'll be a little later in your studies
public static <E> ArrayList<E> eliminateDuplicates(ArrayList<E> list) {
ArrayList<E> newList = new ArrayList<>(list.size());
for (E aList : list) { // for (int i = 0; i <= list.lenght; i++){
if (!newList.contains(aList)) {
newList.add(aList);
}
}
return newList;
}
public static void main(String[] args) {
ArrayList<Integer> tenNumbers = new ArrayList<Integer>();
tenNumbers.add(14);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
ArrayList<Integer> newList = eliminateDuplicates(tenNumbers);
System.out.print("The distinct numbers are: " + newList);
}
}
import java.util.*;
public class Question {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = {1,2,3,3,4,5,6,1};
int[] ne = new int[arr.length];
ArrayList<Integer> already= new ArrayList();
int i = 0;
while(i<arr.length){
if(!already.contains(arr[i]))
already.add(arr[i]);
i++;
}
System.out.println(already.toString());
}
}
Basicaly need to scan this text file put it in to an array but i cant put any duplicates so it has to check the array and see if the array already contain that number, i cant use array list to do that.
My program puts in to an array put it put duplicates so how do i catch those duplicates to do something else with that and keep my array free of duplicates??
public static void readFromfile()throws IOException {
int[] numbers = new int[500];
int result, searchValue;
int index = 0;
// Open the file.
File file = new File("file.txt");
Scanner inputFile = new Scanner(file);
int w = 0;
for (int i=0; i<numbers.length; i++) {
if (i==0 || numbers[i] != numbers[i-1]) {
numbers[w++]=numbers[i];
while(inputFile.hasNextInt() && index < numbers.length) {
numbers[index] = inputFile.nextInt();
Arrays.sort(numbers);
System.out.println(numbers[index]);
//index++;
}
}
}
// Close the file.
inputFile.close();
}
}
Use TreeSet for unique and sorted list and convert it after reading file to an array:
Set<Integer> set = new TreeSet<Integer>();
while (inputFile.hasNextInt()) {
int value = inputFile.nextInt();
if (set.contains(value)) {
// save value to dublicate's file
}
set.add(value);
}
Integer[] numbersInteger = set.toArray(new Integer[set.size()]);
The result numbersInteger will contain exactly the number of elements which are sorted and unique. There will be no empty elements and you don't have to define the size of array before reading file.
If you really need to have an array of int instead of Integer then you have to add these lines:
int[] numbers = new int[numbersInteger.length];
for (int i = 0; i < numbersInteger.length; i++) {
numbers[i] = numbersInteger[i];
}
The code can do a binary search if the array is sorted. Using this in combination with a conditional if statement should determine whether the element should be inserted into the array. Note that if the binarySearch does not find the element it will return a negative result.
public static void readFromfile() throws IOException {
int[] numbers = new int[500];
int result, searchValue;
int index = 0;
// Open the file.
File file = new File("file.txt");
Scanner inputFile = new Scanner(file);
int w = 0;
for (int i = 0; i < numbers.length; i++) {
if (i == 0 || numbers[i] != numbers[i - 1]) {
numbers[w++] = numbers[i];
while (inputFile.hasNextInt() && index < numbers.length) {
int num = inputFile.nextInt();
Arrays.sort(numbers);
if(Arrays.binarySearch(numbers, num) < 0){
numbers[index] = inputFile.nextInt();
}
System.out.println(numbers[index]);
// index++;
}
}
}
// Close the file.
inputFile.close();
}
Use a Set. Every time you get a new number from your TXT file, you add it to the Set like this
Set s = new Set();
int tmp;
...
while(inputFile.hasNextInt() && index < numbers.length) {
tmp = inputFile.newtInt();
if (!s.contains(tmp)) {
s.add(tmp);
numbers[index] = tmp;
Arrays.sort(numbers);
System.out.println(numbers[index]);
//index++;
}
}
You should also consider moving Arrays.sort(numbers); out of the while loop.
Except if you need the array to be sorted at each step.
I have the following array
ArrayList<double[]> db_results = new ArrayList<double[]>();
and I would like to add values like this
db_results.add(new double[] {0,1,2});
but in a loop like this
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
db_results.add(new double[] {val});
}
obviously this is adding a new array each time with the single value... so how do I get it to add all into one array?
double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);
Create the double[] first, add the numbers to it, and add that array to the List.
(The variable should likely be declared as a List, btw, not an ArrayList, unless you're specifically passing it to something that explicitly expects an ArrayList.)
With something like that :
max = 3;
double[] doubles = new double[max];
for ( int i = 0 ; i < max; ++i)
{
double val = Double.parseDouble(i);
doubles[i] = val;
}
db_results.add(doubles);
import java.util.Scanner;
class DarrayEx2
{
public static void main(String args[])
{
int a[][]=new int[3][3];
int r,c,sumr;
Scanner s=new Scanner(System.in);
for(r=0;r<a.length;r++)
{
for (c=0;c<a.length ;c++ )
{
System.out.println("enter an element");
a[r][c]=s.nextInt();
}
}
for(r=0;r<a.length;r++)
{
sumr=0;
System.out.println("elements in a["+r+"] row is");
for (c=0;c<a[1].length ;c++ )
{
System.out.println(" "+a[r][c]);
sumr = sumr+a[r][c];
}
System.out.println(" = "+sumr);
System.out.println(" ");
}
}
}
source : http://www.exceptionhandle.com/portal/java/core-java/part-12-arrays.htm