This question already has answers here:
Displaying asterisk depending on the number entered [closed]
(3 answers)
Closed 8 years ago.
So I have to show the number of total grades(which i have calculated already) as astrisk. the output should be like this,
A=******
B=******
C=******
D=*****
And this is my code:
import java.io.*;
import java.util.*;
public class grades
{
public static final void main(String args[]) throws FileNotFoundException
{
System.out.println("name");
Scanner myScanner = new Scanner(new File("students.txt"));//Creating new scanner object
int lineNumber =1;//Line Number for each student.
while (myScanner.hasNext())
{
String firstName = myScanner.next();//Scanning student first name and storing in the string
String lastName = myScanner.next();// Scanning student last name and storing in the string
String athleteFlag=myScanner.next();//Scanning for verification of athlete and storing in the string
String athlete= "Y";
String notAthlete = "N";
//if else statement to declare if student is a athlete
if (athleteFlag.equals(athlete))
{
athleteFlag="YES";
}
else if(athleteFlag.equals(notAthlete))
{
athleteFlag="NO";
}
int quiz1=myScanner.nextInt();// Grades on Quiz 1
int quiz2=myScanner.nextInt();// Grades on Quiz 2
int quiz3=myScanner.nextInt();// Grades on Quiz 3
int quiz4=myScanner.nextInt();// Grades on Quiz 4
int quiz5=myScanner.nextInt();// Grades on Quiz 5
int test1=myScanner.nextInt();// Grades on Test 1
int test2=myScanner.nextInt();// Grades on Test 2
//student quiz average
double quizAverage = (double)(quiz1+quiz2+quiz3+quiz4+quiz5)/5;
//Overall Numerical Grade
float overallNumericalGrade =(float)(quizAverage+test1+test2)/3;
//Students letter Grade, eligibility and counting number of each grade
String grade;
String eligibility;
int gradeA=0;
int gradeB=0;
int gradeC=0;
int gradeD=0;
int gradeF=0;
if(overallNumericalGrade>=90.0)
{
grade="A";
eligibility ="YES";
gradeA++;
}
else if(overallNumericalGrade>=80.0)
{
grade = "B";
eligibility ="YES";
gradeB++;
}
else if(overallNumericalGrade>=70.0)
{
grade = "C";
eligibility ="YES";
gradeC++;
}
else if(overallNumericalGrade>=60.0)
{
grade = "D";
eligibility ="NO";
gradeD++;
}
else
{
grade = "F";
eligibility ="NO";
gradeF++;
}
System.out.println(lineNumber + " "+lastName+","+firstName+"/ "+athleteFlag+ "/ " + eligibility +
" / " +"Grades on all quiz "+ quiz1+ " "+quiz2+" "+quiz3+" "+ quiz4+" "+quiz5+" "+test1+" "+
test2+ " /" +"quiz average is " + quizAverage +"\n " + "Overall Numerical grade is " +
overallNumericalGrade+" / "+ "Student letter Grade is " + grade);
lineNumber++;
}
}
}
I just dont know how to output this. Any help will be appriciated. Thanks in advance.
Assuming the total of all grade is overallNumericalGrade and that you want to display it as * in the last output (as this is the only output in your code), You could do
System.out.println(lineNumber + " "+lastName+","+firstName+"/ "+athleteFlag+ "/ " + eligibility +
" / " +"Grades on all quiz "+ quiz1+ " "+quiz2+" "+quiz3+" "+ quiz4+" "+quiz5+" "+test1+" "+
test2+ " /" +"quiz average is " + quizAverage +"\n " + "Overall Numerical grade is " +
String.valueOf(overallNumericalGrade).replaceAll(".", "*")+" / "+ "Student letter Grade is " + grade);
The important part is here
String.valueOf(overallNumericalGrade).replaceAll(".", "*")
Where I convert the total value to a String then replace everything with *.
If the total is not overallNumericalGrade then simply use the replacement on whatever is the value.
Edit : To answer to your comment, here more explanation.
String.replaceAll is a method that replace everything corresponding to the given Regular expression(regex) given by what we give as second parameter ( in that case *). The regex I gave is simply a . which means any character except linebreak. So, String.valueOf(overallNumericalGrade) convert it to a String so I can call the replaceAll method, then replace everything with *.
As for an answer to your second question, once again you could use the replacement to replace each linebreak of grade by a simple space so that it display all on the same line. Something like
grade.replaceAll(System.getProperty("line.separator"), " ");
Notice that I used System.getProperty("line.separator") instead of giving in the char so that it work on any system.
Related
This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 4 years ago.
/**
* MadLib.java
*
* #author: Jackie Hirsch
* Assignment: Madlib
*
* Brief Program Description: This program has will read a madlib with
the inputs that the user gives the computer.
*
*
*/
import javax.swing.JOptionPane; //import of JOptionPane
public class MadLib
{
public static void main (String[] args)
{
String cheeseType; //Cheese Character
String interjection; //interjection
String treeType; //tree type
String wholeNumberFriends; // number for number of friends on
//line 27
String numberMiles; //number of miles
int wholeNumberFriendsConverted; // number for number of
//friends on line 27 converted
double numberMilesConverted; //number of miles
//ask user for variable string cheese type
cheeseType = JOptionPane.showInputDialog ("Enter a type of
cheese");
//ask user for varaible string interjection
interjection = JOptionPane.showInputDialog ("Enter an
interjection");
//ask user for variable string tree type
treeType = JOptionPane.showInputDialog ("Enter a type of
tree");
//ask user for variable integer number for number of friends
wholeNumberFriends = JOptionPane.showInputDialog ("Enter a
whole number");
//ask user for variable double number for number of miles
numberMiles = JOptionPane.showInputDialog ("Enter a decimal or
whole number");
//string converted
wholeNumberFriends = Integer.parseInt
(wholeNumberFriendsConverted);
numberMiles = Integer.parseInt (numberMilesConverted);
//Madlib reading printed
JOptionPane.showMessageDialog (null, "There once was a " +
cheeseType + "and this " + cheeseType + "was super exciting. "
+
"Because " + cheeseType + "was so exciting he would shout, " +
interjection + ". " +
"His " + wholeNumberFriendsConverted + "friends, the " +
treeType + ", would sing home and the whole" +
"neighborhood hated them. One neighboor walked outside and
said, " +
"''You annoying hooligans are crazy!!!''. They were so confused
that" +
"they ran away to Neverland which was " + numberMilesConverted
+ "miles so they never" +
"had to grow up. Then they ran into captain hook and then Peter
Pan saved them.");
System.exit (0); //ends the program
}
}
**Hello. I just started learning how to code Java this week in my high school computer science class. I'm trying to convert a string to a double and an integer. The two variables I'm trying to convert are wholeNumberFriends (integer) and numberMiles (double). I have created a new variable for each of them so they can easily convert to a double and an integer. The error I keep getting for this conversion is, incompatible types: double cannot be converted to java.lang.String . Thank you. **
String to Integer
int num = Integer.parseInt("1");
String to Double
double num = Double.parseDouble("1.2");
You can use Integer.valueOf(java.lang.String)
String userInput = "2";
try {
Integer.valueOf(userInput);
} catch (NumberFormatException e) {
// Not a Number
}
The same valueOf method is available in Double, Float, Long etc..
The valueOf method will return you an Object instead of primitive.
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.
Hi im creating a simple mp3 database that stores a trackNum, name and duration. I need to search an array list and get the index of the search.
Here is what i have at the moment.
//My methods
public void searchTrackNum(Intager trackNumber){
System.out.println(trackNum + ": " + name[index] + " " + duration[index]);
}
public void searchName(String name){
System.out.println(trackNum + ": " + name[index] + " " + duration[index]);
}
//Using the methods
case 4:
System.out.println("What name would you like to search for: 1-Track Number or 2-Name");
int question = in.nextInt();
if(question == 1){
System.out.println("Please enter the track Number?");
meth.searchTrackNum(in.nextInt());
}
if(question == 2){
System.out.println("Please enter the Name?");
meth.searchName(in.next());
}
else{
System.out.println("Pease enter 1 or 2.");
}
break;
How do i search an arrayList
I need to be able to get the index of the search to add the name of the track and the duration of it.
I suggest using
int index = Arrays.asList(names).indexOf(nameToLookFor);
If the names are sorted, you can use binarySearch instead.
The task is to "Write a program that displays a user-indicated number of multiples for an integer entered by the user."
I suppose I do not need a completely direct answer (although I do want to know the methods/formula to use), as I want to use this as a learning experience in order to do and learn from the task myself. I really want to know about the process and which methods to use, along with finding a formula. :||
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
So far, I have:
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
\\just stuff to base my code off of
int integer;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
\\pretty much everything from here on out.. I'm not sure what to really do.
int n = integer;
int result = (integer * (numberMultiples));
while (result > 0){}
System.out.print(result);
}
} \\at the moment this code doesn't seem to have any running errors
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
NEW QUESTION
I need to loop my program as well. (By asking a question to the user first.) Mines isn't working, as it just keeps looping only the integer loop and doesn't let me type yes/no.
import java.util.Scanner;
public class MultipleLoops
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int integer, numberMultiples;
String repeat = "yes";
while (repeat != "no")
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++){
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
}
}
}
Ok so you need to understand the problem first to know how to solve it
x = First input
n = Second input
you need to calculate n multiple of x
example with x = 3 and n = 10
To calculate 10 multiple of 3 we need to do :
1st multiple = x*1
2nd multiple = x*2
3rd multiple = x*3
...
n multiple = x*n
you can notice that these operations can be replaced by one for loop (notice first and last character of every line, it can be index of your loop )
Back to java :)
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
Replace your code with the following and try this code :
import java.util.Scanner;
public class MultipleLooping{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int integer,numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
}
}
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing multiple N# 1 = 3
Listing multiple N# 2 = 6
Listing multiple N# 3 = 9
Listing multiple N# 4 = 12
Listing multiple N# 5 = 15
Listing multiple N# 6 = 18
Listing multiple N# 7 = 21
Do you want like this ? Below is the code
package com.ge.cbm;
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//just stuff to base my code off of
int integer;
int firstEntered;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
firstEntered = integer;
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
//pretty much everything from here on out.. I'm not sure what to really do.
for (int i=0;i<numberMultiples;i++){
integer=integer*firstEntered;
System.out.println(integer);
}
}
}
Output:
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing the first 7 multiples of 3:
9
27
81
243
729
2187
6561
this should work
while(repeat.equals("yes"))
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++)
{
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
repeat = keyboard.nextLine();
}
I'm currently working on a program and ran into an error while trying to execute a for loop. I want to declare a variable in the for loop, then break once that variable obtains a certain value, but it returns the error "cannot be resolved to a variable."
Here's my code
int i = -1;
for (; i == -1; i = index)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
int index = (input.indexOf('y'));
}
I want to run the output segement of my program until the user inputs yes, then the loop breaks.
The variable index's scope is local to the block of the for loop, but not the for loop itself, so you can't say i = index in your for loop.
You don't need index anyway. Do this:
for (; i == -1;)
or even
while (i == -1)
and at the end...
i = (input.indexOf('y'));
}
Incidentally, I'm not sure you want input.indexOf('y'); an input of "blatherskyte" will trigger this logic, not just "yes", because there's a y in the input.
Instead of using a for loop, you can do-while(it suits much better for this scenario.
boolean exitLoop= true;
do
{
//your code here
exitLoop= input.equalsIgnoreCase("y");
} while(exitLoop);
for indefinite loop, i would prefer while.
boolean isYes = false;
while (!isYes){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}
You cannot do this. If the variable is declared inside of the loop, then it is re-created every run. In order to be part of the condition for exiting the loop, it must be declared outside of it.
Alternatively, you could use the break keyworkd to end the loop:
// Should we exit?
if(input.indexOf('y') != -1)
break;
Here you want to use a while loop. Usually you can decide which loop to use by saying your logic out loud to yourself, While this variable is(not) (value) do this.
For your problem, initialize the variable outside of the loop, and then set the value inside.
String userInput = null;
while(!userInput.equals("exit"){
System.out.println("Type exit to quit");
userInput = scan.nextLine();
}