How can i make this output easier? - java

The problem I am having is I have to input 50 integers, and when I hit space it won't recognize the number and when I hit enter then my output box is very very long for just 1 digit #'s
static final int MAX = 50;
public static void main(String[] args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("This program will count the number of people "
+ "and how many of that age group cameto the college fair.");
System.out.println("**********************************************************");
System.out.println("Please enter the integer value data:");
int [] peopleTypes = new int[MAX];
Scanner keyboard = new Scanner(System.in);
for(index=0; index<MAX; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
System.out.println("The number of infants that were at the college fair was: " + infants);
System.out.println("The number of children that were at the college fair was: " + children);
System.out.println("The number of teenagers that were at the college fair was: " + teens);
System.out.println("The number of adults that were at the college fair was: " + adults);

Try to use this:
public class ScannerDelimiter {
public static void main(String[] args) {
Scanner scanner = new Scanner("12, 42, 78, 99, 42");
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
} /* Output:
12
42
78
99
42
In this case the delimiter is
<any number of spaces or tabs>,<any number of spaces or tabs>

You could read your input as a String and try to parse it:
String s = "";
int i = 0;
for (index = 0; index < MAX; index++) {
s = keyboard.next();
try {
i = Integer.valueOf(s.trim());
} catch (NumberFormatException nfe) {
// log exception if needed
System.out.println(s + " is not a valid integer.");
continue;
}
// do the rest
peopleTypes[index] = i;
//...
}

Console input in Java is line buffered. You won't get anything until the user hits enter. Hitting space, just adds a space to the line you will get. Note: hitting backspace deletes a character which you won't see either.

Related

I'm having issue with the output with this particular code

This is the code:
import java.util.Scanner;
public class javapractice {
public static void main(String[] Args) {
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number :");
int number = input.nextInt();
boolean nextint = input.hasNextInt();
if (nextint) {
count++;
XX += number;
} else {
break;
}
input.nextLine();
}
int YY = XX/count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
}
}
I want the output to print the sum of the numbers entered and when I enter let's say a word like "Hello", it breaks out of the loop and prints Sum 0 0 and AVG = 0.
The issue I'm having is that whenever I enter the number, it asks me for it two times and doesn't take the next number in the row after that and whenever I enter a string variable lets say "I", it outputs Inputmismatch. What would be the fix to this?
Don't mix nextLine() and all the other next methods; pick one. If you want to read a line's worth of text, just call next(), but if you want the input to flow as 'everytime a user hits enter, read another token', which you usually do, update the definition of 'what defines a token?': scanner.useDelimiter("\r?\n");.
Try this code:
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number: ");
if (input.hasNextInt()) {
count++;
XX += input.nextInt();
} else {
break;
}
}
int YY = XX / count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();

How to write Java statement to display integers between 2 numbers?

I am new to java coding. I have written the code below to the problem: How can I write a statement that can be used in a Java program to read two integers and display the number of integers that lie between them, including the integers themselves?
I couldn't run it in Eclipse. When I try to run it through Eclipse, it tells me "The selection cannot be launched, and there are no recent launches. Anyway, can someone please tell me if this code correct? Are there any errors in it?
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
}
}
Please put some more effort on your query, for sure you can come up with your answers by yourself and you will learn faster. For now You can refer to below answer.
package com.barnwal.jeetendra.learn;
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
System.out.println("How many integers are between " + first + " and "
+ second + "???");
// To print number of integer between entered number
if (second > first) {
System.out.println("Answer : " + (second - first - 1));
// To print the numbers
for (int i = first + 1; i < second; i++)
System.out.print(i + " ");
} else {
// To print number of integer between entered number
System.out.println("Answer : " + (first - second - 1));
// To print the numbers
for (int i = second + 1; i < first; i++)
System.out.print(i + " ");
}
}
}
To avoid the unnecessary if-else statement to look which value is bigger, you can also use the functionality of the class java.lang.Math like this
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
int small = Math.min(first, second) ;
int big = Math.max(first, second);
System.out.println("How many integers are between " + small + " and " + big + "???");
System.out.println("Answer : " + (big - small + 1));
// To print the numbers
for (int i = small; i <= big; i++)
System.out.print(i + " ");
You can use looping like this:
if (first > second){
big = first;
small = second;
}
else if (second > first){
big = second;
small = first;
}
for (int i = small; i <= big; i++)
System.out.print(i + " ");
first of all, when you use resources (System.in) you should close them. You can do it with try-finally or you can use try-with-resources.
Here is your code:
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
try (Scanner s = new Scanner(System.in)){
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
if (first != second)
System.out.println("Answer: " + Math.abs(first-second - 1));
else
System.out.println("Answer: 0");
}
}
}
How about this:
int diff = second - first - 1;
let secont = 25 and first = 23 so the output will be:
25-23-1 = 1;
which is 24

Having trouble converting a character value to an integer value

import java.util.Scanner;
public class baseConverter {
//Main method
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String input = "";
System.out.println("What number base would you like to convert?");
int base = keyboard.nextInt();
//Checking if the base is between 2 and 9, inclusive
if (base >= 2 && base <=9){
System.out.println("Please enter a base " + base + " number:");
}else{
System.out.println("Please enter a base from 2 to 9");
}
input = keyboard.next();
int converted = compute(input, base);
System.out.println("The base-10 conversion of that number is " + converted);
}
//Where all the conversion will take place
public static int compute(String userString, int userBase){
int n = userString.length(), output = 0;
int[] num = new int[n];
//The for loop that does all the computing
for (int i = 1; i <= n; i++){
//assigning values to the array indeces
num[i-1] = Integer.parseInt(String.valueOf(userString.charAt(i-1)));
if(num[i-1] != 0){
output = output + ((userBase ^ (n-i)) * (num[i-1]-1));
}else{
output = output;
}
}
System.out.println("User base is " + userBase+ ". n is "+ n);
return output;
}
}
When I run this and input the base and 3 and the input as 2, it seems to convert the value '2' to it's ASCII value of 50 when storing it in the num array. I guess my question is if there is any way that I could work around this or what an entirely different way of getting the value from the string stored as an integer.

Creating a java program that takes user input for an array and then using my own number and multiplying it by each day

Essentially, I am asking the user for an input of how manys days they would like something to happen (array). Once the user inputs that amount, I must make it to where it will display the number 1 for the first number they inputed and then have a set way of multipying each number after by 2. What I am having a hard time understanding is how I can correlate the user input array to the exact amount of the array I am going to create. My code so far.
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
int[] daysOfRice = new int[num];
for (int i = 0; i < daysOfRice.length; i++) {
System.out.println(daysOfRice);
}
System.out.print(daysOfRice);
I am not sure what exactly is your requirement, have a look:
public class TestC {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
keyboard.close();
int[] daysOfRice = new int[num];
int prod = 1;
for (int i = 1; i <= daysOfRice.length; i++) {
if (i == 1) {
prod = 1;
} else {
prod = prod * 2;
}
System.out.println("Day " + i + ": " + prod
+ " grains of rice are given");
}
}
}

Counting occurrences of integers in an array program java

I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}

Categories