Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently struggling with my first java program.
The question's task was to create a program that prompts the user to enter 5 numbers and store them in an array. Then the array should be printed, after that's done the program prompts the user to enter a number to search. Depending on the number the program should print "(display number) is on the list" or "(display number) is not on the list"
I have been struggling with this for quite a while now not fully understanding the conditional task.
Here is what my code looks like:
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
System.out.println("The sorted numbers are "
+ number1 + ", " + number2 + ", " + number3 + ", " + number4 + ", " + number5);
System.out.println("Enter a number to search: ");
}
I added comments to document what the code was doing. This should hopefully help you grasp the concept.
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
//Create an array of integers to store user input
int[] userNumbers = new int[5];
System.out.print("Enter " userNumbers.length + " numbers: ");
//Goes into a loop, and sets each array index to the user inputted integer
for (int i = 0; i < userNumbers.length; i++) {
userNumbers[i] = input.nextInt();
}
System.out.println("Enter a number you would like to search for");
boolean exists = false;
int numToSearch = input.nextInt();
//for each number in the user numbers array, check to see if that number matches the number to search. If so, set exists = true and break out of the loop to check no further.
for (int num: userNumbers) {
if (numToSearch == num) {
exists = true;
break;
}
}
//if else to decide which output to show the user.
if (exists) {
System.out.println(numToSearch + " is in the list");
} else {
System.out.println(numToSearch + " is not in the list");
}
}
}
At first instead of storing your numbers in single variables, you store them in an array.
The next thing you'll do is use
boolean tmp = false;
int search = input.nextInt();
This will give you the number the user is searching for.
When you have it (the program will wait at the instruction until there's input), you loop over your array and in each iteration you compare it to the given number. You do this by using
if (array[i] == search) {
tmp = true}
With i being your iteration variable.
After the end of the for loop, you'll do another if where you, depending on the state of the tmp variable either print that the number exists or it doesn't.
Sorry for short explanation.
Try following....
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
List<Integer> integers = new ArrayList<Integer>();
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
integers.add(number1);
integers.add(number2);
integers.add(number3);
integers.add(number4);
integers.add(number5);
System.out.println("The sorted numbers are "
+integers);
System.out.println("Enter a number to search: ");
int searchNum = input.nextInt();
if(integers.contains(seacrchNum)){
System.out.println(searchNum+" is on the list");
}else{
System.out.println(searchNum+" is not on the list");
}
}
Explainations :
Placed all the entered numbers into an arrayLists and then prompt for the search Number to be entered. and Check wheather the search number is der in the ArrayLists or not. Based on the condition display the Message
Related
I am having a problem with my java code below. I want the loop to stop when the number "-100" but it stops as soon as you enter any number. I'm just learning how to use java so there could be plenty of mistakes here.
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String num = "";
do {
System.out.println("Enter a number: ");
int n = keyboard.nextInt();
System.out.println("The number you entered is: " +n);
System.out.println("------------------------");
} while ("-100".equals(num));
}
}
num is always the empty string, because you never change the value of num. You update n. Which is what I would base the loop on. Like,
Scanner keyboard = new Scanner(System.in);
int n;
do {
System.out.println("Enter a number: ");
n = keyboard.nextInt();
System.out.println("The number you entered is: " + n);
System.out.println("------------------------");
} while (n != -100);
That is, do loop while n is not -100.
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);
}
}
import java.util.Scanner;
/**
* Created by b00598439 on 30/09/2015.
*/
public class Assessment1 {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
for (int i = 1; i<=2; i=>3; i++){
answer[i] nextInt(); //Get integer entered, if different from 1 or 2, if any other number then quit
}
System.out.println("What size of array would you like?");
int SIZE = in.nextInt(); //What size should the array be?
int [] answer = new int[SIZE]; //Lets user read into the program
System.out.println("The total of the numbers in the program is: " + answer); //Gives total of numbers
System.out.println("The average of the numbers in the program is: " + avg);
int count = 0;
for (int i = 0) ; //Calculating the average
I have been trying to get the code sorted to write to screen and follow on through for the size of the array. I have to get the user to select an option 1, or option 2, if option 1 or 2 isn't chosen then I have to terminate the program. I cannot even get the first part printing or working and this is what I have to do:
1) If the array option is chosen, the program should:
• Ask the user what the size of the array should be
• Let the user read in the numbers into the array
• Output the total of the numbers stored in the array
• Output the average of the numbers stored in the array
I have been sitting here for 4 hours and still getting nowhere
Any help would be appreciated
This can be done in many ways,I have done it in a simple way so you can understand the whole code step by step.By the way,you haven't explained what you want the program to do if option 2 was chosen.You can remove the option 2 by deleting the "case 2:".See the code.
import java.util.Scanner;
public class Assessment1 {
public static void main (String args[]) {
int average,sum=0;
Scanner input = new Scanner(System.in);
Scanner length = new Scanner(System.in);
Scanner option = new Scanner(System.in);
System.out.println("Enter 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
int x=option.nextInt();
switch(x){
case 1:
System.out.println("Input array size: ");
int len=length.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
sum += numbers[i];
}
average=sum/len;
System.out.println("Total sum of all numbers: "+sum);
System.out.println("Average of all numbers: "+average);
case 2:
//insert your "ArrayList code here,you haven't explained what you want here
default:
System.out.println("Program terminated.");
}
}
}
Ok, I developed a little more the code. I put it inside a while loop... it goes back to the beginning and asks to again to enter the options... you enter any number other than 1 or 2 and you get out. I tested it and it works ok in the console. Just a comment.. you are getting the average in integer values... if you would like to get doubles then you have to use doubles and use nextDouble instead of nextInt. Hope that it helps.
import java.util.Scanner;
public class Assessment{
public static void main(String[] args){
// Scanner to get the initial number options
Scanner in = new Scanner(System.in);
// Scanner to get numbers to sum
Scanner numSc = new Scanner(System.in);
// Declaration of variables and array
int answer = 0; //You need int answer, don't need an array by now
int numAnswer;
int sum = 0;
int average;
// Loop the program
while (true){
System.out.println("Enter number 1 for arrays, 2 for arraylists, any other to quit");
// Using in Scanner to test for integer input
if(in.hasNextInt()){
// If there is an integer then give it to numAnswer
numAnswer = in.nextInt();
// What to do if the option is 1, 2 or other number
switch(numAnswer)
{
case 1:
case 2:
answer = numAnswer;
break;
default:
System.exit(0); // Out of the program
}
}
// If answer variable got number 1
if (answer == 1){
// New Scanner to get the size of the array
Scanner sizeSc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
// Getting the size of the array with sizeSc Scanner
int size = sizeSc.nextInt();
// Making a new array with the size of size variable
int[] inputNums = new int[size];
// Looping to get input numbers
for (int i = 0; i < inputNums.length; i++){
System.out.println("Enter a number in the array: ");
//Getting the numbers from console with numSc Scanner
inputNums[i] = numSc.nextInt();
sum += inputNums[i]; //Getting the sum of each number
}
average = (sum/size);
System.out.println("Sum of numbers: " + sum);
System.out.println("Average of numbers: " + average);
System.out.println(" ");
} else {
System.out.println("YOUR CODE TO THE LISTARRAY");
}
}
}
}
import java.util.*;
public class Average {
public static void main(String[] args) {
int count = 0;
int amtOfNums = 0;
int input = 0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
int next = scan.nextInt();
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
}
}
This is supposed to be a Java program that takes integers from the user until a negative integer is entered, then prints the average of the numbers entered (not counting the negative number). This code is not counting the first number I enter. I'm not sure what I'm doing wrong.
Comment out your first input (outside the loop), you called it next.
// int next = scan.nextInt();
That takes one input, and does not add it to count or add one to amtOfNums. But you don't need it.
Write a program that uses a while loop. In each iteration of the loop, prompt the user to enter a number – positive, negative, or zero. Keep a running total of the numbers the user enters and also keep a count of the number of entries the user makes. The program should stop whenever the user enters “q” to quit. When the user has finished, print the grand total and the number of entries the user typed.
I can get this program to work when I enter a number like 0, to terminate the loop. But I have no idea how to get it so that a string stops it.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
int num;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
while (num != 0) {
if (num > 0){
sum += num;
}
if (num < 0){
sum += num;
}
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Your strategy would be to get the input as a string, check to see if it is a "q", and if not convert to number and loop.
(Since this is your project, I am only offering strategy rather than code)
This is the rough strategy:
String line;
line = [use your input method to get a line]
while (!line.trim().equalsIgnoreCase("q")) {
int value = Integer.parseInt(line);
[do your work]
line = [use your input method to get a line]
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
String num;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
while (!num.equals("q")) {
sum += Integer.parseInt(num);
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Cuts down on your code abit and is simple to understand and gives you exactly what you want.
could also add an if statement to check if they entered another random values(so program doesn't crash if the user didn't listen). Something like:
if(isLetter(num.charAt(0))
System.out.println("Not an int, try again");
Would put it right after the while loop, therefore it would already of checked if it was q.
java expects an integer but we should give the same exception. One way to solve this problem is entering a String, so that if the user first pressing is the Q, never enters the cycle, if not the Q. We assume that the user is an expert and will only enter numbers and the Q when you are finished. Within the while we convert the String to number with num.parseInt (String)
Integer num;
String input;
while(!input.equal(q)){
num=num.parseInt(input)
if(num<0)
sum+=1;
else
sumA+=1;
}