processing single dimensional array java - java

I'm trying to create an array with user input from a dialog box. It's supposed to ask how many numbers the user wants to enter, then ask the user to input the numbers. The code is then supposed to output the numbers in reverse order. Below is the code I have so far.. it doesn't work. I did something wrong with trying to initialize the array with user input. I'm pretty new to java so any advice is welcome. Thanks in advance.
public static void main(String[] args)
{
String input;
int space;
double [] numbers;
double count;
String numberInput;
double number;
input = JOptionPane.showInputDialog
(null, "How many numbers would you like to enter?");
space = Integer.parseInt(input);
numbers = new double[space];
count = 0;
while (count < space)
{
numberInput = JOptionPane.showInputDialog
(null, "Enter a number to be sorted: ");
number = Double.parseDouble(numberInput);
for (int i = 0; i < numbers.length; i++)
numbers[i] = number;
count++;
}
double[] numbers2 = swapArray(numbers);
JOptionPane.showMessageDialog(null, numbers2);
}
public static double[] swapArray(double[] array)
{
double[] result = new double[array.length];
for (int i = 0, j = result.length - 1;
i < array.length; i++, j--)
{
result[j] = array[i];
}
return result;
}
}

Here is my take on your assignment. It should give you some ideas on how to deal with the problem, without giving you a copy-paste solution, nor the best-possible (to my own ability) structure/logic (but still giving you tips to point you in their direction):
package so_q33405148;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
//TIP: You can use 'Scanner' instead of a 'Reader' here, to avoid having to parse strings into ints (scanner can do it for you)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many numbers would you like to enter?");
int count = Integer.parseInt(br.readLine());
int input[] = new int[count];
for (int i = 0; i < count; i++) {
System.out.print("Enter a number to be sorted: ");
//TIP: With some clever math, you can invert the array right as it's still filling up here, by manipulating a new int (so 'i' is unchanged, as it's the for-loop's index) using 'i' and 'input.length'...Or, with a little creativity and insight, you may even achieve the same result manipulating 'i' directly somewhere else...
input[i] = Integer.parseInt(br.readLine());
}
System.out.println("Original array:\n" + Arrays.toString(input));
//TIP: Better methods to reverse arrays and/or collections exist.
//Take a look at SO question #3962766 (puritan solution without as much memory-footprint) and also Google about 'Arrays.asList()' and 'Collections.reverse()' (learn about collections-sorting)
int reversedInput[] = new int[input.length];
for (int i = 0; i < count; i++) {
reversedInput[i] = input[count - i - 1];
}
System.out.println("Reversed array:\n" + Arrays.toString(reversedInput));
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Related

How to keep track of the sum of each of the three columns Java

My Question is how to get my program to add each column separately and then find the average afterwards. E.g. 33+42+11 /3 expressed in Java.
Hope that clarifies the question.
I have also linked the numbers and columns below
import java.util.Arrays;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class Assignment
{
public static void main(String[] args)
throws IOException
{
FileInputStream control = null;
Scanner scanner = null;
if (args.length == 0) {
System.out.println("file name expected");
System.exit(0);
}
System.out.println("Opening file " + args[0]);
control = new FileInputStream(args[0]);
System.out.println("Opening of file " + args[0] + " successful");
scanner = new Scanner(control);
long sum = 0;
int count = 0;
if (!scanner.hasNext()) {
System.out.println("No integers");
System.exit(0);
}
while (scanner.hasNext()) {
long number = scanner.nextInt();
sum += number;
count++;
}
long average = sum / count;
System.out.println(average);
control.close();
}
}
This is the columns. Not too sure about how to make it start adding from 127 down to 10 and same for the other two columns
127 33 22
2147483647 42 59
10 11 55
I think I was able to interpret the question.
Here is a working solution - note that you need to scan for one line at a time with one scanner, and then scan each of those lines to break it up into columns. I then stored each of those sums and counts in an array, as you mentioned you wanted to use arrays. However, I just made those arrays hold up to 10 counts, and didn't do any sizing checks on those - those types of issues seemed outside the scope of the original question.
https://repl.it/repls/TintedNarrowRectangle
import java.util.Scanner;
public class Main {
public static void main(String[] args){
String fakeFileInput = " 127 33 22\n2147483647 42 59\n10 11 55";
Scanner scanner = new Scanner(fakeFileInput);
if (!scanner.hasNext()) {
System.out.println("No integers");
System.exit(0);
}
long[] sums = new long[10];
int[] counts = new int[10];
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Scanner innerScan = new Scanner(line);
int current = 0;
while (innerScan.hasNextInt()) {
int number = innerScan.nextInt();
sums[current] += number;
counts[current] += 1;
current++;
}
}
for (int i = 0; i < sums.length; i++) {
System.out.println((1.0*sums[i])/counts[i] + " average for " + i + " column");
}
}
}
I am just providing a 3 * 3 grid solution and my goal is to keep each column summation. My final output would be like {(127+2147483647+ 10), (33+42+11), (22+59+55)}
For that, you just need to maintain another array. For example, you will keep each column summation in sum[] array.
Since you have only 3 columns, you just need sum[] size 3.
int[] sum = new int[3]
After allocation, you can reset sum arrays each index value 0.
for (int i = 0; i < 3; i++) {
sum[i]=0
}
Now the only thing left is taking each row input value. Since you have only 3 columns in each row and totally of 3 raws. You can follow below code snippet.
for (int i=0;i<3;i++){
for(int j=0;j<3;j++){
int number = scanner.nextInt();
sum[i] = sum[i] + number;
}
}
Now you can use sum[] array for your final result. Each sum[] index holds on each column summation.

