How To End Program If User Enters Certain Value
Oct 28, 2014In my computer science project the program has to end if the user enters 0 as his choice from a menu given to him, so how would I go about ending the program.
View RepliesIn my computer science project the program has to end if the user enters 0 as his choice from a menu given to him, so how would I go about ending the program.
View RepliesMy question is how can I make the program repeat until the user enters the number 4 to exit?
/**
* Write an application for a furniture company; the program determines the price of a table. Ask the user to choose 1 for pine, 2 for oak, or 3 for mahogany. The output is the name of the wood chosen as well as the price of the table. Pine table cost $100, oak tables cost $225, and mahogany table cost $310. Also ask the user to specify a
(1) large table or a
(2) small table.
Add $35 to the price of any large table and add nothing to the price for a small table. Display the output. Your program must repeat until the user chooses to exit.
*/
import java.util.Scanner;
public class Wood {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println ("Table Prices");
[Code] .....
In my cs class, we have to write a program that throws an exception if the user enters a negative number, the program should prompt the user to enter only positive numbers and then let them retype the number. But everytime I throw an exception, my program gets suspended.
What am I doing wrong, or is there no way to continue a program if an exception is thrown? Does the program automatically get suspended when an exception is thrown?
try{
do
{
N = kb.nextDouble();
if(N<0) {
throw new NegativeArraySizeException();
}
else
j++;
}
while(j==0);
fill.size(N);
}
catch(NegativeArraySizeException e) {
System.out.println("The number you entered must be positive. Please try again.");
}
import java.util.Scanner;
public class Project_5
{
public static void main (String[] args)
{
Scanner input= new Scanner (System.in);
[code]....
So I'm attempting to have this program take the users input of integers, pressing enter in between each one. If they enter a negative number it lets them know that its invalid. At the end of the program it takes all of the valid integers entered and must add them and average them. I've put the final println in there as a placeholder. If the user types in "6" then presses enter and types in "3" , the output is:
There were 3 valid numbers entered.
The sum of the valid numbers was --- and the average was ---.
There were 0 invalid numbers entered.
It then continues on allowing the user to enter more values. Here is the example output for correct code"
Enter a positive value (EOF to quit): 4
Enter a positive value (EOF to quit): 7
Enter a positive value (EOF to quit): 8
Enter a positive value (EOF to quit): 2
Enter a positive value (EOF to quit): -1
The number "-1" is invalid.
Enter a positive value (EOF to quit): 8
Enter a positive value (EOF to quit): 0
Enter a positive value (EOF to quit): -4
The number "-4" is invalid.
Enter a positive value (EOF to quit): CTRL-D
There were 6 valid numbers entered.
The sum of the valid numbers was 29 and the average was 4.83.
There were 2 invalid numbers.
import java.util.Scanner;
//Calculates the prime #1000.
public class Prime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, i=2, x=2;
[Code]....
I need to receive input from the user, as many times as he wants. tha is done with the while loop. I also need to output the min and the max numbers the user enters, therefore i have the if statememnts. also if the user enters only one value i need to output that one value as the min and the max.
int min =0;
int max = 0;
int option = JOptionPane.YES_OPTION;
while ( option == JOptionPane.YES_OPTION){
String dataString = JOptionPane.showInputDialog("Enter an integer");
int data = Integer.parseInt(dataString);
[Code] ....
I'm trying to do a user validation loop that runs until the user enters a valid binary, q, or Q. I think the rest of my program should work as intended, but here is the areas of concern:
public static boolean isBinary(String num) //Check if the entry is binary
{
for(int i = 0; i < num.length(); i++) {
if(num.charAt(i) != 0 || num.charAt(i) != 1){
return false;
[Code] .....
The program runs without errors otherwise.
Write a java program that will ask a user to input grades until the user inputs the sentinel value -1. The program should test each input to determine whether 0<=grade<=100. If the grade entered is within this range, the program should print "Grade accepted;" if not, the program should print "Invalid input".
View Replies View RelatedI have been struggling with this program for weeks. This program is supposed to take a user's inputted odd number and then print out all prime numbers lower than that number.
public class PrimeNumber
{
Scanner scan = new Scanner(System.in);
int userNum;
String neg;
public void getUserNum()
[code]...
So i'm just toying around with making a simple inventory system, and when i'm trying to get the user's input (first the ID number, then the item name, then the item price) it will take the ID number, output asking for the name (but not take any input for it) and then ask for the item's price. I'm really not sure why it's never happened to me before when getting user input.
This is the input part of my code:
public void getInfoAdd() {
int id;
String name;
double price;
System.out.print("Enter ID: ");
id = sc.nextInt();
System.out.print("Enter item name:");
name = sc.nextLine();
System.out.print("Enter desired price: ");
price = sc.nextInt();
addItem(id, name, price);
}
And this is what it outputs:
Quote
Enter ID: 2
Enter item name:Enter desired price: 40
Successfully added: 2 $40.0
I am doing an multi user chat application, i don't know how to identify the particular pair of user (both end chatting user) among users. and want to send message separately.., which steps i have to fallow, HasMap(); or what is the procedure to achieve my target.
This is my server side program,
Java Code:
import java.util.*;
import java.net.*;
import java.io.*;
public class ChatServer {
Vector<String> users = new Vector<String>();
Vector<HandleClient> clients = new Vector<HandleClient>();
public void process() throws Exception {
ServerSocket server = new ServerSocket(1234);
[Code] ......
Writing a program to take input from user. This input must be done with numbers only. If the input is a string I would like the program to loop and ask for input again.
double depositCheckingAmount;
do
{
System.out.println("Please insert amount to deposit into checking.");
[Code]....
As you can see my attempt is to use the ! expresssion incase the input does not equal a double. Is there another method I should be using?
So im trying to make a coin flip game in java. Im relatively new to the language and the only other language i knew was javascript so im still learning. Ive already made one before using just one class and putting all the code inside, but im now trying to do it with methods since im trying to learn them. The basic idea of the game is that the user picks how many coins they'd like to flip, they pick heads or tails, then the computer flips the coins and calculates if there was more heads or tails to tell the user if they won or not. Im not quite complete with the program as you can see but ive already run itno an error. I was just doing some tests on the code i already have and i found that when i call the method settingUpCoin in my main class the program terminates. So basically, when i run it, it executes userImp right, transform right, but then it dosent let you enter a value for howManyCoins and terminates before you get to settingUpCoin.
(Notes: this was all done in eclipse luna build or the java ide. The class files are all separate in the actual thing i just put them together here to demonstrate my code.
import java.io.IOException;
public class Coin
{
double myCoin;
int numOfCoins;
int counter;
double arrayOfCoins[] = { };
[code]....
i need to create a program that asks the user for an array and then asks the user to fill in the slots of the array but i have to do it in a method
View Replies View RelatedI was tasked with building a program that counts vowels in a phrase or word. I have this working properly, but the problem arises in the next situation. Here is my code:
Scanner userInput = new Scanner(System.in);
int userDecision;
String Choice;
String Phrase;
int vowelCount = 0;
System.out.println(" This program will count the number of vowels in it.
[Code] ....
As you can see, I used a 'for' statement to declare how long the program should run. However, I need the user to be able to say when it ends. For example, at the end of the program it must say "There are ______ number of vowels in your word. Please press '1' to run the program again, or any other number to exit."
I understand a do-while loop is needed here, but every time I try and create an adequate loop with no logic errors, I either break my existing code, or the program does not work correctly.
Basically, my question is, what is the best way to perform this task? Is a do-while loop necessary, or is there a better way?
This is a simple recursion program I had to write. I just cant seem to display my sum function to the user
import java.util.*;
import java.io.*;
public class Recursion {
public static void main(String[] args) {
int number = 0;
[Code] .....
I have an assignment where I'm supposed to write a program where the user inputs a month between 1-12 and then the right amount number in every month. I've tweaked the code a bunch of times, but I keep getting this error message:
insert "}" to complete StatementKALENDER_3.java
insert "}" to complete BlockKALENDER_3.java
The code:
import java.util.*;
import java.util.Scanner;
public class KALENDER_3
}
public static void main(String[] args){
Scanner scanner = new Scanner (System.in);
System.out.print("Skriv ett manadsnummer: ");
[code].....
I think I have just forgot to put in a few { } symbols, maybe an open loop?
My task is to create multiuser console chat program. During whole day of poking around , i finally stand on such concept:
1. When running , Server part must stay into while(true) loop and create threads on each ServerSocket.accept() call, providing socket object inside thread. i.e.
while (true){
System.out.println("Waiting for client to connect");
Thread t = new Thread(new Runner(servSocket.accept(),listOfClientSockets));
System.out.println("Starting thread");
t.start();
}
2. Client side always stays within while(true) loop and waiting for user input with ScannerInstance.nextLine() method.
As soon as user prints something and hits enter, data being captured from scanner and thrown to socket output stream to the server.
My question is : if all parties (X clients and server) are actually in waiting mode (server is waiting for connections and each client is waiting for user input), who will refresh the screen for each client to draw the messages other parties sent?
At this time , each party see updates only when he hits enter and while loop does next iteration reading data from buffer and displaying on console.
I am still relatively new to java and am working on a lab program. I have already met the requirements and am trying to spice my code up with a loop that prompts the user to say if the program should run again. This is what I have so far:
package lab2;
import java.util.Scanner;
public class OrderedPairTest{
public static void main(String[] args){
boolean retry = true;
while(retry == true){
[code]....
However, it is giving me an error after the user inputs "y" in for the answer to run again. What did I do wrong?
Error code is: Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) at lab2.OrderedPairTest.main(OrderedPairTest.java:11)
so I had to create a program that allows the user to enter a day using a number and then enter a year and after they did that it would create an entire calendar for that year ..so I have that but the only issue is I can not get the numbers to line up neatly.how to do the entire thing in loops, I tried a couple in here..what this would look like as loops instead of switches and cases and if else
import java.util.Scanner;
public class Calendar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
[code]....
How do i exit a java program is the user input is nothing "",This is my code
Java Code:
import java.util.Scanner;
public class MyQueue<T> implements Queue<T> {
private T[] ringbuffer;
static int capacity = 0;
int mysize = 0;
[code]....
Am i doing this right?
public class TwoStrings
{
public static String duplicate (String s) {
String t = s + s;
return t;
[Code] ....
I don't understand how i'm supposed to define a variable when the user has to type it into the program so it can be converted. This program i'm working on is supposed to convert from meters to feet (meter = feet * 0.305) but the user has to type in the meters they want converted. how do i solve the problem that keeps coming up that says "variable meter symbol cant be found" ? I keep trying different lines to no avail
public class Lab2
{
public static void main(String[] args) {
double feet = meter * 0.305;
double meter = feet/0.305;
System.out.println("Enter in feet for conversion to meters");
meter = meter * 0.305;
[Code] .....
I am new to Java an have to Create a program that keeps track of the following information input by the user: First Name, Last Name, Phone Number, and Age. Now - let's store this in a multidimensional array that will hold 10 of these contacts. So our multidimensional array will need to be 10 rows and 4 columns.You should be able to add and remove contacts in the array.
View Replies View RelatedOk, so I have to make a program that tells the user to type a sentence and at the end of the sentence a "." must be put to end the program. If a "." period is not entered, it must re-prompt the user to enter a period. On top of all this, the program has to count the number of letters in the sentence. I cant seem to get the while loop working and I cant find anywhere how to make a counter count the number of letters.
import java.io.*;
class Sentence
//The purpose of this program is to
[Code]....
So the assignment is as follows. Develop a new class called BankAccount. A bank account has the owner's name and balance. Be sure to include a constructor that allows the client to supply the owner's name and initial balance. A bank account needs - accessors for the name and balance, mutators for making deposits and withdrawals. I have the following code :
import java.util.Scanner;
public class BankAccount{
public static void main(String [] args){
Scanner reader = new Scanner(System.in);
double name;
double balance;
double deposit;
double withdrawl;
[Code] ....
I am having trouble with my if statements. I don't know how to link the number 1 & 2 keys to deposit and withdrawal actions. Plus I am supposed to have a while loop yet don't know how to implement this so that the while loop will ask the user if they would like to make another transaction after either depositing or withdrawing.