Small addition to current code - java

import java.util.Scanner;
public class linecounter {
public static void main(String[] args) {
System.out.print("Enter a line of integers ");
Scanner chopper = new Scanner(System.in);
int x = chopper.nextInt();
while (chopper.hasNextInt()) {
System.out.println(chopper.nextInt());
}
}
}
I am in a CS1 class learning the basics of Java and have a quick question, on this code could anyone tell me how i could get it to keep count of how many integers were typed in?
Thank you

above your while loop, declare:
int count = 0;
then in your while loop use
count++;
This will start you at 0 and every time it increments the count

You could add a counter to the while loop.
int counter = 0;
while (chopper.hasNextInt()) {
counter++;
System.out.println(chopper.nextInt());
}
System.out.println(counter);

In the cases that you have integer numbers, double numbers and you only need count the integer numbers, you can use:
public class linecounter {
public static void main(String[] args) {
System.out.print("Enter a line of integers ");
Scanner chopper = new Scanner(System.in);
int x = chopper.nextInt();
int counter = 0;
while (chopper.hasNextInt()) {
System.out.println(chopper.nextInt());
String myCurrentArg = chopper.nextInt();
if(isInteger(myCurrentArg) ){
counter++;
}
}
System.out.println("The number of integer arguments are: " + counter);
}
public static boolean isInteger(String s) {
return isInteger(s,10);
}
}

Related

Reading a series of numbers from the user until -1 is inputted, Java

I am trying to write a program to read a series of numbers from the user until -1 is entered. It should then print the average (with decimals) of those numbers (not including the -1). This is what I have so far, but it does not seem to work properly whenever I input -1. This is what I have thus far:
import java.util.Scanner;
import java.util.*;
public class Tute1
{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many numbers you want: ");
int numb = sc.nextInt();
int i =0;
int total =0;
while (i <= numb) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer ");
int myChoice=scan.nextInt();
total=total+myChoice;
i=i+1;
if(myChoice == -1) {
System.out.println("The average is "+ (total+1)/numb);
break;
}
}
System.out.println("The average is "+ total/numb);
}
}
Your code seems a bit odd. Here is how I would do it
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int total = 0;
while (true) {
System.out.println("Enter an integer ");
int myChoice = scan.nextInt();
if (myChoice != -1) {
total = total + myChoice;
i += 1;
} else {
break;
}
}
float average = total / i;
System.out.println("The average is " + average);
}
Hope this helps. You can add try-catch and stuff to make it so that user does not exploit this
Few things:
first of all you dont need to create a new scanner as your code inside the while loop. Its because the while loop is inside you function scope so every thing you declare on you function the while loop knows about. (It does not work the other way around)
second your breaking condition should be inside the while loop the if with break is redundant and unnecessary.
third thing you should get rid of numb as its doing nithung
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int numb = sc.nextInt();
int i =0;
int total =0;
while (numb != -1)
{
total=total+numb;
i=i+1;
int numb = sc.nextInt()
}
System.out.println("The average is "+ total/i);
}
}
I think this solution is smaller and more elegant

Using a for loop, display the number of entries and the sum in Java

so I was asked to create a program in which the user enters four integers and then displays the number of entries and the sum of the integers using a for loop. This is what I came up with.
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
for (int i = 0; i != 4 ; i++)
{
System.out.println(" Enter an integer: ");
int num = in.nextInt();
sum = sum + num;
count = count + 1;
}
System.out.println("Number of entries: " + count);
System.out.println("Total sum of entries: " + sum);
}
}
I was wondering what a cleaner way was to ask the user for the four numbers using a for loop, and what other people might suggest be best for this situation. Thanks for any input, p.s. (I have just started learning!)
i think you are looking something like this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum=0;
for(int i=0;i<4;i++){
System.out.println("ENter Number"+(i+1));
sum += sc.nextInt();
}
System.out.println("the Sum is "+sum);
sc.close();
}
You can check with enter. If user presses enter, you can break.
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
break;
}
Have a look at this solution. I cleaned it up a bit. Maybe you will find some design decisions I made which will help you in the future:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int sum = 0;
for (int count = 1; count <= 4; count++) {
System.out.print(String.format("Please enter %d. integer: ", count));
sum = sum + readNumber(scanner);
}
System.out.println("The sum of numbers entered is: " + sum);
}
}
private static int readNumber(Scanner scanner) {
do {
String input = scanner.nextLine();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.print(String.format("Input %s is not a valid integer. Try again: ", input));
}
} while (true);
}
As you're a beginner it's the best way for getting input from the user in console. But you are for the condition should be like:
for ( int i =0;i < 4 ; i ++){}

read multiple inputs from same line in java

