array while loop output Java - 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();

Related

What is the best way to read user inputs via scanner?

I use some approaches similar to the following one in Java:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a= new int[3];
//assign inputs
for (int i=0;i<3;i++)
a[i] = scan.nextInt();
scan.close();
//print inputs
for(int j=0;j<3;j++)
System.out.println(a[j]);
}
However, generally the first input parameter is length and for this reason I use an extra counter (c) in order to distinguish the first element. When using this approach, the scanner does not read inputs one by one and checking the first and other elements in two blocks seems to be redundant.
// input format: size of 3 and these elements (4, 5, 6)
// 3
// 4 5 6
public static void getInput() {
int n = 0; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//block I: check the first element (size of array) and assign it
if (scan.nextInt() <= 0)
System.out.println("n value must be greater than 0");
else {
n = scan.nextInt();
array = new int[n];
}
System.out.println("Enter array elements:");
//block II: check the other elements adn assign them
while(scan.hasNextInt() && c<n) {
if (scan.nextInt() >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c] = scan.nextInt();
c++;
}
}
scan.close();
int sum = 0;
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
My question is "how can I modify this approach with a single block (while and for loop inside while)? I tried 5-6 different variations but none of them works properly?"
Hope this helps,
public static void getInput() {
int n; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//check the first element (size of array) and assign it
n = scan.nextInt();
while(n <= 0)
{
System.out.println("n value must be greater than 0");
System.out.println("Enter size:");
n = scan.nextInt();
}
array = new int[n];
System.out.println("Enter array elements:");
// check the other elements and assign them
while(c<n) {
int num = scan.nextInt();
if (num >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c++] = num;
}
}
scan.close();
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
Output:
Enter size:
-1
n value must be greater than 0
Enter size:
4
Enter array elements:
1
2
3
4
Sum = 10
I've optimized your code and fixed some bug.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
int n = scan.nextInt();
if (n <= 0) {
System.out.println("n value must be greater than 0");
return; // need to break from here
}
int c = 0;
int sum = 0; // no need for array
System.out.println("Enter array elements:");
// check the other elements and assign them
while (c++ < n) {
int next = scan.nextInt();
if (next >= 100) {
System.out.println("Array elements must be lower than 100");
c--; // ensure can reenter the number
} else {
sum += next;
}
}
scan.close();
System.out.println("Sum = " + sum);
}

How to find the random index in an array?

Create 8 randomly generated integer values between 1 to 50. DONE
Display the series of values on screen. DONE
Users has to enter value. Find index & display.
if value cannot be found, display -none.
This is pretty easy. As you already completed step 1 and 2 you just have to ask the user for an input, search your array and output the index, if the input matches a value in the array.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int[] numbers = new int[8];
for(int i = 0; i < 8; i++) {
numbers[i] = random.nextInt(50) + 1;
System.out.print(numbers[i] + ", ");
}
System.out.print("\nInput value: ");
int input = scanner.nextInt();
boolean found = false;
for(int i = 0; i < numbers.length; i++) {
if(input == numbers[i]) {
System.out.println("Index: " + i);
found = true;
}
}
if(!found) {
System.out.println("none");
}
}

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.

Inputting integers in to an array Error?

The purpose of my code is to display the student number and their respective grade as follows:
Student Grade
1 53
2 45
So on...
I used a 5x2 array, in which the user can input the values for the grade...
However I run in to a problem, when inputting the grades, for some reason I have to input 3 values, out of all the 3 inputted values only the 3rd is considered.
My problems:
(1) Why is it that I am even able to enter 3 values per student (Should only be able to input 1 value per student).
(2) Why is it the 3rd value that is being considered?
Here is my code:
import java.util.*;
public class practice {
public static void main(String[] args) {
int[][] studentGrade = new int[5][2];
for(int i = 0; i<5; i++) {
studentGrade[i][0] = i+1;
}
for(int j = 0; j<5; j++) {
System.out.printf("Student %s: ", j+1);
Scanner input = new Scanner(System.in);
if(input.nextInt()>=0 && input.nextInt()<=100) {
studentGrade[j][1] = input.nextInt();
}
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j);
}
}
System.out.print("\nStudent \t Grade");
for(int s=0; s<5; s++) {
System.out.print("\n" + studentGrade[s][0] +"\t" + "\t " + studentGrade[s][1]);
}
}
}
input.nextInt() consumes the next integer in the stream.
You need to do this:
Scanner input = new Scanner (System.in);
for (int j = 0; j < 5; j++) {
System.out.printf("Student %s: ", j+1);
int num = input.nextInt();
if (num >= 0 && num <= 100)
studentGrade[j][1] = num;
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j+1);
}
}
This will make it so that you read the number being input only once, and then you use that number when checking boundaries and then setting the grade.

Taking User Input for an Array

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Categories