i have an absolute value program and as of right now it accepts numbers like 1 +1 -1 but i also need it to be able to accept decimals as valid inputs from the user. i also need to use the intString.matches method. how would i go about doing that?
here is the code im supposed to redo
import java.util.Scanner;
public class absolutevalue {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Type in a number ");
String inStr = input.nextLine();
if (inStr.matches("//d"))
System.out.println("The absolute value is" +inStr);
else
System.out.println("not even close");
input.close();
}
}
You can accept String, double, float, big decimal, boolean from user with small change like :
import java.util.Scanner;
public class absolutevalue {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Type in a number ");
int num = input.nextInt(); // for Int.
String str = input.next(); // for String.
String str = input.nextLine(); // for line of String.
double num = input.nextDouble(); // for double.
float str = input.nextFloat(); // for float.
if (num <0){
num = num * -1;
}
System.out.println("The absolute value is " + num);
input.close();
}
}
You can do that with
Float num = input.nextFloat();
Your code will be like that...
import java.text.DecimalFormat;
import java.util.Scanner;
public class AbsoluteValue {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Type in a number ");
Float num = input.nextFloat();
if (num < 0) {
num = num * -1;
}
System.out.println("The absolute value is " + num);
input.close();
}
}
Related
I'm attempting to write a loop, that when the user inputs Y, the loop continues, and when the user inputs N, the loop stops. However, when I try to assign the variable I get the error "Cannot convert from void to char" I'm obviously messing up somewhere along the line but I'm not sure where.
import java.util.Scanner;
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
char ans = System.out.print("Would you like to input another value? (Y or N)? ");
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
} ```
You're assigning ans to the result of System.out.print() which is a void method.
Instead, create the prompt beforehand and use the Scanner to take the input:
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
// New Prompt
System.out.print("Would you like to input another value? (Y or N)? ");
// Take input and set ans
char ans = input.next().charAt(0);
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
}
In Java, if you want to ask users, for example, to input numbers only between 1,000 and 100,000, the program would continue further. Otherwise, ask the user to input the number again in the given range.
Edit: Here, my program only tries to validate the input only once. How shall I make to ask the user to input until valid data(i.e between 1000-100000) is entered
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Principal:");
double principal = sc.nextDouble();
if(principal<1000 || principal >100000) {
System.out.println("enter principal again:");
principal = sc.nextDouble();
}
}
You can use do-while loop here as below
public static void main(String []args){
Scanner in = new Scanner(System.in);
int result;
do {
System.out.println("Enter value bw 1-100");
result = in.nextInt();
} while(result < 0 || result > 100);
System.out.println("correct "+ result);
}
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
class Myclass {
static boolean isInteger(double number){
return Math.ceil(number) == Math.floor(number);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double num;
do{
System.out.print("Enter a integer between 1000 and 100000 : ");
num = in.nextDouble();
}
while((num < 1000 || num > 100000)||(!isInteger(num)));
System.out.println("Validated input : "+num);
}
}
Hope this helps you
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!
I would like to take my current program and separate the averging function in to a method out side of the main method. I would like to store the numbers grabbed with the scanner in to an array list and then use my averaging method to grab those number and average the numbers together. then Output the average in place of the current System.out.println your average is..
Please help me illustrate this. I am having trouble understanding how all this comes together.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
{
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
}
//added an import here
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
//main difference is the average calculation is done within a method instead of main
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
double sum = 0;
int count = 0;
System.out.println("Enter a number to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) //input until user no longer wants to give input
{
if (count == 21)
{
break; //this command here jumps out of the input loop if there are 21
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble()); //simply adding to the array list
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr); //go to method calculate average, expect a double to be returned
System.out.println("Your average is: " + average);
}
private static Double calculate_average( ArrayList<Double> myArr ) //method definition
{
Double Sum = 0.0;
for (Double number: myArr) //for loop that iterates through an array list
{
Sum += number; //add all the numbers together into a sum
}
return Sum / myArr.size(); //return the sum divided by the number of numbers in the array list
}
}
This should help. Best of luck :)
Average avg = new Average();
... avg.add(scan2.nextDouble());
System.out.println("Your average is: " + Average.result());
public class Average {
void add(double x) { ... }
double result() { ... }
}
The thinking up the implementation I leave to you.
Here is some example code
private static void hoot(List<Double> kapow)
{
... do all the stuffs
}
public static void main(final String[] arguments)
{
List<Double> blam = new ArrayList<Double>();
blam.add(1.1);
blam.add(1.2);
blam.add(1.3);
hoot(blam);
}
Im writing a code that will will take the entered number and only add the values that are in the even positions.
For example:
If user enters 53429
The sum of of the even positions is 5.
My issue is I'm trying to convert the strings of the even positions back into integers and add them together. This is what I have
I keep receiving an error when I try to parse the string to an integer.
Cannot find symbol
symbol : method parseInt(java.lang.String)
location: class Integer
Code:
import java.util.Scanner;
public class NumberSums {
public static void main(String [] args) {
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if (length<5) {
System.out.println("Invalid value");
System.exit(0);
}
if (length>5) {
System.out.println("Invalid value");
System.exit(0);
}
String s2 = s1.substring(0,1);
String s3 = s1.substring(1,2);
String s4 = s1.substring(2,3);
String s5 = s1.substring(3,4);
String s6 = s1.substring(4,5);
int a = Integer.parseInt(s3);
//int b = Integer.parseInt(s5);
//sum = (a + b);
System.out.println("The sum of all even positions is " + sum);
}
}
I'm willing to bet that you have a class named Integer, and Java is trying to use that rather than java.lang.Integer.
Rename your class, or use java.lang.Integer.parseInt(s3) instead.
code to add even placed chars in the string.
String str="1234567";
int sum=0;
for(int i=1;i<str.length();i=i+2){
sum+=(str.charAt(i)-'0');
}
System.out.println(sum);
And we can also take from keyboard and start the calculation:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter number : ");
String number=null;
try{
number = reader.readLine();
}
catch (IOException e) {
e.printStackTrace();
throw e;
}
int sum=0;
for(int i=1;i<number.length();i=i+2){
sum+=(number.charAt(i)-'0');
}
System.out.println(sum);
I ran the program and it works fine... if you uncomment the lines int b and sum = (a + b);. However, you have to declare the sum variable, i.e. int sum = (a + b);
What JDK are you running? The error you describe would only occur if Integer.parseInt(String foo); didn't exist, except it's been around since at least Java 1.4, so I'm not sure why you wouldn't find it; unless you have another Integer class defined in the same package, which could confuse the compiler.
Here is the complete program, including imports (which may be the problem, if you're importing a different Integer than java.lang.Integer), fixing the variable declaration and removing unnecessary code, fixing indentation, and adding a Scanner.close() statement:
import java.util.Scanner;
public class Test {
public static void main(String [] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if(length != 5)
{
System.out.println("Invalid value");
System.exit(0);
}
String s3 = s1.substring(1,2);
String s5 = s1.substring(3,4);
int a = Integer.parseInt(s3);
int b = Integer.parseInt(s5);
int sum = (a + b);
System.out.println("The sum of all even positions is " + sum);
keyboard.close();
}
}
The Modified code. Try understanding it.
import java.util.Scanner;
public class EvenPos {
public static void main(String [] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if(length<5) {
System.out.println("Invalid value");
System.exit(0);
}
if(length>5) {
System.out.println("Invalid value");
System.exit(0);
}
else{
char a = s1.charAt(1);
char b = s1.charAt(3);
int q = Character.getNumericValue(a); //Convert Char to Integer
int z = Character.getNumericValue(b); // //Convert Char to Integer
int sum = 0;
if (q % 2 == 0 && z % 2 == 0){ //If both even, then.....
sum = q+z;
System.out.println("Your sum: " + sum);
}
else{
System.out.println("No even Number found at even POS");
}
}
}
}