Here is my code snippet
public void m1(int a) // a value passed from main
{
for(int i=0;i<a;i++)
{
// Read "a" inputs from the user one by one
}
}
public static void main(String[] args)
{
int a;
// read value of a from user
m1(a)
}
Can U please tell me how to give this input in one line.
Like in the same line we need to provide the value of a and also should take a values from user.
eg:enter code here
a=6. 6 values from user
6 22 33 44 55 66
6 and the 6 inputs from the user should be in the same line (given by the user at the same time).
You could go this way:
public class Number {
static Scanner sc = new Scanner(System.in);
static int arr[];
public static void read(int a)
{
arr = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
}
public static void main(String args[]) {
System.out.print("Enter numbers here : ");
int a = sc.nextInt();
read(a);
// printing the array
for (int i = 0; i < a; i++) {
System.out.print(arr[i]+" ");
}
System.out.println("");
}
}
But better and cleaner way will be returning the array from read method:
public class Number {
static Scanner sc = new Scanner(System.in);
public static int[] read(int a)
{
int arr[] = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
public static void main(String args[]) {
System.out.print("Enter numbers here : ");
int a = sc.nextInt();
int numbers[] = read(a);
// printing the numbers array
for (int i = 0; i < a; i++) {
System.out.print(numbers[i]+" ");
}
System.out.println("");
}
}
Input:
Enter numbers here : 4 1 2 3 4
Output:
1 2 3 4
Solve that your problem? I haven't understand exactly what you want, but with this you can do anything, or not?
public static void m1(String[] a) // a value passed from main
{
for (int i = 1; i < a.length; i++) {
// Read "a" inputs from the user one by one
System.out.println(a[i]);
}
}
public static void main(String[] args) {
m1(args);
}
public static void m1(int a) // a value passed from main
{
Scanner scan = new Scanner(System.in);
int arr[] = new int[a];
for(int i=0;i<a;i++)
{
arr[i]=scan.nextInt();
}
}
public static void main(String[] args)
{
int a=(int) 6.6;
// read value of a from user
m1(a);
}
Input:
1 -2 "nonumber" 34
Output:
1
-2
34
Code:
String line = scanner.nextLine();
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(line);
while (m.find()) {
System.out.println(m.group());
}
First, a couple of quick pointers:
- Name your methods something more practical than m1()
- Make sure you end your statements with a semi-colon ( e.g m1() )
- You need to define m1() as static, or otherwise instantiate the class which contains m1()
- Learn about Scanners and Arrays; you must import a library to use a Scanner object. ( import java.util.Scanner; )
public static void storeIntegers(int a){
//This is how you declare an array.
int[] someIntArray = new int[a];
//You must create a Scanner object to take in user input.
Scanner userInput = new Scanner(System.in);
for(int i = 0; i < a; i++){
someIntArray[i] = userInput.nextInt();
}
// Just to make sure it worked.
for(int e = 0; e < someIntArray.length; e++){
System.out.println(someIntArray[e]);
}
}// End storeIntegers()
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.println("How many numbers?");
int a = userInput.nextInt();
storeIntegers(a);
}// End main()

comparision b/w elements of an array

in this code i want to take no. of testcases by keyboard input and rest is the same problem. only what i am doing is like. if i take 2 test cases then it shud be print the result based on both cases after taking the complete input. For example: INPUT testcases : 2 //case1// 5(no of building) 7 5 2 11 1 //case2// 3(no. of building) 1 2 3 OUTPUT 7//OUTPUT FOR 1ST CASE// 0//OUTPUT FOR 2ND CASE// HOPE, NOW PROBLEM IS CLEAR
import java.util.Scanner;
public class Komal {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("enter the test cases");
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
System.out.println("total no of building");
int n=sc.nextInt();
int ar[]=new int[n];
for(int j=0;j<n;j++)
{
System.out.println("enter the heights");
ar[j]=sc.nextInt();
}
for(int j=1;j<ar.length;j++)
{int sum=0;
if(ar[0]<ar[i])
{
break;
}else
{
sum += (ar[0]-ar[i]);
}
System.out.println(sum);
}
}
}
}
Here is the complete code. Luckily i had my laptop running and this isn't a very difficult program.
public class TillGreater{
public static void main(String args[]){
int[] ar = {5,4,2,7,1};
int sum=0;
for(int i = 1 ; i < ar.length;i++){
if(ar[0]<ar[i]){
break;
}else{
sum = sum + (ar[0]-ar[i]);
}
}
System.out.println(sum);
}
}
try this:
public static int SumUntilBigger(int[] a)
{
int sum=0;
for(int i=1;i<a.length;i++)
{
if(a[i]<=a[0])
sum+=a[0]-a[i];
else
return sum;
}
return sum;//will reach this statement if all the elements are bigger than the first one
}
this compares each element with the first element and when the element is bigger it just return the sum and exits from method, if all elements are bigger than the first one just return the sum of all differences.
you can use it in main like this:
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter the size of the array");
int size=s.nextInt();
int[] a=new int[size];
System.out.println("enter the array values");
for(int i=0;i<size;i++)
a[i]=s.nextInt();
System.out.println("The differences sum : "+SumUntilBigger(a));
}

Create a java program that prompt the user for a positive number and then displays each digit in reverse order on a separate line

import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
output:
Please enter a value:
789
7
8
9
How do I reverse the output? For example, when I enter the number 123, it would display 321 with each digit on a new line.
If the user is inputting values in base 10, you could instead use the modulo operator along with integer division to grab the rightmost values successively in a while loop as so:
import java.util.Scanner;
public class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int quotient = value;
int remainder = 0;
while(quotient != 0){
remainder = quotient%10;
quotient = quotient/10;
System.out.print(remainder);
}
}
}
This might be a better method that attempting to convert the int to a string and then looping through the string character by character.
Loop you printing for loop in the reverse direction:
import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = digit.length()-1; i >= 0; i--) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Edit: No reason to reverse the string itself, ie. using a Stringbuilder like the other answers say. This just adds to the runtime.
import java.util.*;
public class Francis {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Simply reverse the string before looping through it
digit = new StringBuilder(digit).reverse().toString();

Categories

Resources