Java adding issue - java

I have an issue with my java program displaying every number it is adding, what can I do so that it only displays the total. I am guessing since I have "element" in the last part of the code it showing every single addition: Here is what I have written:
import java.util.Scanner;
public class SomeClass {
public static void main(String[]args){
int ans = 0;
int num;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many integers do you have? (Max 20)");
int x= keyboard.nextInt();
int [] element = new int[x];
for(int subscript = 0; subscript < element.length; subscript++){
System.out.println("Enter element for subscript " + (subscript));
element[subscript] = keyboard.nextInt();
}
System.out.println("Here are all of those numbers");
for(int subscript = 0; subscript < element.length; subscript++){
num = element[subscript];
System.out.println(num);
}
for (int i = 0; i < element.length; i++){
ans += element[i];
System.out.println("The sum of these numbers is " + ans);
}
}
}

//previous lines of code
for (int i = 0; i < element.length; i++){
ans += element[i];
}
System.out.println("The sum of these numbers is " + ans);
//code follows

Because You print out the 'num' as many as length of element. You have to delete that line if your intention is to show only the summed ans which is result of sumation. If you wanna show inputs then its fine
Also
Take this sentence out of the for loop
System.out.println("The sum of these numbers is " + ans);
Everytime for loops working, that line works too. So make it works once after you add all the numbers with for loop.

Related

Java is printing last number using array method, by ignoring other numbers

I'm trying to let my code print numbers I put in output but using array method.
package pkg11;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
for (int z = 1; z <= b; z++) {
System.out.println("Input your" + " " + z + " " + "number");
x = in.nextInt();
}
System.out.println();
int[] a = new int[x];;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
The problem is when it's printing it only prints the last value, for example, I put that I want to put 3 numbers, the first was 1 the second was 2 the third was 3, it prints the third without putting the first 2.
Have a close look at the following code fragment of yours and try to spot the error:
for (int z = 1; z <= b ; z++) {
System.out.println("Input your" +" " +z +" " +"number");
x = in.nextInt();
}
// here you create the array
int [] a = new int [x];
If you didnt spot it: You create the array you want to save each integer in after you have read all values from the console. There is no way you can store the users input in the array, since it is not known at that time.
Then, what did you actually do?
You used the same variable x all the time x = in.nextInt();, overriding each input.
What can i do to solve the problem?
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
int[] a = new int[b];
for (int z = 0; z < b; z++) {
System.out.println("Input your" + " " + (z + 1) + " " + "number");
a[z] = in.nextInt();
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
First, declare int[] a = new int[b]; before you read the values and assign each input the the array with a[z] = in.nextInt();. Also, i modified your loop index a little bit to make things easier.
Ok, what else can i do?
Apart from the user entering non numbers, this code is a little bit more bullet-proof! If you are looking for even more, you can use in.nextLine() and Integer.valueOf() to prevent the user from entering strings instead of numbers.
Scanner in = new Scanner(System.in);
int amountOfNumers;
System.out.println("How many number do you want to put? Amount: ");
amountOfNumers = in.nextInt();
while (amountOfNumers < 1) {
System.out.println("Please enter a number greater than one:");
amountOfNumers = in.nextInt();
}
int[] numbers = new int[amountOfNumers];
for (int i = 0; i < amountOfNumers; i++) {
System.out.println("Input your " + (i + 1) + " number: ");
numbers[i] = in.nextInt();
}
System.out.println("Your numbers are:");
Arrays.stream(numbers).forEach(System.out::println);

About saving and printing distinct numbers in an array

before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.

array while loop output Java

Ok, i got this working while loop that lets the user insert random numbers, if the number is 0 or if the loops length has been achieved then it will stop, now i have to output all the numbers that was inputed and the amount of the inputs (example 1, 2, 3 amount = 3). How do i output the array? i only get 0 from the println.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0 || a1[i] == a1.length){
break;
}else{
tal += a1[i];
}
}//End of while
System.out.println("The inserted numbers are are: " + a1[i]);
}//
First of all, store tal in array and increment i every time you store. Finally iterate through array to print elements entered
import java.util.Scanner;
public class Tset {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0||i>=100){
break;
}else{
a1[i]=tal;
i++;
}
}//End of while
System.out.println("The inserted numbers are are: ");
for(int j=0;j<i;j++){
System.out.println(a1[j]+"\t");
}
System.out.println("amount is: " +i);
}//
}
Use an ArrayList instead of an array to collect the number input and then iterate over it to print them use its built-in lenght method to output the amount
I am not sure what you are trying to do, but this might help.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a1 = new int[100];
int i = 0;
int tal = 0;
int tmp;
do {
System.out.println("Insert number (0-end):");
tmp = scan.nextInt();
a1[i] = tmp;
tal += a1[i++];
} while (tmp != 0 && i < a1.length);
System.out.println("The inserted numbers are : ");
for (int j = 0; j < i-1; j++) {
if (j == i-2) {
System.out.print(a1[j] + ".");
} else {
System.out.print(a1[j] + ", ");
}
}
System.out.println("The sum is : " + tal);
}
Couple of issues:
You may want to put element you read into array like a1[i] = scan.nextInt(); and initializing tal as 0 and using a1[i] in if condition instead of tal.
You are not incrementing value of i and end's up overwriting the previous value.
Once you come out of loop, you just print 0th value of array which i think you entered 0 and came out of loop.
You can over come these as below:
Just after tal += a1[i]; increment value of i as:
i++;
Now to print your element, use a loop like:
System.out.print("The inserted numbers are are:");
for (int j=0; j<i; j++) {
System.out.print(" " + a1[j]);
}
System.out.println();

Create an array based on a range of values given by the user

What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}

Min value of array returns as 0

I'm having problems figuring out why returns for my minimum value in my array keep ending up as 0. I've checked several questions with the same problem but can't use those solutions because my array is being created in one method and my min/max values are calculated in another method.
Is there anyway I can keep my min/max value in a separate method and still get a non-zero answer for my min value? Also, there is more code in the processSalesReport method but I left it out because it was irrelevant. Thanks ahead of time!
import java.util.Arrays;
import java.util.Scanner;
public class CarSalesReport {
int sum;
int count = 0;
int[] num = new int[1500];
String ans = "";
Scanner userInput = new Scanner(System.in);
public CarSalesReport(Scanner input) {
String regex = "\\d+|done";
System.out.println("Type sales (type \"done\" when finished)");
do{
System.out.print("Sale Number " + (count + 1) + ": ");
ans = userInput.nextLine();
while(!ans.matches(regex)){
System.out.println("Please enter a positive number");
ans = userInput.nextLine();
}
if(!ans.equalsIgnoreCase("done")){
int ans1 = Integer.parseInt(ans);
num[count] = ans1;
count++;
}
}while(!ans.equalsIgnoreCase("done"));
}
public void processSalesReport(){
int max = num[0];
for(int a=0;a<num.length;a++){
if(max<num[a]){
max=num[a];
}
}
//This is where I'm having my problems.
int min = Integer.MAX_VALUE;
for(int a=1;a<num.length;a++){
if(min>num[a]){
min=num[a];
}
}
Arrays.sort(num);
System.out.println("\nMaximum sale: $" + max);
System.out.println("\nMinimum sale: $" + min);
}
}
It's because you've got 1500 entries in your array, which are all initialised to 0. You're iterating through all of them trying to find the minimum, instead of just iterating through the ones you've explicitly populated.
In the loop where you calculate the minimum, change
for (int a = 1; a < num.length; a++) {
to
for (int a = 0; a < count; a++) {
so that you only look at the entries that you've populated.

Categories