I am working on a program that allows the user to input an integer, double, character, and a string. I have used variables to store the numbers in I am using BlueJ as my IDE, and my question is how I can reverse a system.out.println line that has variables in it?
Here is my code below:
import java.util.Scanner;
import java.lang.String;
public class Lab1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Entering a integer
int money = 0;
System.out.println("Enter an integer:");
money = input.nextInt();
//entering a double
double cost = 10;
System.out.println("Enter a double:");
cost = input.nextDouble();
//Entering a character
char a;
System.out.println("Enter a character:");
a = input.next().charAt(0);
//Entering a string
System.out.println("Please enter a string:");
String string = input.next();
System.out.println();
//Single line separated by spaces
int num = money;
double price = cost;
char b = a;
String text = string;
System.out.println("Single line:");
System.out.print(num + " " + price + " " + b + " " + text);
//Values in reverse
System.out.println();
System.out.println();
System.out.println("Values in reverse:");
}
}
Note: I am using BlueJ for this, and I have tried reversing the variables but, I couldn't.
My output:
Enter an integer:
45
Enter a double:
98.32
Enter a character:
a
Please enter a string:
welcome
Single line:
45 98.32 a welcome
The reverse of '45 98.32 a welcome' should be:
Welcome a 98.32 and 45.
Thank you and have a great day.
System.out.println("Values in reverse:");
System.out.print(text + " " + b + " " + price + " " + num)
For this simple question, I thought you need to change the order of output then it would be fine?
Anyway, if this is not your expected output, do tell me so.
In case this is what you are looking for, reverse() method is for the StringBuilder class: String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder which meant you can only reverse the string output rather than the println in Java.
Related
I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
I have never taken a programming class before so I am very new to all of this and am having a bit of a challenge trying to get my answers to be displayed in writing. For example: if the user enters the numbers 2 and 5 and *, the answer should be displayed as two multiplied by five is 10.
Here is my program:
import java.util.Scanner;
public class CalculatorProjectCH
{//begin class
public static void main(String[] args)
{//begin main
//This program will ask the user to input two digits from 0-9 and then input a method of operation.
System.out.println("This program will act as a simple calculator. ");
System.out.println("It will ask you to enter two numbers from 0-9 and a method of operation "
+"(+, -, *, /, ^.) ");
//Declare variables input1, input2, result1, result2, result3, result4, and result5, as doubles.
double input1, input2, result1, result2, result3, result4, result5;
String text;
//Create scanner object to allow for input
Scanner input = new Scanner (System.in);
//Ask the user to enter the first number
System.out.print("\nEnter your first number: ");
input1 = input. nextDouble();
//Ask the user to enter the operation
System.out.println("Please enter the operation you would like to execute: ");
text = input.next();
//Ask the user to enter the second number
System.out.println("Enter your second number: ");
input2 = input.nextDouble();
result1= input1+input2;
result2= input1-input2;
result3= input1*input2;
result4= input1/input2;
result5= Math.pow(input1,input2);
switch (text)
{
case "+" :
System.out.println(result1);
break;
case "-" :
System.out.println(result2);
break;
case "*" :
System.out.println(result3);
break;
case "/" :
System.out.println(result4);
break;
case "^" :
System.out.println(result5);
break;
//If the user did not enter a valid method of operation
default :
System.out.println("Your operation was not recognized.");
}
}//end main
}//end class
You need to link the int value to the String version of the word somehow. I would suggest using an array:
String[] wordNumbers = new String[]{"zero","one", "two", "three"..."nine"};
Now when you need to print the String version of a number, just do this:
System.out.println(wordNumbers[0]);
Output:
zero
case "*" :
System.out.println(input1 + " multiplied by " + input2 + " is " + result3);
break;
case "/" :
System.out.println(input1 + " devided by " + input2 + " is " + result4);
break;
So I didn't change your code, just added this little part as an example to make sure what your question is about, is this what you are looking for?? And if this is it, you can just add + and - on your own with this principle.
there are another answers in stackoverflow, if you want this in your program than just tell me I can help you make it, I am just not sure what exactly you need
here I found a youtube video if you are into videos
I need to write a test class that will do the following:
a. Let the user input an integer and display it.
b. Let the user input a float value and display it.
c. Let the user input his/her name (no white spaces) and display the
name as: “Hello <name>, welcome to Scanner!”
d. Let the user input a character and display it.
e. Let the user input any string (with white spaces) and display it.
My questions is, how can I simply scan just a Character and display it? And in number 2, How can I input a String with white spaces and display it? (letters "d" and "e")
I've searched around, but I cannot find the simplest solution (since I'm new to Java and programming).
Here is my code so far:
package aw;
import java.io.PrintStream;
import java.util.Scanner;
public class NewClass1
{
public static void main(String[] args)
{
int num;
double num2;
String name;
char c;
Scanner sc = new Scanner(System.in);
PrintStream ps = new PrintStream(System.out);
//for integer
System.out.println("Enter a number: ");
num = sc.nextInt();
ps.printf("%d\n", num);
//for float
System.out.println("Enter a float value: ");
num2 = sc.nextDouble();
ps.printf("%.2f\n", num2);
//for name w/o white space
System.out.print("Enter your first name: ");
name = sc.next();
ps.printf("Hello %s, welcome to Scanner\n", name);
//for character
System.out.print("Enter a character: ");
c = sc.findWithinHorizon(".", 0).charAt(0);
System.out.print(“%c”, c);
//for name w/ white space
System.out.print("Enter your full name: ");
name = sc.nextLine();
System.out.print(“%s”, name);
}
}
I hope you can help me. Thanks!
First, there's no need to wrap System.out in a PrintStream because out already supports formatting with format() or printf() methods.
Next, you need to understand that when you input a line of data you also terminate it with a new line \n. The next<Type>() methods only consume the <Type> and nothing else. So, if a next<Type>() call may match \n, you need to skip over any extra new lines \n with another nextLine() before.
Here's your code with fixes:
int num;
double num2;
String name;
char c;
Scanner sc = new Scanner(System.in);
//for integer
System.out.print("Enter a number: ");
num = sc.nextInt();
System.out.printf("%d\n", num);
//for float
System.out.print("Enter a float value: ");
num2 = sc.nextDouble();
System.out.printf("%.2f\n", num2);
//for name w/o white space
System.out.print("Enter your first name: ");
name = sc.next();
System.out.printf("Hello %s, welcome to Scanner\n", name);
//for character
System.out.print("Enter a character: ");
c = sc.findWithinHorizon(".", 0).charAt(0);
System.out.printf("%c\n", c);
sc.nextLine(); // skip
//for name w/ white space
System.out.print("Enter your full name: ");
name = sc.nextLine();
System.out.printf("%s", name);
Use Scanner.next(Pattern) and pass Pattern.compile("[A-Za-z0-9]") to let scanner accept only 1 character defined. You can pass any regex as argument and check for next() Scanner.next(); for next line with spaces
Use this:
//for a single char
char Character = sc.findWithinHorizon(".", 0).charAt(0);
//for a name with white space
System.out.print("Enter your full name: ");
String name2 = sc.next();
String surname = sc.next();
System.out.println(name2 + " " + surname);
I already try to make a program it works as well but the problem is, that is not the same output what i want.
Note **
That is what i want..
enter starting base: it should be binary or octal or hexa
enter end base: it should be decimal
enter number: if 2 is entered as the starting base only 1s and 0s can be entered. If 16 is entered as the starting base 0-9 and A-F can be used.
and what i make :(
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
String binaryNumber = scanner.nextLine();
System.out.println("Enter a end base: ");
String octalNumber = scanner.nextLine();
System.out.println("Enter a number: ");
String decimalNumber = scanner.nextLine();
int myInt = Integer.parseInt(binaryNumber, 2);
int myInt2 = Integer.parseInt(octalNumber, 8);
int x = myInt;
System.out.println(
binaryNumber + " in Binary, is "
+ Integer.toString(myInt, 8) + " in Octal" + " and "
+ Integer.toString(x, 10) +" in decimal");
This is what you need to do. Figure out the code and understand. You have Scanner#nextInt() method to read integers. You don't have to use nextLine() method for this. And more over, Scanner#nextInt(int radix) accepts the input in specified radix form. It throws an exception if you don't enter the input in that form. You can catch that exception to display the error message to the user.
Your goals startBase,endBase, and the variables used for them binaryNumber is mismatching. Please name your variables which convey the purpose of them.
See the modified version of your code here:
import java.util.*;
public class Tester{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
int startBase = scanner.nextInt();
System.out.println("Enter a end base: ");
int endBase = scanner.nextInt();
int number=0;
try{
System.out.println("Enter a number: ");
number= scanner.nextInt(startBase);
System.out.println("Entered number:"+number+"(base"+startBase+")");
System.out.println("Converted number:"+Integer.toString(number,endBase)+"(enbase"+endBase+")");
}catch(InputMismatchException e){
System.out.println("Invalid input for the given radix");
e.printStackTrace(); //you can comment it if you don't need this.
}
}
}
How do I enter a digit like '23423' and output it like '2 3 4 2 3'? And how do I make it so that user cannot enter less or more than 5-digits?
(Your help would be appreciated. I just need hints from you guys since I'm learning Java. Looking forward to learn something new.)
This is what I have so far:
Scanner input = new Scanner(System.in);
int value1, value2, value3, value4, value5;
System.out.print("Enter a number: ");
value1 = input.nextInt();
System.out.print("Enter a number: ");
value2 = input.nextInt();
System.out.print("Enter a number: ");
value3 = input.nextInt();
System.out.print("Enter a number: ");
value4 = input.nextInt();
System.out.print("Enter a number: ");
value5 = input.nextInt();
System.out.printf(" %d " + " %d " + " %d " + " %d " + " %d\n ", value1, value2, value3, value4, value5);
It can be redone with a loop: make the loop read the input 5 times and, each time, put the i-th read value at the i-th position of an array.
Then, to print it, you can just use a for loop that prints each element of the array.
If you really want them to enter a single 5 digit number, you're going to have to do validation on the users input and then give an error if the input isn't valid. If the requirements are such that the first digit of your 5 digit number should never be zero, you can just get an int and then check if it is greater than 9999 and less than 100000. Otherwise take it as a string and check the length, then turn it into an integer once you have validated it.
The most appropriate solution seem to me a while loop where you build a string and add a space. In the aftermath of the while processing you should eliminate the last space. Something like the following should fit your needs. I have used the apache commons project, but you also utilize your own class.
Scanner scanner = new Scanner(System.in);
String str = "";
while (scanner.hasNext()) {
String next = scanner.next();
if (next.equals("E")) {
break;
}
if (NumberUtils.isNumber(next)) {
for (int i = 0; i < next.length(); i++) {
str += Integer.valueOf(next.substring(i, i + 1)) + " ";
}
}
}
str = str.substring(0, str.length() - 1);
System.out.println("your number: " + str);
With "E" you can exit the loop.