So I am trying to create a loop that accepts number "0 - 10". If it is less than "0" than the loop exits and the program prints out all the numbers and the number of times each was entered. So Lets say you enter values like 1 2 3 4 5 1 It will print out something like Number:1 Times Entered:2 then next line will print out Number:2 Times Entered:1. If it goes higher than 10 I will just give them an input error. If someone can just help me out creating the correct variables and format I think I can take it from there. Here is what I have thus far... I know it's not correct but this is the idea I am trying to do.
import java.io.*;
public class test {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
Integer[] numbers = new Integer[1000]
int count = 0;
str = input.readLine();
while(str != null){
numbers[count] = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(numbers < 0)
break;
else if(numbers >= 0 || numbers <= 50)
numbers[count]++;
else
System.out.print("You must enter a value less than 51");
} // Close while loop here
System.out.println("Number:" + number + " Times Entered:" + count);
}
}
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
int i,number;
Integer[] numbers = new Integer[10];
int count = 0;
for(i=0;i<10;i++)
numbers[i]=0;
str = input.readLine();
while(str != null){
number = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(number == 0)
break;
else if(number >= 0 && number <= 10)
numbers[number-1]++;
else
System.out.print("You must enter a value less than 11");
str = input.readLine();
} // Close while loop here
for(i=0;i<10;i++)
System.out.println("Number:" + (i+1) + " Times Entered:" + numbers[i]);
}
}
This should work.And put some efforts form your side so that you can learn
Related
I am trying to run while loop for each input user enter but don't know how to stop if user is not entering input.
I need help in stopping while loop if user doesn't enter input.
Code:
import java.util.*;
class petrol{
public static void main(String[] args){
int vehicle_counter=0,petrol_counter=0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
Scanner s1 = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>();
while(true){
if(petrol_counter<=200 && array.size()<50){
int input = s1.nextInt();
petrol_counter=petrol_counter+input;
vehicle_counter++;
array.add(input);
}
else{
System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
break;
}
}
System.out.println("Hii");
}
}
e.g: If I enter 2 3 4 2 and press enter loop should stop.
Problem with possible solution :
If I use while(s1.nextInt().equals(true)) I get an error.
How do I use break?
So, you can try something like this. Instead of Scanner, use BufferedReader to parse the input since all you need is a single line input. Also, BufferedReader is faster compared to Scanner.
Here is the code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Petrol {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vehicle_counter=0,petrol_counter=0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
String input = br.readLine();
String[] values = input.split(" ");
if(values.length>50){
System.out.println("Vehicles exceeded 50");
}else{
for(int i=0;i<values.length;i++){
int ip = Integer.parseInt(values[i]);
petrol_counter+=ip;
vehicle_counter++;
if(petrol_counter>200){
System.out.println("Petrol Quantity exceeded 200L");
}
}
}
System.out.println(petrol_counter+" Litres "+ " Vehicles "+vehicle_counter);
}
}
If you want to keep the Scanner you could also make the input as char and having a if statement that will exit the loop when you press a certain character.
import java.util.*;
public class petrol {
public static void main(String[] args) {
int vehicle_counter = 0, petrol_counter = 0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
Scanner s1 = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>();
while (true) {
if (petrol_counter <= 200 && array.size() < 50) {
char input = s1.next().charAt(0); // use char instead
if (input == 'q' || input == 'Q') { //if user enters q or Q
System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
break;
}
petrol_counter = petrol_counter + input;
vehicle_counter++;
array.add((int) input); //Cast to int
}
}
System.out.println("Hii");
}
}
I have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you
Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).
You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}
(Writing in java)I have two inputs(History, Geography) taken from the console. I can enter the values of History/Geography as any integer and I can do it any number of times I want. When I decide to stop taking console input I need to find out how many History and how many Geography.
I have successfully taken the console inputs.
However, I don't know how my code should store (remember) what all I entered for History and Geography and then spit it out.
Help Please. IN the example below I cannot figure out how to achieve the second part annotated with
console>
Select 1.Subject 2.Subject Count //console message
1 //console input
Which Subject? 1.History 2. Geography //console message
1 //console input
How many History ? //console message
5 //console input
[Another round]
console>
Select 1.Subject 2.Subject Count //console message
2 //console input
5 History // console message
The question you have asked isnt very clear, but from what I understood, this might be of help to you
You could also use a SwitchCase statement here!
import java.io.*;
public class Subject{
public static void main(String[] args)throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
boolean flag = true;
int hist = 0, geog = 0, val = 0;
while(flag){
System.out.println("Enter the number for subject\n1.History\n2.Geography\n -1.Exit");
val = Integer.parseInt(in.readLine());
if(val == 1){
hist ++;
}
else if(val == 2){
geog ++;
}
else if(val == -1){
System.out.print("Total History: ", hist);
System.out.print("Total Geography: ", geog);
flag = false;
continue;
}
else{
System.out.println("invalid option");
continue;
}
}
}
}
/*
int hist[] = new int[100];
int geog[] = new int[100];
int i = 0;
int j = 0
while(true){
//if history
//then do this
hist[i] = i + 1;
i++;
//if geography
//do this
geog[j] = i + 1;
j++
//if user wants to exit
for(int m = 0; m<=i; m++){
//calculate sum like this: Sum += hist[m];
//print sum
}
for(int n = 0; m<=j; n++){
//calculate sum like this: Sum2 += geog[n];
//print Sum2
}
}
*/
Basically what I have to do is read user input in (CUI) until the user presses x. Then display the min,max and average of the numbers the user has entered. I keep getting a InputMismatchException when I press x. I have tried a lot of different ways and that is why I may have some unnecessary code in there.
import java.io.*;
import java.util.Scanner;
import java.lang.Number;
public class taskTwo{
public static void main(String [] args) throws IOException {
int min = 0;
int max = 0;
boolean isX =false;
Scanner input = new Scanner (System.in);
BufferedReader input2 = new BufferedReader (new InputStreamReader (System.in));
String s = "x";
s = input2.readLine();
while(isX == false){
if(s.equals ("x") || s.equals ("X")){
isX = true;
}
int val = input.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
if(isX == true){
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
}
in the while loop you are using nextInt(), obviously it will expect an integer as input. So when you are giving input x which is an string then it will fail.
So in the loop take string as input and if it is not X and is a number then convert it to int values and calculate
s = input2.readLine(); is called outside while loop means only for first line it will check for X and loop can never be ended if fist line is not X or you entered 0.
1.) You don't need two objects reading input. Just input is sufficient.
2.) You can use
input.hasNextInt();
and
input.hasNext();
to check if the input is an int or a string. Something like:
while(true){
if(input.hasNextInt()){
//do something with the integer
}else if(input.hasNext()){
if(input.next().toLowerCase() == "x"){
break;
}
}
}
I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.
System.out.println("Enter a ten digit binary number. Press 'Enter' after each digit. Only use one or zero. :");
binary[0] = keyboard.nextInt();
for (index = 1; index < 10; index++)
binary[index] = keyboard.nextInt();// fill array with 10 binary
// digits from user. User
// must press 'Enter' after
// each digit.
Try this:
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext())
{
final String input = scanner.next();
try
{
int num = Integer.parseInt(input, 2);
}
catch (NumberFormatException error)
{
System.out.println(input + " is not a binary number.");
//OR You may exit here, if you don't want to continue
}
}
Try this code part :
import java.util.Scanner;
public class InputTest
{
public static void main(String... args) throws Exception
{
Scanner scan = new Scanner(System.in);
int[] binary = new int[10];
for (int index = 0; index < 10; index++)
{
int number = scan.nextInt();
if (number == 0 || number == 1)
{
binary[index] = number;
System.out.println("Index : " + index);
}
else
System.exit(0);
}
}
}