program that reads integers between 1 and 100 and counts the occurrence of each

Write a program that reads integers between
1 and 100 and counts the occurrence of each (you should store the numbers in an array). Output should be in ascending order. Assume the input ends when the user enters a 0.
Hi guys, I know that this question has been posted before, perhaps a lot of times, but as I am a complete beginner at java, I don't completely understand the complexity of the codes that are posted. I just started taking Java classes, and would appreciate if you could help me figure out how to get my program to output the correct occurrences at the end. I'm so close to getting the answer but I can't figure it out for the life of me!! Thanks in advance!
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
//declarations
int [] myArray = new int [100];
int input = 5;
Scanner keyboard = new Scanner(System.in);
//input and processing
System.out.println("Please enter integers between 1 and 100 (enter 0 to stop): ");
while (input != 0)
{
input = keyboard.nextInt();
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] = input;
}
}
}
//output (This is where I need help!!!!)
for (int k = 0; k < myArray.length; k++)
{
if (myArray[k] != 0)
{
System.out.print(k + " occurs " + myArray[k] + " time");
if (myArray[k] > 1)
{
System.out.println("s");
}
else
System.out.println("");
}
}
keyboard.close();
}
}
You are storing the number entered by the user in the array. Instead, you should store a counter in each position of the array for the corresponding integer. When the user inputs a number, you should increase the corresponding counter.
The second part of your code (output results) seems ok. It is the first one that needs fixing.
I think the first for loop should be something like this:
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] += 1;
}
}
}
This should store add 1 to the array everytime the numbers occurs.
hey this my source code that worked out or me.
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// ask for user to input numbers
System.out.println("Enter some integers between 1 and 100 (and 0 when done): ");
int[] myArray = new int[1000];//create a new array for user inputs
int number;//variable for user inputs
int count = 0;
do
{
number = input.nextInt();
myArray[count] = number;
count++;
}
while (number != 0);
int[] mySort = new int [count - 1]; //create a new array with only the numbers
for(int i = 0; i< (count-1); i++) { //get the array until 0th number into new
mySort[i] = myArray[i];
}
java.util.Arrays.sort(mySort);// sort the array in ascending order
int n = 0;
for(int i = 0; i < mySort.length; i++) {//check if the number have checked before
int occurance = 0;
if(n >= mySort[i]) {
continue;
}
else {
n = mySort[i];//if a new number found do the calculation+
for (int j=0; j<mySort.length; j++)
if (n == mySort[j])
occurance++;
System.out.print(n + " occurs " + occurance );
{
if (occurance == 1) {
System.out.println(" time.");
}
else {
System.out.println(" times.");
}
}
}
}
}
}

Java Array get digits and make number from array input

import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]

