gpt4 book ai didi

java - 如何找到 (x :g)?) 的基数 10

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:12:16 25 4
gpt4 key购买 nike

我的作业快结束了,对这个算法的正确方法有点困惑。我需要找到一个数字的 base10:用户提供的基数。

基本上我的程序所做的是接受用户输入,例如 407:8 或 1220:5 等。

我想输出的是这样的。

 INPUT:    407:8 
OUTPUT: 407 base 8 is 263 base 10

我一直在考虑这种漫长的方法,但我确信有一种更简单的方法可以解决这个问题。

附件是我目前所拥有的。感谢观看!!

import javax.swing.JOptionPane;  //gui stuff
import java.util.Scanner; // Needed for accepting input
import java.text.*; //imports methods for text handling
import java.lang.Math.*; //needed for math stuff*

public class ProjectOneAndreD //my class + program name
{


public static void main(String[] args) //my main
{
String input1; //holds user input
int val=0, rad=0, check1=0; //holds integer values user gives
and check for : handler
double answer1=0; //holds the answer!


Scanner keyboard = new Scanner(System.in);
//creates new scanner class

do //will continue to loop if no : inputted
{
System.out.println("\t****************************************************");
System.out.println("\t Loading Project 1. Enjoy! "); //title
System.out.println("\t****************************************************\n\n");

input1 = JOptionPane.showInputDialog("INPUT: ","EXAMPLE: 160:2"); //prompts user with msgbox w/ example
System.out.println("Program Running..."); //gives user a secondary notice that everything is ok..

check1=input1.indexOf(":"); //checks input1 for the :

if(check1==-1) //if no : do this stuff
{
System.out.println("I think you forgot the ':'."); //let user know they forgot
JOptionPane.showMessageDialog(null, "You forgot the ':'!!!"); //another alert to user
}
else //otherwise is they remembered :
{
String numbers [] = input1.split(":"); //splits the string at :

val = Integer.parseInt(numbers[0]); //parses [0] to int and assigns to val
rad = Integer.parseInt(numbers[1]); //parses [1] to int and assigns to rad
//answer1 = ((Math.log(val))/(Math.log(rad))); //mathematically finds first base then
//answer1 = Integer.parseInt(val, rad, 10);

JOptionPane.showMessageDialog(null, val+" base "+rad+" = BLAH base 10."); //gives user the results
System.out.println("Program Terminated..."); //alerts user of program ending
}

}while(check1==-1); //if user forgot : loop

}
}

最佳答案

您可以使用 Integer.parseInt(s, radix)

answer = Integer.parseInt(numbers[0], rad);

您解析给定基数中的数字。

关于java - 如何找到 (x :g)?) 的基数 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com