Java Array get digits and make number from array input - java

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]

Related

I was writing a code to enter a number and then reversing it, but the modulo isn't working it seems. What could have gone wrong here?

My concern is only with why the modulo (%) isn't working. Please don't comment on the code on it's entirety. My code is as displayed below.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a number");
int num = scanner.nextInt();
int count = 0;
while(num!=0) {
num = num/10;
count++;
}
System.out.println("Total digits = " + count );
int rem = num % 10;
System.out.println(rem);
}}
The output is
Also quick note: the output for "rem" is 0 only when "num" is passed as an operand. If a number replaces the "num" then the code works just fine
There is a wrong logic used for reversing the number. You can try below code.
public class ReverseNumberExample1
{
public static void main(String[] args)
{
int number = 987654, reverse = 0;
while(number != 0)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number/10;
}
System.out.println("The reverse of the given number is: " + reverse);
}
}

How to read multiple inputs on same line in Java?

So I'm trying to read all the input from one line, using scanner, then take the values and find the second largest. I would use an array BUT I am not allowed. You are supposed to enter 10 integers, hit enter and evaluate them.
Something like this:
10 20 30 40 50 60 70 80 90 100 ENTER
Second highest number is: 90
I can't manage to solve it at all. It should be easy but I have no idea.
public class SecondLargest {
public static void main(String[] args) {
{
int largest = 0;
int secondLargest = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter integers: ");
int numbers = sc.nextInt();
largest = numbers;
while (sc.hasNextInt()) {
if (numbers > largest) {
secondLargest = largest;
largest = numbers;
} else if (numbers > secondLargest) {
secondLargest = numbers;
}
}
System.out.println("Second largest number is: " + secondLargest);
sc.close();
}
}
Start with assigning the first scanned integer to largest and secondLargest variables and then process the remaining nine integers in a loop as follows:
num = sc.nextInt();
if (num > largest) {
secondLargest = largest;
largest = num;
}
Demo:
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 10 integers separated by single spaces: ");
// Scan the first integer and assign it to largest and secondLargest
int num = sc.nextInt();
int largest = num;
int secondLargest = largest;
// Input 9 more integers
for (int i = 1; i < 10; i++) {
num = sc.nextInt();
if (num > largest) {
secondLargest = largest;
largest = num;
}
}
System.out.println("The second largest number is: " + secondLargest);
}
}
A sample run:
Enter 10 integers separated by single spaces: 10 23 4 12 80 45 78 90 105 7
The second largest number is: 90
Note: This is just a sample program assuming that the input is in the correct format. I leave it to you to work on how to deal with the wrong input. It will be a good exercise for you.
/*
**In this code I've used BufferedReader class which is faster than Scanner
Class as well as have large buffer of 8KB while Scanner has only 1KB.**
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Second_Highest {
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] s=br.readLine().split(" ");
int a[]=new int[10];
int max=Integer.parseInt(s[0]);
for(int i=0;i<10;i++)
{
a[i]=Integer.parseInt(s[i]);
if(a[i]>max)
{
max=a[i];
}
}
int secondmax=Integer.parseInt(s[0]);
for(int i=0;i<10;i++)
{
if(a[i]>secondmax && a[i]<max)
{
secondmax=a[i];
}
}
System.out.print(secondmax);
}
}
To read single line input, You can do this simply by eating the (\n) which is new line in Java.
Input : 1 2 3
\\Create the object of Scanner Class
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
// this will eat the new line and move forward for other inputs.
sc.nextLine()
To read in a loop or to store at 2D array.
Input :
1 2 3
3 4 5
6 7 8
//... do the above declaration of array
for ( int i = 0; i < n; i++){
for( int j = 0; j < m; j++){
arr[i][j] = sc.nextInt()
}
sc.nextLine(); // you need to eat the \n here.
}
This will work perfectly.
Now you should be able to get the input easily in a single line.
Below snippet can be used to take multiple Integer Input on same line.
Scanner sc= new Scanner(System.in); // Declare and Initialize Scanner
while(sc.hasNext()) // While the input has data execute
System.out.println(sc.nextInt()); // nextInt() method is used to take Integer data
For Multiple String input on same line separated by white space or a comma,
we can use the following snippet
Scanner sc = new Scanner(System.in).useDelimiter("[,\\s+]");
import java.util.*;
public class m1{
public static void main(String args[]){
Scannerscan = new Scanner(System.in);
Stringnum = scan.nextLine();
String[] strs = num.split("\\s+");
int[] arrs = new int[strs.length];
for(inti=0;i<strs.length;i++)
{
String stringnum = strs[i];
arrs[i] = Integer.parseInt(stringnum);
if(arrs[i]%2==0){
System.out.print(" ");
}
else{
System.out.print(arrs[i]);
}
}
scan.close();
}
}

How to use a loop where integers are inputted?

I'm working on a question and I'm new to programming, so I'm not that familiar with a few concepts. The question asks the user to input an initial number, followed by a list of that many numbers. The program should then print back how many of the numbers entered were negative.
For example, I first input 5, followed by 5 other random numbers.
5
6,-9,28,-32,-1
The output should be
3
So far all I have is:
class main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++)
{
System.out.println(i);
if(i<0)
{
c++;
}
}
System.out.println(c);
}
}
I'm really confused. Can someone offer an explanation as to how the code works?
You can read the positive integers inside for loop from the given inputs and then check if that each input integer is greater than or equal to zero:
scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++) {
int num = scan.nextInt();
if(num>=0)
{
System.out.println(num);
}
}

Java using a while loop to load user input into an array

I was wondering how to load up an array (with user input) using a while loop. The code below prints a 0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int n = 0;
int[] myArray = new int[10];
System.out.printf("enter a value>>");
while (scan.nextInt() > 0) {
for (i = 0; i > 0; i++) {
myArray[i] = scan.nextInt();
}
System.out.printf("enter a value>>");
}
System.out.printf("array index 2 is %d", myArray[2]);
}
There are multiple things wrong with your code:
First of all
while(scan.nextInt() > 0){
Scanner.nextInt() returns an int from your standard input so you actually have to pick up that value. You are checking here what the user typed but then not using it at all and storing the next thing that the user types by saying:
myArray[i] = scan.nextInt();
You don't really need the outer while loop, just use the for loop, its enough.
However, your for loop is off as well:
for(i = 0; i > 0; i++){
It starts at i equal to 0 and runs while i is greater than 0. This means it will never actually run the code within the loop because 0 is never greater than 0. And if it did run (you started it at some number < 0), you would end up in an infinite loop because your condition i > 0 is always true for positive numbers.
Change the loop to:
for(i = 0; i < 10; i++){
Now, your loop could look like:
for(i = 0; i < 10; i++){ // do this 10 times
System.out.printf("enter a value>>"); // print a statement to the screen
myArray[i] = scan.nextInt(); // read an integer from the user and store it into the array
}
one other way to do it
Scanner scan = new Scanner(System.in);
List list = new ArrayList();
while(true){
System.out.println("Enter a value to store in list");
list.add(scan.nextInt());
System.out.println("Enter more value y to continue or enter n to exit");
Scanner s = new Scanner(System.in);
String ans = s.nextLine();
if(ans.equals("n"))
break;
}
System.out.println(list);
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
int[] arr=new int[4];
int i;
for(i=0;i<4;i++)
{
System.out.println("Enter the number: ");
arr[i]=input.nextInt();
}
for(i=0;i<4;i++)
{
System.out.println(arr[i]);
}
}
Hope this code helps.

I need to find specific variables that the user has inputted however I don't comprehend how

Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}

Categories

Resources