How can I define a char variable within a method? - java

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));
}
}

Related

Take integer inputs till the user enters 0 and print the sum of all numbers (HINT: while loop) (coding language:- JAVA)

IN this problem we have to print the sum of all the numbers until the user enters zero.
my attempt:
import java.util.Scanner;
public class printsum_until_enter0 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
//int count = 0;
int x = in.nextInt();
while (x >0) {
if (x > 0) {
sum = sum + x;
System.out.println(sum);
x--;
} else {
System.out.println("no data was entered");
}
x--;
}
}
}
it runs infinitly before writing X--...but now it takes only one input and after that it is executed...but it supposed to execute after entering 0 and sum of all the numbers before entering 0. But it is not happeing.Any solution guys...Code in java..
Your problem is that you only ask the user for input once. What you want to do is move the scanner.nextInt part somehow into your loop. In java there is a concept called do while loop which executes the loop body first and then checks the loop condition if it should be repeated. If you do not want to use a do while loop you can use a while true loop to check if the input was 0 and exit. Notice also how x needs to be initialised before the function body to be recognized by the while statement
Unfortunately, I did not get why you decreased x in your code. Let me know if I misunderstood your question or you have any more questions
import java.util.Scanner;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int x = 0;
do {
System.out.println("Please insert a number: ");
x = in.nextInt();
// If x is 0 it wont change the sum
sum += x;
System.out.println(sum);
} while (x > 0);
System.out.println("no data was entered");
}
}
Fixed your code
package test1;
import java.util.Scanner;
public class printsum_until_enter0 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int x = in.nextInt();
while (x >0) {
if (x > 0) {
sum = sum + x;
} else {
System.out.println("no data was entered");
}
x = in.nextInt();
}
System.out.println(sum);
}
}
do {
x = in.nextInt();
if(x > 0) {
sum += x;
}
} while(x > 0)

how to use value from the for-loop outside it java

import java.util.Scanner;
public class App {
public static void main(String[] args) {
double input;
double netto=0;
Scanner value = new Scanner(System.in);
for(int x=0;x<4;x++){
System.out.println("Please enter the number");
input = value.nextInt();
if(input>=300){
netto= input - input*0.30;
}
else {
netto =input- input*0.20;
}
}
netto=+netto;
System.out.println(netto);
}
}
i want that the code adds the results after subtracting part of them according to the entered value.
the problem is that the code saves the last result only and shows it.
Seems like you meant to accumulate the values into netto using += instead of overriding it with =:
for (int x = 0; x < 4; x++) {
System.out.println("Please enter the number");
input = value.nextInt();
if (input>=300) {
netto += input - input * 0.30; // Here
}
else {
netto += input - input * 0.20; // And here
}
}

How to use try catch to replace invalid data of user input array instead of restarting code in Java?

Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}

how can i change my program to accept different inputs?

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();
}
}

Finding the maximum out of three doubles from standard input

We have a java assignment where in we're supposed to develop a method that scans one line that is supposed to contain three double values and returns the largest. Throwing all possible exceptions is allowed.
Here is what I've done so far:
import java.util.Scanner;
public class s3dv {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double entered;
System.out.println("Enter 3 values to find the maximum:");
entered = input.nextDouble();
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
} // End getMaxValue method
}
I'm having an error at line 15.
change your code to
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
System.out.println("Enter 3 values to find the maximum:");
for(int i=0;i<3;i++){
entered[i] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i]; } } return maxValue;
}
You cannot give a double parameter to a method while it expects a double array. And also you request user to enter double value only once, you should repeat that procedure. Change your main method to this:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
int counter = 0;
while (counter != 3)
{
System.out.println("Enter a double value:");
entered[counter++] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
Your getMaxValue() method seems OK, however when entering doubles from console use comma(,) instead of dot(.), you might get InputMismatchException otherwise.
this main code will read the 3 double value in a single line, split them and pass it to the getMaxValue
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userLine, lineSplitted[];
System.out.println("Enter 3 values to find the maximum:");
userLine = input.nextLine();
lineSplitted=userLine.split(" ");
double entered[]=new double[lineSplitted.length];
for (int i=0; i<lineSplitted.length; i++) entered[i]=Double.valueOf(lineSplitted[i]);
System.out.println("Maximum is - " + getMaxValue(entered));
}

Categories

Resources