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);
}
}
Related
Given two numbers a and b, find kth digit from right of a^b?
Link for the problem:
http://www.practice.geeksforgeeks.org/problem-page.php?pid=302
MyApproach:
I took 4 numbers as Input.First was the number of test cases.Then,Input was numbers a b and k respectively(Seperated by space).I calculated a^b and then from right searched each number till the time kth digit is not equal to the count.If I get them equal I returned the remainder expected.
Below is the Code:
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
System.out.print(" ");
int b=sc.nextInt();
System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
GeeksId Output:
Wrong !! Here your code Failed
Input:
7 6 3
And its Correct output is:
6
Eclipse ID:
Input:
7 6 3
Output
6
Wny I am getting Failed on geeksId?Is my solution do not produce correct output?
It seems like you did not follow the direction of the problem. The problem gives you a few constraints. you do not do a check for those. You should add the code to check that, so it will make sure you do not run into any exceptions.
I wanted to point out that you can just convert the Math.pow(a,b) result to string, and print the length - k char using the charAt function. This will make it very easy. and gets rid of the loops.
Code for that part is:
String tempString = String.valueOf(result);
System.out.println(tempString.charAt(tempString.length() - k));
Hope this puts you in the right direction.
Can also be done this way without much String operations and not expecting the intermediate output a^b to store in long data type,
private void handle() {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for(int i = 0; i < T; i++) {
findKthDigit(scanner);
}
scanner.close();
}
private void findKthDigit(Scanner scanner) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int k = scanner.nextInt();
System.out.println((int)((Math.pow(a, b) % Math.pow(10, k))
/ Math.pow(10, k-1)));
}
As requested, your program is modified to make it work in GFG system,
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
//System.out.print(" ");
int b=sc.nextInt();
// System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
Hope this helps to understand. (however, you need to check other related exceptions for a good programming practice)
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]
I'm new with java and i have to write a code that asks the user two numbers an interval. Then the user must introduce n numbers and the program must return how many numbers belong to that interval.
I've tried to do this and this is what i have:
import java.util.*;
public class NumsInter {
public static void main(String[] args) {
Scanner sc;
int a,b,nums,count;
sc = new Scanner (System.in);
System.out.print ("Write two numbers a and b(a<=b)(interval): ");
a=sc.nextInt();
b=sc.nextInt();
count=0;
System.out.println("write a number: ");
while(sc.hasNextInt()){
nums=sc.nextInt();
if (a<=nums && nums>=b){
count= count + 1;
} else {
count= count;
}
}
System.out.println(count +" numbers are included in ("+a+","+b+")");
}
}
Example: If the user writes 2 and 6, and then 4,4,3,1 the output should be 3.
As I am a newbie i don't know how can i do this the good way, can someoen help?
PD: How can i break the loop so i can get the output?
Thank You!
Try something like this
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter the numbers you want to test, enter 'stop' to stop");
boolean userInput = true;
while(input.hasNextInt() && userInput){
if(input.hasNext("stop")){userInput = false;}
numbers.add(input.nextInt());
}
Where you have a loop that checks if there is a next int while at the same time checking to see if the user is done or not.
And them something like this to print your answer
for(int i =0; i < numbers.size(); i++){
testNum = numbers.get(i);
if(testNum > lowerLimit && testNum < upperLimit){
count++;
}
}
System.out.println(count + " valid numbers have been entered!");
take an int [] no_between_max&min after take the input from user and store in this array. after that take a for loop and compare the value of array with max and min ant increase the count variable.
int noOfItem=sc.nextInt();
int [] no_between_max_min = new int[noOfItem];
for(int i=0;i<noOfItem;i++){
no_between_max_min[i]=sc.nextInt();
}
for(int i=0;i<no_between_max_min.length;i++){
if(no_between_max_min[i]>=a&&no_between_max_min[i]<=b){
count++;
}
}
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 came across this problem whereas user need to enter a certain series of number in one input, then the program will output back the number one by one. For example, the user entered 4 6 8, then the program will output 4 6 8 to the user.
The code that i have done is like this :
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int N;
String num;
Scanner in = new Scanner(System.in);
System.out.println("Enter number:");
num = in.nextLine();
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int x = 0; x < num.length(); x++)
{
char c = num.charAt(x);
if(Character.getNumericValue(c) >= 0 ){
numbers.add(Character.getNumericValue(c));
}
}
for(int n=0; n<numbers.size(); n++){
System.out.println(numbers.get(n));
}
}
}
But i think it is not really efficient as it is quite long for just doing a simple task. So, could you suggest anything that is much simpler? Thanks!
If all the numbers are in one line then this can solve the problem:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] tokens = reader.readLine().split(" ");
for (int i = 0; i < tokens.length; i++)
System.out.println(Integer.parseInt(tokens[i]));
See BufferedReader for more info.
Set delimitter on Scanner and read each number a int
Scanner in = new Scanner(System.in);
in.useDelimiter("\\s");
System.out.println("Enter number:");
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (in.hasNextInt()) {
numbers.add(in.nextInt());
}
Here's my idea:
String num = "4 6 8"; // user's input
System.out.println(num.replaceAll("\\s+", "\n"));
4
6
8
If you want to ignore everything except the numbers you can use "[^\\d]+" instead of "\\s+".