Possible Workaround for Optimal solution for split function in java while reading multiple lines?

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two or more numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Print Each number in Separate line which can be used further for summation
Input
2
50 100
100 50 105
Output
50
100
100
50
105
Now this is the code that i've written that is Giving me Output
import java.util.Scanner;
import java.util.StringTokenizer;
public class Generation {
public static void main(String[] str) {
Scanner keyboard = new Scanner(System.in);
int inputSize;
do {
System.out.println("Enter the value of T Size");
inputSize = keyboard.nextInt();
keyboard.nextLine();
if (inputSize < 2 || inputSize > 10) {
System.out.println("Not a Valid Input Size");
}
} while (inputSize < 2 || inputSize > 10);
String[] inputValue = new String[inputSize];
int tokenCount = 0;
for (int i = 0; i < inputSize; i++) {
System.out.println("Enter the inputs");
inputValue[i] = keyboard.nextLine();
StringTokenizer strToken = new StringTokenizer(inputValue[i], " ");
tokenCount += strToken.countTokens();
}
keyboard.close();
//suppose this is 2nd part
int[] splitedString = new int[tokenCount];
int tempTokenCount = 0;
for (int i = 0; i < inputSize; i++) {
String[] tempSplitArray = inputValue[i].split(" ");
for (int j = 0; j < tempSplitArray.length; j++) {
splitedString[tempTokenCount] = Integer
.parseInt(tempSplitArray[j]);
tempTokenCount++;
}
}
/*for (String s : inputValue) {
System.out.println(s);
}*/
for (Integer s : splitedString) {
System.out.println(s);
}
}
}
Now my question is how can i optimize the 2nd part where i have to use two for loop which result in O(npower2) time complexity. What is the workaround for such situations ?
You are concerned with performance, and I see you have some knowledge of the issues (taking about power time complexity) but I think you don't really fully understand what this means.
Just because your program has nested loops, doesn't mean it is (much) less efficient than one with a single loop. The outer loop iterates over each line and the inner loop iterates over the tokens (which vary in number) so the total number of iterations is the total number of tokens and has nothing to do with any power law.
The main problems with performance is that you simply have too much code to do a very simple thing and you are using temporary arrays, scanners, parsers which will all add to the overhead of it. You can read a file containing its with the following code:
import java.util.Scanner;
public class Scan {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int i;
while (keyboard.hasNext()) {
try {
i = keyboard.nextInt();
System.out.println(i);
} catch(Exception e) {
// Whatever
System.err.println(e.getMessage());
System.exit(1);
}
}
}
}
This will do most of what your class does and in addition catches exceptions. The only thing it doesn't do is read the initial count of lines. Actually, counting lines is hard in the scanner as it doesn't really support it, but maybe you can do without that or have another solution.

How do I get my value to print every time the loop increments in Java (For Loop)

I need to create a code that prints a pyramid like structure, given the user integer input which will be printed last. (I have attached an image of a final product below). I am new to programming, have been enjoying it, but am stuck in this problem.
My code can currently produce the user input 4 times. So I feel like I am close, just a little bit of tweaking will get the job done
I need my code to print out every single time that the loop increments instead of just displaying the user input a certain amount of times. I converted the integer to a string so that I can show the value x amount of times, but I feel that this is what is throwing me off. If I can somehow get the string to display the values at every incrementation then I will be golden. PLEASE HELP! Below is my code
import java.util.Scanner; //import scanner
public class NumberStack { // class
static Scanner myScanner; //declare scanner
public static void main(String[] args){ //add main method
myScanner= new Scanner (System.in); //scanner input declaration
int input= 0;
while (true) {
System.out.print("Enter an integer between 0 and 9 inclusive: ");
if (!myScanner.hasNextInt()) {
System.out.println("You have not entered an integer");
}
input= myScanner.nextInt();
if ( (input>=0) && (input<=9) ) {
String smln= Integer.toString(input);
String out="";
for (int p=0; p<input; p++) {
for (int j=0; j<input; j++) {
for (int i=0; i<((input*2)-1);i++) {
out += smln;
}
System.out.println(""+out);
out="";
smln= Integer.toString(input);
}
}
} //end of if statement
else {
System.out.println("You have not entered an integer within range");
}
} //end of while loop
} //end of main method
} //end of class
when you are facing problems like this one, you should try to look for a pattern...check this out
int input = 4;
for(int i = 1; i <= input; i++)
{
int times = i;
int length = 2 * i - 1;
String str = "";
for(int j = 0; j < length; j++)
{
str += i;
}
for(int k = 0; k < times; k++)
{
System.out.println(str);
}
}
Since your method is currently printing the data fro a particular number properly eg for input 4 it is printing
4444
4444
4444
4444
I would suggest that extract ur code for display into a separate function. And call that function using the number from a loop.
for(int i=1; i<=num;i++)
function_f1(i);
This should do the trick for you and since you are starting off with coding , it will also give you ideas on using methods.

Categories

Resources