Can someone please explain the usage not just answer I really would like to learn how to do this. This is my 2nd month using Java and please explain formatting usage in Java. Thank you so much. I really appreciate it. Feel free to ask any other question in regards C++ or python. I am in need of help in formatting, big decimal usage and how to set
import java.util.*;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.math.*;
public class Main{
public static void main(String[] args)
{
Scanner myCalculation = new Scanner(System.in);
System.out.print("Welcome to the Interest Calculator \n\n");
String option = "y";
while (option.equalsIgnoreCase("y"))
{
System.out.print("Enter Loan Amount: ");
//double loanAmount = 520000;
double loanAmount = myCalculation.nextDouble();
//Get Interest rate from user
System.out.print("Enter Interest Rate: ");
// double interRate = .05375;
double interRate = myCalculation.nextDouble();
double interest = loanAmount * interRate;
System.out.printf("%.3f", interest);
System.out.println();
//prompt user to continue? if he enter y then it will Continue
//else it will stop
//System.out.println("Continue? (y:n): ");
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
System.out.println("Would you like to continue? (yes or no)");
String s = scan.nextLine();
if(s.equals("no")) {
stop = true;
}
}
}
}
}
Scanner in = new Scanner(System.in);
System.out.print("enter double");
double d = in.nextDouble(); //doubles
System.out.print("enter int");
int i = in.nextInt(); //ints
System.out.print("enter text");
String text = in.next(); //gets a string up to the first space
in.nextLine();
System.out.print("enter text w/ spaces");
String line = in.nextLine(); //gets a string up to the first space
System.out.println(d);
System.out.println(i);
System.out.println(text);
System.out.println(line);
in.close();
System.out.println(new DecimalFormat("#.###").format(4.567346344634));
Related
I have a problem with trying to end this while loop. When it runs, typing "exit" for the name part doesn't seem to register and the code continues as if "exit" was a name typed in. What I intended to happen is for "exit" to be typed in so that the loop can end. Any help? Here is the code for the class:
import java.util.*;
import java.io.*;
public class BankTest {
public static void main(String args[]) {
List<BankAccount> bank = new ArrayList<BankAccount>();
Scanner scan = new Scanner(System.in);
//enter into list the accounts and end with exit typed in
String name = "";
while (name.contains("exit")==false) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
//find highest account amount
double largestMon = bank.get(0).getBalance();
String largestPer = bank.get(0).getName();
for (int i=0;i<bank.size();i++) {
double compare = bank.get(i).getBalance();
if (compare>largestMon) {
largestMon = compare;
largestPer = bank.get(i).getName();
}
}
System.out.println(largestPer+" has the largest account with $");
}
}
I've already tried switching between != and equals() compare the strings.
Change while (name.contains("exit")==false) to while(true)
and add line if (name.equals('exit')) break; after name = scan.nextLine();
First of all you could change
name.contains("exit")==falseinto !name.contains("exit")
A better solution would be to use a while true loop and break if the name variable is equal to "exit"
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
Notice that in cases like this you shouldn't use .contains() or .equals but rather .equalsIgnoreCase()
This should work
while(true){
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
Modify your while loop as follows:
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
How can I limit the input to only integers (no doubles etc)? simple question for someone experienced to answer. if input is anything other than double then display error message, with ability to enter input again
import java.util.Scanner;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int years;
int minutes;
System.out.println("Years to Minutes Converter");
System.out.print("Insert number of years: ");
years = reader.nextInt();
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}
Use Scanner.hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Example code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt())
sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt())
sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt or worry about NumberFormatException. Note that since hasNextXXX methods doesn't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.
Ok I made this:
package reader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System. in );
int years;
int minutes;
String data = null;
System.out.println("Years to Minutes Converter");
boolean test = false;
while (test == false) {
System.out.print("Insert number of years: ");
String regex = "\\d+";
data = reader.next();
test = data.matches(regex);
if (test == false) {
System.out.println("There is a problem try again");
}
}
years = Integer.valueOf(data);
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}
It will say:
Years to Minutes Converter
Insert number of years: dsds
There is a problem try again
Insert number of years: ..
There is a problem try again
Insert number of years: 2
That is 1051200 in minutes.
I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!
This question already has answers here:
Check if String contains only letters
(17 answers)
Closed 7 years ago.
I am writing some code but am unsure how to set it so users can only input certain letters for grade. (A,B,C,D,F)
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String Grade1;
String Grade2;
String Grade3;
String Grade4;
String Grade5;
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
System.out.println("Please enter leter grade one. \n");
Grade1 = in.next();
System.out.println("Please enter leter grade two. \n");
Grade2 = in.next();
System.out.println("Please enter leter grade three. \n");
Grade3 = in.next();
System.out.println("Please enter leter grade four. \n");
Grade4 = in.next();
System.out.println("Please enter leter grade five. \n");
Grade5 = in.next();
System.out.println("Your grades are ==>");
System.out.println(Grade1);
System.out.println(Grade2);
System.out.println(Grade3);
System.out.println(Grade4);
System.out.println(Grade5);
}
}
Variables should start with lowercase letter.
To ensure only valid data is entered, loop back and ask again if it's wrong.
Letter is spelled with 2 t's.
Use nextLine(), not next().
Easiest way to check valid text (for this case), is a regular expression, e.g.
String grade1;
do {
System.out.println("Please enter letter grade one: ");
grade1 = in.nextLine();
} while (! grade1.matches("[ABCDF]"));
Use this approach.
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String[] grades = new String[5];
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
for(int i = 0; i < grades.length; i++) {
System.out.println("Please enter letter grade " + i + "\n");
grades[i] = in.nextLine();
while(!grade[i].matches("[abcdfABCDF]")) {
System.out.println("Please enter a grade from A to F");
grades[i] = in.nextLine();
}
}
System.out.println("Your grades are ==>");
for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
}
}
I have some code with no compile errors, but after I enter the second number while its running it crashes on me :(
Heres what I have:
import java.util.Scanner;
public class Assignment536 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of sides: ");
int numberOfSides = input.nextInt();
System.out.println("Enter the side: ");
double side = input.nextInt();
System.out.println("The area of the polygon is: " +area(numberOfSides, side));
input.close();
}
public static double area(int n, double side) {
double answer = (n*(side*side))*(4*(Math.tan((Math.PI*n))));
return answer;
}
}
Any help would be greatly appreciated!
Thank you,
Sebastian
Add input.nextLine() between the numberOfSlices and side request...
System.out.println("Enter the number of sides: ");
int numberOfSides = input.nextInt();
input.nextLine();
System.out.println("Enter the side: ");
double side = input.nextInt();
After requesting numberOfSlices there is still a carriage return/line feed in the input buffer, when you try and request the side value Scanner fails because it can't convert the the carriage return/line feed to a double type.
You should change:
final double side = input.nextInt();
for
final double side = input.nextDouble();
if you want to read a double.
The last part of your formula is wrong. It should be (Math.pi/n) .
import java.util.Scanner;
public class CalcAreaPolygon {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
double area;
final double PI; /method in the formula
double side;
int n;
PI = Math.PI;
System.out.println("Enter the number of sides: ");
n = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter the side: ");
side = scanner.nextDouble();
area = (n * (side * side)) / (4 * (Math.tan(PI/n)));
System.out.println("The area of the polygon is " + area);
}
}